# COMPREHENSIVE BOOKING SYSTEM & CMS - PROJECT BLUEPRINT

## 📋 PROJECT OVERVIEW

This document provides a complete blueprint for building an advanced booking system inspired by airporttaxis-uk.co.uk, including a full Content Management System (CMS) for managing all website content, images, and prices.

**Estimated Development Time**: 2-3 weeks for full implementation
**Current Status**: Database schema created, ready for implementation

---

## ✅ COMPLETED WORK

### 1. Database Schema Created
✓ **File**: `database/migrations/0005_cms_and_enhanced_booking.sql`
✓ **Tables Created**:
- `cms_content` - Homepage/page content management
- `cms_vehicles` - Vehicle fleet management
- `cms_pricing` - Pricing rules and extras
- `cms_airports` - Airport information database
- `cms_settings` - Website settings
- `cms_images` - Image gallery/uploads
- `bookings_enhanced` - Advanced booking system
- `quote_requests` - Manual quote requests
- `drivers` - Driver management

### 2. Default Data Seeded
✓ 6 default vehicles (Saloon, Executive, Estate, People Carrier, etc.)
✓ 10 major UK airports
✓ Default pricing rules
✓ CMS content sections
✓ Default settings

---

## 🎯 IMPLEMENTATION ROADMAP

### PHASE 1: ADVANCED BOOKING SYSTEM (Week 1)

#### 1.1 Enhanced Quote/Booking Page
**File to Create**: `public/booking-advanced.html`

**Features**:
```html
- Journey Type Selection:
  □ Airport to Address
  □ Address to Airport  
  □ Address to Address (Point-to-Point)

- Pickup Details:
  □ Journey type dropdown
  □ Airport selector (if applicable)
  □ Postcode/Address input
  □ Date picker
  □ Time picker
  □ Flight number (if airport pickup)

- Dropoff Details:
  □ Airport selector (if applicable)
  □ Postcode/Address input

- Passenger Details:
  □ Number of passengers (1-8)
  □ Number of luggage (0-10)
  □ Special requirements textarea

- Return Journey Option:
  □ Checkbox for return journey
  □ Return date/time fields (conditional)
  □ 10% discount applied automatically
```

**Key Features**:
1. **Instant Quote Button** - Calculate price instantly
2. **Manual Quote Button** - Send quote request to admin
3. **Vehicle Suggestion** - Auto-suggest based on passengers/luggage
4. **Distance Calculation** - Use existing DISTANCE_MATRIX or API
5. **Price Breakdown** - Show base fare + distance + extras

#### 1.2 Vehicle Selection Page
**File to Create**: `public/vehicle-selection.html`

**Features**:
- Display all suitable vehicles based on passenger/luggage count
- Vehicle cards with:
  - Image
  - Name & description
  - Capacity (passengers + luggage)
  - Features list
  - Price for this journey
  - "Select This Vehicle" button
- Filter options:
  - All Vehicles
  - Economy
  - Executive
  - Large Groups
- Sort by: Price, Capacity, Luxury

#### 1.3 Enhanced Booking Confirmation
**File to Update**: `public/booking.html`

**New Features**:
- Show selected vehicle details
- Show full journey summary
- Add extras checkboxes:
  □ Meet & Greet (£15)
  □ Child Car Seat (FREE)
  □ Additional luggage (+£5)
- Show return journey details if applicable
- Price breakdown table
- Terms & conditions checkbox
- Payment method selection

---

### PHASE 2: BACKEND API (Week 1-2)

#### 2.1 CMS API Routes
**File to Create**: `server/routes/cms.js`

```javascript
// Content Management
GET    /api/cms/content                  // Get all content
GET    /api/cms/content/:section         // Get content by section
PUT    /api/cms/content/:id              // Update content
POST   /api/cms/content                  // Create new content

// Vehicle Management
GET    /api/cms/vehicles                 // Get all vehicles
GET    /api/cms/vehicles/:id             // Get vehicle by ID
POST   /api/cms/vehicles                 // Create new vehicle
PUT    /api/cms/vehicles/:id             // Update vehicle
DELETE /api/cms/vehicles/:id             // Delete vehicle

// Pricing Management
GET    /api/cms/pricing                  // Get all pricing rules
POST   /api/cms/pricing                  // Create pricing rule
PUT    /api/cms/pricing/:id              // Update pricing rule
DELETE /api/cms/pricing/:id              // Delete pricing rule

// Airport Management
GET    /api/cms/airports                 // Get all airports
POST   /api/cms/airports                 // Create airport
PUT    /api/cms/airports/:id             // Update airport

// Settings Management
GET    /api/cms/settings                 // Get all settings
GET    /api/cms/settings/:key            // Get setting by key
PUT    /api/cms/settings/:key            // Update setting

// Image Upload
POST   /api/cms/images/upload            // Upload image
GET    /api/cms/images                   // Get all images
DELETE /api/cms/images/:id               // Delete image
```

#### 2.2 Enhanced Booking API
**File to Update**: `server/routes/bookings.js`

```javascript
// Enhanced Quote Calculation
POST   /api/bookings/quote               // Calculate instant quote
POST   /api/bookings/quote/manual        // Submit manual quote request

// Enhanced Booking
POST   /api/bookings/create-enhanced     // Create enhanced booking
GET    /api/bookings/enhanced/:id        // Get enhanced booking

// Vehicle Availability
GET    /api/bookings/vehicles/available  // Get available vehicles
POST   /api/bookings/vehicles/suggest    // Get vehicle suggestions
```

#### 2.3 Quote Request API
**File to Create**: `server/routes/quote-requests.js`

```javascript
GET    /api/quotes/requests              // Get all quote requests (admin)
GET    /api/quotes/requests/:id          // Get quote request by ID
POST   /api/quotes/requests              // Create quote request (customer)
PUT    /api/quotes/requests/:id/quote    // Admin submits quote
PUT    /api/quotes/requests/:id/status   // Update status
```

---

### PHASE 3: ADMIN CMS PANEL (Week 2)

#### 3.1 Admin Content Management
**File to Create**: `public/admin-cms-content.html`

**Features**:
- List all content sections (hero, features, about, etc.)
- Edit form for each section:
  - Title (text input)
  - Subtitle (text input)
  - Content (textarea or rich text editor)
  - Button text & link
  - Image upload
  - Active status toggle
  - Display order
- Live preview
- Save & publish button

**UI Components**:
```html
<div class="cms-section-card">
  <div class="section-header">
    <h3>Hero Section</h3>
    <span class="status-badge active">Active</span>
  </div>
  
  <form class="edit-form">
    <input type="text" name="title" placeholder="Title">
    <input type="text" name="subtitle" placeholder="Subtitle">
    <textarea name="content" placeholder="Content"></textarea>
    <input type="file" name="image" accept="image/*">
    <img src="/uploads/hero.jpg" class="preview">
    <button type="submit">Save Changes</button>
  </form>
</div>
```

#### 3.2 Admin Vehicle Management
**File to Create**: `public/admin-cms-vehicles.html`

**Features**:
- Vehicle list table with:
  - Image thumbnail
  - Name
  - Type
  - Capacity (passengers/luggage)
  - Base price
  - Price per mile
  - Status
  - Actions (Edit, Delete)
- "Add New Vehicle" button
- Edit/Create modal with form:
  - Vehicle name
  - Description
  - Image upload
  - Max passengers (number)
  - Max luggage (number)
  - Base price (£)
  - Price per mile (£)
  - Vehicle type (dropdown)
  - Features (tag input)
  - Active status
  - Display order

#### 3.3 Admin Pricing Management
**File to Create**: `public/admin-cms-pricing.html`

**Features**:
- Pricing rules table:
  - Rule name
  - Type (airport fee, extra service, discount)
  - Value (£ or %)
  - Applies to
  - Status
  - Actions
- "Add New Rule" button
- Edit form with:
  - Rule name
  - Rule type (dropdown)
  - Value (number)
  - Value type (fixed/percentage)
  - Description
  - Applicable to (multi-select)
  - Active status

**Example Rules**:
```
Meet & Greet Service    | Extra Service | £15.00   | Fixed
Child Car Seat          | Extra Service | £0.00    | Fixed  
Return Journey Discount | Discount      | 10%      | Percentage
Airport Parking Fee     | Airport Fee   | £5.00    | Fixed
```

#### 3.4 Admin Airport Management
**File to Create**: `public/admin-cms-airports.html`

**Features**:
- Airport list with:
  - Name
  - Code (MAN, LHR, etc.)
  - Postcode
  - Meet & Greet Fee
  - Status
- Add/Edit form
- Bulk import from CSV

#### 3.5 Admin Settings
**File to Create**: `public/admin-cms-settings.html`

**Categories**:

**Company Information**:
- Company name
- Address
- Registration number
- VAT number

**Contact Details**:
- Phone number
- Email address
- Booking email
- Support email

**Booking Settings**:
- Minimum advance hours
- Allow same-day booking
- Default currency
- Currency symbol
- Cancellation policy

**Social Media**:
- Facebook URL
- Twitter URL
- Instagram URL
- LinkedIn URL

**Email Settings**:
- SMTP host
- SMTP port
- SMTP username
- SMTP password
- From email
- From name

#### 3.6 Admin Image Gallery
**File to Create**: `public/admin-cms-images.html`

**Features**:
- Grid view of all uploaded images
- Upload button (multiple files)
- Image details:
  - Filename
  - Size
  - Upload date
  - Category
  - Alt text
- Actions: Copy URL, Edit, Delete
- Search/filter by category
- Categories:
  - Vehicle images
  - Hero images
  - Service images
  - Gallery images

---

### PHASE 4: IMAGE UPLOAD SYSTEM (Week 2)

#### 4.1 Backend Image Upload
**File to Create**: `server/middleware/upload.js`

```javascript
const multer = require('multer');
const path = require('path');
const fs = require('fs');

// Storage configuration
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadDir = path.join(__dirname, '../../public/uploads');
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname));
  }
});

// File filter
const fileFilter = (req, file, cb) => {
  const allowedTypes = /jpeg|jpg|png|gif|webp/;
  const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
  const mimetype = allowedTypes.test(file.mimetype);
  
  if (extname && mimetype) {
    cb(null, true);
  } else {
    cb(new Error('Only image files are allowed!'));
  }
};

// Export multer middleware
module.exports = multer({
  storage: storage,
  limits: { fileSize: 5 * 1024 * 1024 }, // 5MB limit
  fileFilter: fileFilter
});
```

#### 4.2 Image Upload Routes
**File to Update**: `server/routes/cms.js`

```javascript
const upload = require('../middleware/upload');

// Single image upload
router.post('/images/upload', 
  authMiddleware, 
  upload.single('image'), 
  async (req, res) => {
    try {
      const { category, alt_text } = req.body;
      const file = req.file;
      
      // Save to database
      const result = await db.run(
        `INSERT INTO cms_images 
        (filename, original_name, file_path, file_size, mime_type, category, alt_text, uploaded_by) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
        [
          file.filename,
          file.originalname,
          `/uploads/${file.filename}`,
          file.size,
          file.mimetype,
          category || 'general',
          alt_text || '',
          req.user.id
        ]
      );
      
      res.json({
        success: true,
        image: {
          id: result.lastID,
          url: `/uploads/${file.filename}`,
          filename: file.filename
        }
      });
    } catch (error) {
      res.status(500).json({ error: error.message });
    }
  }
);

// Multiple images upload
router.post('/images/upload-multiple', 
  authMiddleware, 
  upload.array('images', 10), 
  async (req, res) => {
    // Handle multiple file uploads
  }
);
```

---

### PHASE 5: FRONTEND INTEGRATION (Week 3)

#### 5.1 Dynamic Content Loading
**Update all pages to load content from CMS**

Example for homepage:
```javascript
// Load hero section
fetch('/api/cms/content/hero')
  .then(res => res.json())
  .then(data => {
    document.getElementById('hero-title').textContent = data.title;
    document.getElementById('hero-subtitle').textContent = data.subtitle;
    document.getElementById('hero-image').src = data.image_url;
  });

// Load vehicles
fetch('/api/cms/vehicles?active=1')
  .then(res => res.json())
  .then(vehicles => {
    const vehicleGrid = document.getElementById('vehicle-grid');
    vehicles.forEach(vehicle => {
      vehicleGrid.innerHTML += `
        <div class="vehicle-card">
          <img src="${vehicle.image_url}" alt="${vehicle.name}">
          <h3>${vehicle.name}</h3>
          <p>${vehicle.description}</p>
          <div class="capacity">
            <span>👤 ${vehicle.max_passengers}</span>
            <span>🧳 ${vehicle.max_luggage}</span>
          </div>
          <div class="price">From £${vehicle.base_price}</div>
        </div>
      `;
    });
  });
```

#### 5.2 Quote Calculator Integration
```javascript
async function calculateQuote() {
  const quoteData = {
    journey_type: document.getElementById('journey-type').value,
    pickup_location: document.getElementById('pickup').value,
    pickup_postcode: document.getElementById('pickup-postcode').value,
    dropoff_location: document.getElementById('dropoff').value,
    dropoff_postcode: document.getElementById('dropoff-postcode').value,
    pickup_date: document.getElementById('date').value,
    pickup_time: document.getElementById('time').value,
    passengers: parseInt(document.getElementById('passengers').value),
    luggage: parseInt(document.getElementById('luggage').value),
    meet_greet: document.getElementById('meet-greet').checked,
    is_return: document.getElementById('return-journey').checked
  };
  
  const response = await fetch('/api/bookings/quote', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(quoteData)
  });
  
  const quote = await response.json();
  
  // Display quote
  displayQuote(quote);
}

function displayQuote(quote) {
  document.getElementById('quote-result').innerHTML = `
    <h3>Your Quote</h3>
    <div class="quote-breakdown">
      <div class="line-item">
        <span>Base Fare</span>
        <span>£${quote.base_fare.toFixed(2)}</span>
      </div>
      <div class="line-item">
        <span>Distance (${quote.distance_miles} miles @ £${quote.price_per_mile}/mile)</span>
        <span>£${quote.distance_charge.toFixed(2)}</span>
      </div>
      ${quote.airport_fee > 0 ? `
        <div class="line-item">
          <span>Airport Fee</span>
          <span>£${quote.airport_fee.toFixed(2)}</span>
        </div>
      ` : ''}
      ${quote.meet_greet_fee > 0 ? `
        <div class="line-item">
          <span>Meet & Greet</span>
          <span>£${quote.meet_greet_fee.toFixed(2)}</span>
        </div>
      ` : ''}
      ${quote.discount_amount > 0 ? `
        <div class="line-item discount">
          <span>Return Journey Discount (${quote.discount_type})</span>
          <span>-£${quote.discount_amount.toFixed(2)}</span>
        </div>
      ` : ''}
      <div class="line-item total">
        <span><strong>Total Price</strong></span>
        <span><strong>£${quote.total_price.toFixed(2)}</strong></span>
      </div>
    </div>
    <div class="suggested-vehicles">
      <h4>Recommended Vehicles</h4>
      ${quote.suggested_vehicles.map(v => `
        <div class="vehicle-option">
          <img src="${v.image_url}" alt="${v.name}">
          <div class="vehicle-info">
            <h5>${v.name}</h5>
            <p>£${v.price_for_journey.toFixed(2)}</p>
          </div>
          <button onclick="selectVehicle(${v.id})">Select</button>
        </div>
      `).join('')}
    </div>
    <button class="btn-primary" onclick="proceedToBooking()">Book Now</button>
  `;
}
```

---

## 🎨 UI/UX IMPROVEMENTS

### Admin Panel Design
- **Sidebar Navigation**:
  - Dashboard
  - Content Management
  - Vehicle Management
  - Pricing Management
  - Airport Management
  - Image Gallery
  - Settings
  - Bookings
  - Quote Requests
  - Drivers

- **Consistent Cards**: All sections use card-based layout
- **Data Tables**: Sortable, searchable tables with pagination
- **Form Validation**: Client-side and server-side validation
- **Toast Notifications**: Success/error messages
- **Loading States**: Spinners while fetching data
- **Confirmation Modals**: For delete actions

### Customer-Facing Pages
- **Progress Indicator**: Show booking steps (Quote → Vehicle → Details → Confirm)
- **Vehicle Comparison**: Side-by-side vehicle comparison
- **Trust Badges**: Display certifications, reviews
- **Live Chat**: WhatsApp integration
- **Mobile Responsive**: All pages work on mobile

---

## 📦 DEPENDENCIES NEEDED

Add to `package.json`:
```json
{
  "dependencies": {
    "multer": "^1.4.5-lts.1",
    "sharp": "^0.33.0",
    "express-fileupload": "^1.4.3"
  }
}
```

---

## 🚀 DEPLOYMENT CHECKLIST

- [ ] Install multer for image uploads
- [ ] Create `/public/uploads/` directory
- [ ] Set proper permissions for uploads folder
- [ ] Configure CORS for API routes
- [ ] Test all API endpoints
- [ ] Test image upload functionality
- [ ] Backup database before going live
- [ ] Set up automated backups
- [ ] Configure SSL certificate
- [ ] Test on mobile devices

---

## 📝 NEXT STEPS

1. **Install dependencies**: `npm install multer sharp`
2. **Create uploads directory**: `mkdir -p public/uploads`
3. **Implement Phase 1**: Start with booking form
4. **Implement Phase 2**: Build API routes
5. **Implement Phase 3**: Build admin panels
6. **Test thoroughly**: Each feature as you build
7. **Deploy**: Follow deployment checklist

---

## 💡 TIPS FOR DEVELOPMENT

1. **Start Small**: Build one feature at a time
2. **Test Often**: Test each API endpoint as you build
3. **Use Postman**: Test API routes before building UI
4. **Version Control**: Commit after each feature
5. **Documentation**: Document API endpoints
6. **Error Handling**: Always handle errors gracefully
7. **Security**: Validate all inputs, sanitize data

---

## 📞 SUPPORT

This is a comprehensive blueprint. The actual implementation requires:
- 2-3 weeks of focused development
- Testing and refinement
- Security hardening
- Performance optimization

**Current Project State**:
- ✅ Database schema complete
- ✅ Migration files created
- ⏳ API routes need implementation
- ⏳ Admin UI needs implementation
- ⏳ Customer booking flow needs implementation

---

**Good luck with the implementation! This blueprint should give you everything you need to build a professional booking system with full CMS capabilities.** 🚀
