# RideShare Application - cPanel Deployment Guide

## 📋 Overview

This is a complete PHP + MySQL conversion of the RideShare application (originally Python/FastAPI + MongoDB). All features have been preserved including:

- User authentication (JWT-based)
- Ride booking and management
- Driver and Rider dashboards
- Admin panel
- Wallet system with holds, captures, and refunds
- Stripe payment integration
- Real-time ride matching
- State machine for rides and drivers

## 🎯 Requirements

- **cPanel Hosting** with:
  - PHP 7.4 or higher (PHP 8.x recommended)
  - MySQL 5.7 or higher (MySQL 8.x recommended)
  - Apache with mod_rewrite enabled
  - SSL certificate (for production)
  
- **PHP Extensions Required:**
  - PDO
  - PDO_MySQL
  - JSON
  - OpenSSL
  - cURL
  - mbstring

## 📦 Installation Steps

### Step 1: Database Setup

1. **Create MySQL Database:**
   - Log into cPanel
   - Go to "MySQL® Databases"
   - Create a new database (e.g., `yourusername_rideshare`)
   - Create a MySQL user with a strong password
   - Add the user to the database with ALL PRIVILEGES

2. **Import Database Schema:**
   - Go to phpMyAdmin in cPanel
   - Select your new database
   - Click "Import"
   - Upload the file: `database_setup.sql`
   - Click "Go" to execute

3. **Verify Tables Created:**
   You should see these tables:
   - users
   - rides
   - wallet_transactions
   - stripe_sessions
   - stripe_events
   - state_transitions
   - app_settings
   - custom_pages
   - push_subscriptions
   - visitor_tracking

### Step 2: Upload Files

**Option A: Using File Manager**
1. In cPanel, go to File Manager
2. Navigate to `public_html` (or your domain's document root)
3. Delete any existing `index.html` or files
4. Upload ALL files from the `php-rideshare` folder
5. Extract if uploaded as ZIP

**Option B: Using FTP**
1. Connect via FTP client (FileZilla recommended)
2. Upload all files to `public_html`

**Final Structure:**
```
public_html/
├── api/
│   ├── index.php
│   ├── auth.php
│   ├── rides.php
│   └── ...
├── config/
│   ├── config.php
│   └── database.php
├── includes/
│   ├── helpers.php
│   └── wallet.php
├── public/
│   ├── .htaccess
│   ├── index.html (React build)
│   ├── uploads/
│   └── static/ (React assets)
├── .env.example
└── database_setup.sql
```

### Step 3: Configuration

1. **Copy Environment File:**
   - Rename `.env.example` to `.env`
   - Or create a new `.env` file

2. **Edit `.env` File:**
```env
# Database Configuration
DB_HOST=localhost
DB_NAME=yourusername_rideshare
DB_USER=yourusername_dbuser
DB_PASS=your_secure_password

# JWT Secret (Generate a random 64-character string!)
JWT_SECRET=CHANGE_THIS_TO_RANDOM_STRING_GENERATED_SECURELY

# Stripe Keys (from https://dashboard.stripe.com/)
STRIPE_SECRET_KEY=sk_test_your_key_here
STRIPE_PUBLISHABLE_KEY=pk_test_your_key_here

# App Configuration
APP_URL=https://yourdomain.com
CORS_ALLOWED_ORIGINS=*
```

3. **Set File Permissions:**
```
chmod 755 api/
chmod 755 config/
chmod 755 includes/
chmod 777 public/uploads/
chmod 644 .env
```

### Step 4: Frontend Build (React)

The React frontend needs to be built before deployment:

**On your local machine:**
```bash
cd iphone-main/frontend
npm install
npm run build
```

**Upload build files:**
1. Copy contents of `build/` folder to `public_html/public/`
2. Ensure `index.html` is in the root of `public/`
3. Ensure `static/` folder with CSS/JS is present

**Update Frontend API URL:**
- Edit the built `index.html` or create a config
- Set `REACT_APP_BACKEND_URL` to your domain
- For cPanel: usually `https://yourdomain.com`

### Step 5: Test the Installation

1. **Test Database Connection:**
   Visit: `https://yourdomain.com/api/health`
   
   Expected response:
   ```json
   {
     "success": true,
     "message": "API is running",
     "data": {
       "status": "ok",
       "timestamp": 1234567890
     }
   }
   ```

2. **Test Authentication:**
   - Visit your domain homepage
   - Try to sign up as a new user
   - Login with the test account:
     - Email: `admin@rideshare.com`
     - Password: `admin123` (⚠️ CHANGE THIS IMMEDIATELY!)

3. **Change Default Admin Password:**
   ```sql
   UPDATE users 
   SET password = '$2y$10$YOUR_NEW_BCRYPT_HASH' 
   WHERE email = 'admin@rideshare.com';
   ```

## 🔐 Security Checklist

- [ ] Change JWT_SECRET to a random 64+ character string
- [ ] Change default admin password
- [ ] Set proper file permissions (755 for directories, 644 for files)
- [ ] Secure the .env file (should not be web-accessible)
- [ ] Enable SSL certificate (Let's Encrypt via cPanel)
- [ ] Update CORS_ALLOWED_ORIGINS to your specific domain
- [ ] Set up database backups in cPanel
- [ ] Disable PHP error display in production
- [ ] Review and restrict upload directory access

## 🎨 Graphics and Assets

All graphics, maps, and images from the original application are preserved:

- **Upload Directory:** `/public/uploads/`
  - Page images: `/public/uploads/page-images/`
  - APK files: `/public/uploads/apk-files/`

- **React Assets:** `/public/static/`
  - CSS, JS, and media files from React build

- **Maps:** Leaflet.js integration is maintained in React frontend

## ⚙️ Features Implemented

### ✅ Authentication System
- JWT-based authentication
- User signup/login
- Password reset
- Email verification
- Role-based access (Admin, Driver, Rider)

### ✅ Ride Management
- Create ride requests
- Match drivers with riders
- Real-time ride status updates
- Trip start/completion
- Cancellation with policies

### ✅ Wallet System
- Balance management
- Wallet holds before ride
- Fund capture after completion
- Automatic refunds
- Cancellation fee logic

### ✅ Stripe Integration
- Payment processing
- Checkout sessions
- Webhook handling
- Insufficient balance handling

### ✅ Driver Features
- Online/offline status
- Accept/decline rides
- Trip management
- Earnings tracking

### ✅ Rider Features
- Book rides
- Track driver location
- Wallet management
- Ride history

### ✅ Admin Features
- Dashboard
- User management
- Ride monitoring
- Settings configuration

## 🐛 Troubleshooting

### "500 Internal Server Error"
- Check `.htaccess` syntax
- Verify PHP version compatibility
- Check error logs in cPanel (Error Log viewer)
- Ensure mod_rewrite is enabled

### "Database connection failed"
- Verify .env database credentials
- Check if database user has privileges
- Confirm database name is correct
- Test connection in phpMyAdmin

### "API endpoint not found"
- Verify .htaccess is uploaded correctly
- Check file permissions
- Clear browser cache
- Test direct API URL: `/api/health`

### Frontend not loading
- Verify React build files are uploaded
- Check index.html is in public root
- Verify REACT_APP_BACKEND_URL is correct
- Check browser console for errors

### Uploads not working
- Check `uploads/` directory permissions (777)
- Verify PHP upload_max_filesize setting
- Check disk space quota in cPanel

## 📞 API Endpoints

### Authentication
- `POST /api/auth/signup` - Register new user
- `POST /api/auth/login` - Login
- `GET /api/auth/me` - Get current user
- `POST /api/auth/forgot-password` - Request password reset
- `POST /api/auth/reset-password` - Reset password

### Rides
- `POST /api/rides` - Create new ride
- `GET /api/rides` - Get user's rides
- `GET /api/rides/{id}` - Get ride details
- `GET /api/rides/available` - Get available rides (driver)
- `GET /api/rides/active` - Get active ride
- `POST /api/rides/{id}/accept` - Accept ride (driver)
- `POST /api/rides/{id}/start` - Start trip (driver)
- `POST /api/rides/{id}/complete` - Complete trip (driver)
- `POST /api/rides/{id}/cancel` - Cancel ride

### Wallet
- `GET /api/wallet/balance` - Get wallet balance
- `POST /api/wallet/add-funds` - Add funds to wallet

### Admin
- `GET /api/admin/users` - List users
- `GET /api/admin/stats` - Get statistics
- `PUT /api/admin/settings` - Update settings

## 📊 Database Schema

See `database_setup.sql` for complete schema. Key tables:

- **users**: All user accounts (riders, drivers, admin)
- **rides**: Ride requests and trips
- **wallet_transactions**: Wallet operations log
- **stripe_sessions**: Stripe payment sessions
- **state_transitions**: Audit log for state changes

## 🔄 Maintenance

### Regular Backups
- Use cPanel Backup Wizard
- Export database via phpMyAdmin
- Download `uploads/` directory

### Monitoring
- Check error logs regularly: `/logs/php_errors.log`
- Monitor disk space usage
- Review database size
- Check SSL certificate expiration

### Updates
- Keep PHP version updated
- Update MySQL if available
- Review security patches
- Test in staging before production updates

## 📝 Default Admin Access

**⚠️ CHANGE IMMEDIATELY AFTER FIRST LOGIN!**

- Email: `admin@rideshare.com`
- Password: `admin123`

## 🎉 Deployment Complete!

Your RideShare application is now running on cPanel with PHP and MySQL!

For support or issues, check:
- Error logs in cPanel
- PHP error log
- Browser console
- Network tab in developer tools

**Important:** Test all features thoroughly before going live!
