const db = require('../config/database');

const generateOrderNumber = () => {
  return 'ORD-' + Date.now() + '-' + Math.floor(Math.random() * 1000);
};

exports.createOrder = async (req, res) => {
  try {
    const {
      tour_id,
      tour_date,
      number_of_people,
      customer_name,
      customer_email,
      customer_phone,
      special_requests
    } = req.body;

    // Validate number_of_people format and limits
    if (number_of_people && typeof number_of_people === 'object') {
      const { adults = 0, children = 0, infants = 0 } = number_of_people;

      // Validate limits
      if (adults < 1 || adults > 4) {
        return res.status(400).json({ message: 'Yetişkin sayısı 1-4 arasında olmalıdır' });
      }
      if (children < 0 || children > 6) {
        return res.status(400).json({ message: 'Çocuk sayısı 0-6 arasında olmalıdır' });
      }
      if (infants < 0 || infants > 4) {
        return res.status(400).json({ message: 'Bebek sayısı 0-4 arasında olmalıdır' });
      }

      // Toplam kişi kontrolü
      const totalPeople = adults + children + infants;
      if (totalPeople > 15) {
        return res.status(400).json({ message: 'Toplam kişi sayısı 15\'i geçemez' });
      }
    }

    const [tours] = await db.query('SELECT * FROM tours WHERE id = ?', [tour_id]);

    if (tours.length === 0) {
      return res.status(404).json({ message: 'Tur bulunamadı' });
    }

    const tour = tours[0];
    const total_price = tour.price * number_of_people;
    const order_number = generateOrderNumber();

    let customer_id = null;
    const [existingCustomers] = await db.query(
      'SELECT id FROM customers WHERE email = ?',
      [customer_email]
    );

    if (existingCustomers.length > 0) {
      customer_id = existingCustomers[0].id;
    } else {
      const [customerResult] = await db.query(
        'INSERT INTO customers (full_name, email, phone) VALUES (?, ?, ?)',
        [customer_name, customer_email, customer_phone]
      );
      customer_id = customerResult.insertId;
    }

    const [result] = await db.query(
      `INSERT INTO orders (order_number, customer_id, tour_id, tour_date, number_of_people,
       total_price, customer_name, customer_email, customer_phone, special_requests,
       payment_status, booking_status)
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', 'pending')`,
      [
        order_number,
        customer_id,
        tour_id,
        tour_date,
        number_of_people,
        total_price,
        customer_name,
        customer_email,
        customer_phone,
        special_requests
      ]
    );

    res.status(201).json({
      message: 'Sipariş başarıyla oluşturuldu',
      order: {
        id: result.insertId,
        order_number,
        total_price
      }
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Sunucu hatası' });
  }
};

exports.getAllOrders = async (req, res) => {
  try {
    const { booking_status, payment_status } = req.query;
    let query = `
      SELECT o.*, t.title as tour_title, t.location as tour_location
      FROM orders o
      LEFT JOIN tours t ON o.tour_id = t.id
      WHERE 1=1
    `;
    const params = [];

    if (booking_status) {
      query += ' AND o.booking_status = ?';
      params.push(booking_status);
    }

    if (payment_status) {
      query += ' AND o.payment_status = ?';
      params.push(payment_status);
    }

    query += ' ORDER BY o.created_at DESC';

    const [orders] = await db.query(query, params);
    res.json(orders);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Sunucu hatası' });
  }
};

exports.getOrderById = async (req, res) => {
  try {
    const [orders] = await db.query(
      `SELECT o.*, t.title as tour_title, t.description as tour_description,
       t.location as tour_location, t.duration as tour_duration
       FROM orders o
       LEFT JOIN tours t ON o.tour_id = t.id
       WHERE o.id = ?`,
      [req.params.id]
    );

    if (orders.length === 0) {
      return res.status(404).json({ message: 'Sipariş bulunamadı' });
    }

    res.json(orders[0]);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Sunucu hatası' });
  }
};

exports.updateOrderStatus = async (req, res) => {
  try {
    const { booking_status, payment_status } = req.body;

    const updateFields = [];
    const params = [];

    if (booking_status) {
      updateFields.push('booking_status = ?');
      params.push(booking_status);
    }

    if (payment_status) {
      updateFields.push('payment_status = ?');
      params.push(payment_status);
    }

    if (updateFields.length === 0) {
      return res.status(400).json({ message: 'Güncellenecek alan bulunamadı' });
    }

    params.push(req.params.id);

    const [result] = await db.query(
      `UPDATE orders SET ${updateFields.join(', ')} WHERE id = ?`,
      params
    );

    if (result.affectedRows === 0) {
      return res.status(404).json({ message: 'Sipariş bulunamadı' });
    }

    res.json({ message: 'Sipariş durumu güncellendi' });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Sunucu hatası' });
  }
};

exports.deleteOrder = async (req, res) => {
  try {
    const [result] = await db.query('DELETE FROM orders WHERE id = ?', [req.params.id]);

    if (result.affectedRows === 0) {
      return res.status(404).json({ message: 'Sipariş bulunamadı' });
    }

    res.json({ message: 'Sipariş silindi' });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Sunucu hatası' });
  }
};
