# PHP Server Deployment Guide

## Overview

The server has been converted from Node.js to PHP for easier deployment on shared hosting platforms like Namecheap.

## File Structure

```
server/
├── booking.php          # Booking form endpoint handler
├── contact.php          # Contact form endpoint handler
├── health.php           # Health check endpoint
├── config.php           # Configuration loader
├── .htaccess            # Apache routing configuration
├── .env                 # Environment variables (create this)
└── PHP_DEPLOYMENT_GUIDE.md
```

## Features

- ✅ Native PHP mail() function (no dependencies)
- ✅ Beautiful HTML email templates
- ✅ CORS enabled
- ✅ Error handling and logging
- ✅ Input validation and sanitization
- ✅ French language support

## Setup Instructions

### 1. Create .env File

Create a `.env` file in the `server/` directory:

```env
# Email Configuration
SMTP_HOST=mail.taxiagadirairport.com
SMTP_PORT=587
EMAIL_USER=info@taxiagadirairport.com
EMAIL_PASS=your_password_here

# Server Configuration (optional)
PORT=5000
NODE_ENV=production
```

### 2. Configure PHP mail() Function

On shared hosting, you may need to configure the mail function:

#### Option A: Using php.ini (if you have access)

Create or edit `php.ini` in your server directory:

```ini
[mail function]
SMTP = mail.taxiagadirairport.com
smtp_port = 587
sendmail_from = info@taxiagadirairport.com
sendmail_path = /usr/sbin/sendmail -t -i
```

#### Option B: Using .user.ini (for shared hosting)

Create `.user.ini` in your server directory:

```ini
sendmail_path = /usr/sbin/sendmail -t -i
```

#### Option C: Hosting Panel Configuration

Most shared hosting providers allow you to configure SMTP settings through their control panel (cPanel, Plesk, etc.).

### 3. File Permissions

Set proper file permissions:

```bash
# Set permissions for PHP files
chmod 644 *.php
chmod 644 .htaccess

# Set permissions for config file
chmod 600 .env

# Ensure server directory is writable for logs
chmod 755 .
```

### 4. Upload Files

Upload all files to your hosting:

```
public_html/
├── index.html (your React app)
├── assets/ (your React build files)
└── api/ or server/
    ├── booking.php
    ├── contact.php
    ├── health.php
    ├── config.php
    ├── .htaccess
    └── .env
```

**Note:** Adjust the API paths based on your folder structure.

### 5. Update Frontend API URLs

Update your React components to point to the PHP server:

**For BookingForm.tsx and Contact.tsx:**

```javascript
// Change from Railway to your domain
const apiUrl = window.location.hostname === 'localhost' 
    ? 'http://localhost/api'
    : 'https://taxiagadirairport.com/api';
```

Or use relative paths:

```javascript
const apiUrl = '/api';
```

### 6. Test the API

#### Test Booking Endpoint

```bash
curl -X POST https://yourdomain.com/api/booking \
  -H "Content-Type: application/json" \
  -d '{
    "from": "agadir_airport",
    "to": "hotel_agadir",
    "arrival-date": "2024-12-31T12:00",
    "fullname": "Test User",
    "email": "test@example.com",
    "phone": "+212600000000",
    "address": "Test Hotel",
    "passengers": "2",
    "trip-type": "round-trip"
  }'
```

#### Test Contact Endpoint

```bash
curl -X POST https://yourdomain.com/api/contact \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Test User",
    "email": "test@example.com",
    "phone": "+212600000000",
    "subject": "Test Subject",
    "message": "Test message"
  }'
```

#### Test Health Check

Visit: `https://yourdomain.com/api/health`

Should return:
```json
{
  "status": "OK",
  "message": "PHP server is running",
  "php_version": "7.4.x",
  "timestamp": "2024-12-31T12:00:00+00:00"
}
```

## Troubleshooting

### Emails Not Sending

1. **Check PHP mail configuration:**
   ```php
   <?php
   phpinfo();
   ?>
   ```
   Look for "mail function" settings.

2. **Check error logs:**
   - Look in your hosting control panel's error log
   - Check `/var/log/php_errors.log` or similar

3. **Test mail function:**
   ```php
   <?php
   $test = mail('test@example.com', 'Test', 'Test message');
   var_dump($test);
   ?>
   ```

4. **Contact your hosting provider:**
   Some shared hosting requires verification before sending emails.

### CORS Issues

If you see CORS errors, check your `.htaccess` file includes:

```apache
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "GET, POST, OPTIONS"
Header always set Access-Control-Allow-Headers "Content-Type"
```

### File Not Found Errors

1. Check `.htaccess` rewrite rules
2. Ensure mod_rewrite is enabled on Apache
3. Verify file paths are correct

### 500 Internal Server Error

1. Check file permissions
2. Look for syntax errors in PHP files
3. Check error logs in hosting control panel
4. Verify `.htaccess` syntax

## Environment Variables

You can set environment variables in three ways:

1. **`.env` file** (recommended for development)
2. **Hosting control panel** (for production)
3. **`.htaccess`** using SetEnv:
   ```apache
   SetEnv SMTP_HOST mail.taxiagadirairport.com
   SetEnv EMAIL_USER info@taxiagadirairport.com
   ```

## Security Recommendations

1. **Protect .env file:**
   ```apache
   <FilesMatch "^\.env">
       Require all denied
   </FilesMatch>
   ```

2. **Input Validation:**
   - Already implemented in booking.php and contact.php
   - All inputs are sanitized using `htmlspecialchars()`
   - Email validation using `filter_var()`

3. **Rate Limiting:**
   Consider adding rate limiting to prevent spam:
   ```php
   // Simple rate limiting example
   $rateLimitFile = __DIR__ . '/rate_limit.txt';
   $rateLimit = file_get_contents($rateLimitFile);
   $count = $rateLimit > time() - 3600 ? $rateLimit : 0;
   
   if ($count > 10) {
       http_response_code(429);
       echo json_encode(['error' => 'Too many requests']);
       exit();
   }
   
   file_put_contents($rateLimitFile, time());
   ```

## Differences from Node.js Version

| Feature | Node.js | PHP |
|---------|---------|-----|
| Email | Nodemailer | Native mail() |
| Dependencies | npm packages | None |
| Server | Express | Apache + PHP |
| Deployment | Railway/Vercel | Shared Hosting |
| Configuration | .env with dotenv | .env + config.php |

## Next Steps

1. Test all forms thoroughly
2. Monitor error logs for the first week
3. Set up email delivery monitoring
4. Consider adding rate limiting
5. Add SSL certificate if not already installed

## Support

For issues or questions:
- Check error logs first
- Review this guide's troubleshooting section
- Contact your hosting provider
- Review PHP and Apache documentation

## Additional Resources

- [PHP mail() documentation](https://www.php.net/manual/en/function.mail.php)
- [Apache .htaccess guide](https://httpd.apache.org/docs/current/howto/htaccess.html)
- [Namecheap hosting documentation](https://www.namecheap.com/support/knowledgebase/hosting/)
