const express = require('express');
const router = express.Router();
const database = require('../config/database');
const { auth, isAdmin } = require('../middleware/auth');

// Helper to get db instance
const getDb = () => database.db;

// ============================================
// VEHICLE MANAGEMENT API
// ============================================

// GET /api/cms/vehicles - List all vehicles
router.get('/vehicles', (req, res) => {
  try {
    const query = `
      SELECT * FROM cms_vehicles 
      ORDER BY display_order ASC, id ASC
    `;
    
    getDb().all(query, [], (err, rows) => {
      if (err) {
        console.error('Error fetching vehicles:', err);
        return res.status(500).json({ error: 'Failed to fetch vehicles' });
      }
      
      // Parse features JSON
      const vehicles = rows.map(v => ({
        ...v,
        features: v.features ? JSON.parse(v.features) : []
      }));
      
      res.json({ success: true, vehicles });
    });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// GET /api/cms/vehicles/active - List active vehicles only
router.get('/vehicles/active', (req, res) => {
  try {
    const query = `
      SELECT * FROM cms_vehicles 
      WHERE is_active = 1
      ORDER BY display_order ASC, id ASC
    `;
    
    getDb().all(query, [], (err, rows) => {
      if (err) {
        console.error('Error fetching active vehicles:', err);
        return res.status(500).json({ error: 'Failed to fetch vehicles' });
      }
      
      const vehicles = rows.map(v => ({
        ...v,
        features: v.features ? JSON.parse(v.features) : []
      }));
      
      res.json({ success: true, vehicles });
    });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// GET /api/cms/vehicles/:id - Get single vehicle
router.get('/vehicles/:id', (req, res) => {
  try {
    const { id } = req.params;
    
    getDb().get('SELECT * FROM cms_vehicles WHERE id = ?', [id], (err, row) => {
      if (err) {
        console.error('Error fetching vehicle:', err);
        return res.status(500).json({ error: 'Failed to fetch vehicle' });
      }
      
      if (!row) {
        return res.status(404).json({ error: 'Vehicle not found' });
      }
      
      const vehicle = {
        ...row,
        features: row.features ? JSON.parse(row.features) : []
      };
      
      res.json({ success: true, vehicle });
    });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// POST /api/cms/vehicles - Add new vehicle (Admin only)
router.post('/vehicles', auth, isAdmin, (req, res) => {
  try {
    const {
      name,
      description,
      max_passengers,
      max_luggage,
      vehicle_type,
      base_price,
      price_per_mile,
      image_url,
      features,
      is_active,
      display_order
    } = req.body;
    
    // Validation
    if (!name || !max_passengers || !max_luggage || !base_price || !price_per_mile) {
      return res.status(400).json({ error: 'Missing required fields' });
    }
    
    const query = `
      INSERT INTO cms_vehicles (
        name, description, max_passengers, max_luggage, vehicle_type,
        base_price, price_per_mile, image_url, features, is_active, display_order
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `;
    
    const featuresJson = features ? JSON.stringify(features) : JSON.stringify([]);
    
    getDb().run(query, [
      name,
      description || '',
      max_passengers,
      max_luggage,
      vehicle_type || 'standard',
      base_price,
      price_per_mile,
      image_url || '',
      featuresJson,
      is_active !== undefined ? is_active : 1,
      display_order || 0
    ], function(err) {
      if (err) {
        console.error('Error adding vehicle:', err);
        return res.status(500).json({ error: 'Failed to add vehicle' });
      }
      
      res.json({ 
        success: true, 
        message: 'Vehicle added successfully',
        vehicleId: this.lastID 
      });
    });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// PUT /api/cms/vehicles/:id - Update vehicle (Admin only)
router.put('/vehicles/:id', auth, isAdmin, (req, res) => {
  try {
    const { id } = req.params;
    const {
      name,
      description,
      max_passengers,
      max_luggage,
      vehicle_type,
      base_price,
      price_per_mile,
      image_url,
      features,
      is_active,
      display_order
    } = req.body;
    
    const query = `
      UPDATE cms_vehicles 
      SET name = ?, description = ?, max_passengers = ?, max_luggage = ?,
          vehicle_type = ?, base_price = ?, price_per_mile = ?, image_url = ?,
          features = ?, is_active = ?, display_order = ?, updated_at = CURRENT_TIMESTAMP
      WHERE id = ?
    `;
    
    const featuresJson = features ? JSON.stringify(features) : JSON.stringify([]);
    
    getDb().run(query, [
      name,
      description || '',
      max_passengers,
      max_luggage,
      vehicle_type || 'standard',
      base_price,
      price_per_mile,
      image_url || '',
      featuresJson,
      is_active !== undefined ? is_active : 1,
      display_order || 0,
      id
    ], function(err) {
      if (err) {
        console.error('Error updating vehicle:', err);
        return res.status(500).json({ error: 'Failed to update vehicle' });
      }
      
      if (this.changes === 0) {
        return res.status(404).json({ error: 'Vehicle not found' });
      }
      
      res.json({ 
        success: true, 
        message: 'Vehicle updated successfully' 
      });
    });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// DELETE /api/cms/vehicles/:id - Delete vehicle (Admin only)
router.delete('/vehicles/:id', auth, isAdmin, (req, res) => {
  try {
    const { id } = req.params;
    
    getDb().run('DELETE FROM cms_vehicles WHERE id = ?', [id], function(err) {
      if (err) {
        console.error('Error deleting vehicle:', err);
        return res.status(500).json({ error: 'Failed to delete vehicle' });
      }
      
      if (this.changes === 0) {
        return res.status(404).json({ error: 'Vehicle not found' });
      }
      
      res.json({ 
        success: true, 
        message: 'Vehicle deleted successfully' 
      });
    });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// ============================================
// AIRPORT MANAGEMENT API
// ============================================

// GET /api/cms/airports - List all airports
router.get('/airports', (req, res) => {
  try {
    const query = 'SELECT * FROM cms_airports ORDER BY name ASC';
    
    getDb().all(query, [], (err, rows) => {
      if (err) {
        console.error('Error fetching airports:', err);
        return res.status(500).json({ error: 'Failed to fetch airports' });
      }
      
      res.json({ success: true, airports: rows });
    });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// GET /api/cms/airports/active - List active airports
router.get('/airports/active', (req, res) => {
  try {
    const query = 'SELECT * FROM cms_airports WHERE is_active = 1 ORDER BY name ASC';
    
    getDb().all(query, [], (err, rows) => {
      if (err) {
        console.error('Error fetching active airports:', err);
        return res.status(500).json({ error: 'Failed to fetch airports' });
      }
      
      res.json({ success: true, airports: rows });
    });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// POST /api/cms/airports - Add new airport (Admin only)
router.post('/airports', auth, isAdmin, (req, res) => {
  try {
    const { code, name, postcode, address, meet_greet_fee, parking_fee, is_active } = req.body;
    
    if (!code || !name) {
      return res.status(400).json({ error: 'Code and name are required' });
    }
    
    const query = `
      INSERT INTO cms_airports (code, name, postcode, address, meet_greet_fee, parking_fee, is_active)
      VALUES (?, ?, ?, ?, ?, ?, ?)
    `;
    
    getDb().run(query, [
      code,
      name,
      postcode || '',
      address || '',
      meet_greet_fee || 15.00,
      parking_fee || 0.00,
      is_active !== undefined ? is_active : 1
    ], function(err) {
      if (err) {
        console.error('Error adding airport:', err);
        return res.status(500).json({ error: 'Failed to add airport' });
      }
      
      res.json({ 
        success: true, 
        message: 'Airport added successfully',
        airportId: this.lastID 
      });
    });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// PUT /api/cms/airports/:id - Update airport (Admin only)
router.put('/airports/:id', auth, isAdmin, (req, res) => {
  try {
    const { id } = req.params;
    const { code, name, postcode, address, meet_greet_fee, parking_fee, is_active } = req.body;
    
    const query = `
      UPDATE cms_airports 
      SET code = ?, name = ?, postcode = ?, address = ?, 
          meet_greet_fee = ?, parking_fee = ?, is_active = ?
      WHERE id = ?
    `;
    
    getDb().run(query, [
      code,
      name,
      postcode || '',
      address || '',
      meet_greet_fee || 15.00,
      parking_fee || 0.00,
      is_active !== undefined ? is_active : 1,
      id
    ], function(err) {
      if (err) {
        console.error('Error updating airport:', err);
        return res.status(500).json({ error: 'Failed to update airport' });
      }
      
      if (this.changes === 0) {
        return res.status(404).json({ error: 'Airport not found' });
      }
      
      res.json({ 
        success: true, 
        message: 'Airport updated successfully' 
      });
    });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// DELETE /api/cms/airports/:id - Delete airport (Admin only)
router.delete('/airports/:id', auth, isAdmin, (req, res) => {
  try {
    const { id } = req.params;
    
    getDb().run('DELETE FROM cms_airports WHERE id = ?', [id], function(err) {
      if (err) {
        console.error('Error deleting airport:', err);
        return res.status(500).json({ error: 'Failed to delete airport' });
      }
      
      if (this.changes === 0) {
        return res.status(404).json({ error: 'Airport not found' });
      }
      
      res.json({ 
        success: true, 
        message: 'Airport deleted successfully' 
      });
    });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// ============================================
// PRICING RULES MANAGEMENT API
// ============================================

// GET /api/cms/pricing - List all pricing rules
router.get('/pricing', (req, res) => {
  try {
    const query = 'SELECT * FROM cms_pricing ORDER BY id ASC';
    
    getDb().all(query, [], (err, rows) => {
      if (err) {
        console.error('Error fetching pricing rules:', err);
        return res.status(500).json({ error: 'Failed to fetch pricing rules' });
      }
      
      res.json({ success: true, pricing: rows });
    });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// POST /api/cms/pricing - Add pricing rule (Admin only)
router.post('/pricing', auth, isAdmin, (req, res) => {
  try {
    const { rule_name, rule_type, value, value_type, applicable_to, description, is_active } = req.body;
    
    if (!rule_name || !rule_type || !value || !value_type) {
      return res.status(400).json({ error: 'Missing required fields' });
    }
    
    const query = `
      INSERT INTO cms_pricing (rule_name, rule_type, value, value_type, applicable_to, description, is_active)
      VALUES (?, ?, ?, ?, ?, ?, ?)
    `;
    
    getDb().run(query, [
      rule_name,
      rule_type,
      value,
      value_type,
      applicable_to || '',
      description || '',
      is_active !== undefined ? is_active : 1
    ], function(err) {
      if (err) {
        console.error('Error adding pricing rule:', err);
        return res.status(500).json({ error: 'Failed to add pricing rule' });
      }
      
      res.json({ 
        success: true, 
        message: 'Pricing rule added successfully',
        ruleId: this.lastID 
      });
    });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// PUT /api/cms/pricing/:id - Update pricing rule (Admin only)
router.put('/pricing/:id', auth, isAdmin, (req, res) => {
  try {
    const { id } = req.params;
    const { rule_name, rule_type, value, value_type, applicable_to, description, is_active } = req.body;
    
    const query = `
      UPDATE cms_pricing 
      SET rule_name = ?, rule_type = ?, value = ?, value_type = ?, 
          applicable_to = ?, description = ?, is_active = ?, updated_at = CURRENT_TIMESTAMP
      WHERE id = ?
    `;
    
    getDb().run(query, [
      rule_name,
      rule_type,
      value,
      value_type,
      applicable_to || '',
      description || '',
      is_active !== undefined ? is_active : 1,
      id
    ], function(err) {
      if (err) {
        console.error('Error updating pricing rule:', err);
        return res.status(500).json({ error: 'Failed to update pricing rule' });
      }
      
      if (this.changes === 0) {
        return res.status(404).json({ error: 'Pricing rule not found' });
      }
      
      res.json({ 
        success: true, 
        message: 'Pricing rule updated successfully' 
      });
    });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// DELETE /api/cms/pricing/:id - Delete pricing rule (Admin only)
router.delete('/pricing/:id', auth, isAdmin, (req, res) => {
  try {
    const { id } = req.params;
    
    getDb().run('DELETE FROM cms_pricing WHERE id = ?', [id], function(err) {
      if (err) {
        console.error('Error deleting pricing rule:', err);
        return res.status(500).json({ error: 'Failed to delete pricing rule' });
      }
      
      if (this.changes === 0) {
        return res.status(404).json({ error: 'Pricing rule not found' });
      }
      
      res.json({ 
        success: true, 
        message: 'Pricing rule deleted successfully' 
      });
    });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// ============================================
// SETTINGS MANAGEMENT API
// ============================================

// GET /api/cms/settings - Get all settings
router.get('/settings', (req, res) => {
  try {
    const query = 'SELECT * FROM cms_settings ORDER BY category, setting_key';
    
    getDb().all(query, [], (err, rows) => {
      if (err) {
        console.error('Error fetching settings:', err);
        return res.status(500).json({ error: 'Failed to fetch settings' });
      }
      
      res.json({ success: true, settings: rows });
    });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// GET /api/cms/settings/:key - Get single setting
router.get('/settings/:key', (req, res) => {
  try {
    const { key } = req.params;
    
    getDb().get('SELECT * FROM cms_settings WHERE setting_key = ?', [key], (err, row) => {
      if (err) {
        console.error('Error fetching setting:', err);
        return res.status(500).json({ error: 'Failed to fetch setting' });
      }
      
      if (!row) {
        return res.status(404).json({ error: 'Setting not found' });
      }
      
      res.json({ success: true, setting: row });
    });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// PUT /api/cms/settings/:key - Update setting (Admin only)
router.put('/settings/:key', auth, isAdmin, (req, res) => {
  try {
    const { key } = req.params;
    const { value } = req.body;
    
    if (value === undefined) {
      return res.status(400).json({ error: 'Value is required' });
    }
    
    const query = `
      UPDATE cms_settings 
      SET setting_value = ?, updated_at = CURRENT_TIMESTAMP
      WHERE setting_key = ?
    `;
    
    getDb().run(query, [value, key], function(err) {
      if (err) {
        console.error('Error updating setting:', err);
        return res.status(500).json({ error: 'Failed to update setting' });
      }
      
      if (this.changes === 0) {
        return res.status(404).json({ error: 'Setting not found' });
      }
      
      res.json({ 
        success: true, 
        message: 'Setting updated successfully' 
      });
    });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// ============================================
// CONTENT MANAGEMENT API
// ============================================

// GET /api/cms/content - Get all content
router.get('/content', (req, res) => {
  try {
    const query = 'SELECT * FROM cms_content WHERE is_active = 1 ORDER BY section, display_order';
    
    getDb().all(query, [], (err, rows) => {
      if (err) {
        console.error('Error fetching content:', err);
        return res.status(500).json({ error: 'Failed to fetch content' });
      }
      
      res.json({ success: true, content: rows });
    });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// GET /api/cms/content/:section - Get content by section
router.get('/content/:section', (req, res) => {
  try {
    const { section } = req.params;
    
    const query = 'SELECT * FROM cms_content WHERE section = ? AND is_active = 1 ORDER BY display_order';
    
    getDb().all(query, [section], (err, rows) => {
      if (err) {
        console.error('Error fetching content:', err);
        return res.status(500).json({ error: 'Failed to fetch content' });
      }
      
      res.json({ success: true, content: rows });
    });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

// PUT /api/cms/content/:id - Update content (Admin only)
router.put('/content/:id', auth, isAdmin, (req, res) => {
  try {
    const { id } = req.params;
    const { section, title, subtitle, content, button_text, button_link, image_url, is_active, display_order } = req.body;
    
    const query = `
      UPDATE cms_content 
      SET section = ?, title = ?, subtitle = ?, content = ?, 
          button_text = ?, button_link = ?, image_url = ?, 
          is_active = ?, display_order = ?, updated_at = CURRENT_TIMESTAMP,
          updated_by = ?
      WHERE id = ?
    `;
    
    getDb().run(query, [
      section,
      title || '',
      subtitle || '',
      content || '',
      button_text || '',
      button_link || '',
      image_url || '',
      is_active !== undefined ? is_active : 1,
      display_order || 0,
      req.user.id,
      id
    ], function(err) {
      if (err) {
        console.error('Error updating content:', err);
        return res.status(500).json({ error: 'Failed to update content' });
      }
      
      if (this.changes === 0) {
        return res.status(404).json({ error: 'Content not found' });
      }
      
      res.json({ 
        success: true, 
        message: 'Content updated successfully' 
      });
    });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

module.exports = router;
