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

exports.getAllTours = async (req, res) => {
  try {
    const { status, featured } = req.query;
    let query = 'SELECT * FROM tours WHERE 1=1';
    const params = [];

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

    if (featured) {
      query += ' AND featured = ?';
      params.push(featured === 'true' ? 1 : 0);
    }

    query += ' ORDER BY created_at DESC';

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

exports.getTourById = async (req, res) => {
  try {
    const [tours] = await db.query('SELECT * FROM tours WHERE id = ?', [req.params.id]);

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

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

exports.createTour = async (req, res) => {
  try {
    const {
      title,
      description,
      short_description,
      price,
      duration,
      location,
      image_url,
      gallery,
      max_people,
      included_services,
      excluded_services,
      itinerary,
      available_dates,
      status,
      featured
    } = req.body;

    const [result] = await db.query(
      `INSERT INTO tours (title, description, short_description, price, duration, location,
       image_url, gallery, max_people, included_services, excluded_services, itinerary,
       available_dates, status, featured)
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [
        title,
        description,
        short_description,
        price,
        duration,
        location,
        image_url,
        JSON.stringify(gallery || []),
        max_people || 10,
        JSON.stringify(included_services || []),
        JSON.stringify(excluded_services || []),
        JSON.stringify(itinerary || []),
        JSON.stringify(available_dates || []),
        status || 'active',
        featured || false
      ]
    );

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

exports.updateTour = async (req, res) => {
  try {
    const {
      title,
      description,
      short_description,
      price,
      duration,
      location,
      image_url,
      gallery,
      max_people,
      included_services,
      excluded_services,
      itinerary,
      available_dates,
      status,
      featured
    } = req.body;

    const [result] = await db.query(
      `UPDATE tours SET
       title = ?, description = ?, short_description = ?, price = ?, duration = ?,
       location = ?, image_url = ?, gallery = ?, max_people = ?, included_services = ?,
       excluded_services = ?, itinerary = ?, available_dates = ?, status = ?, featured = ?
       WHERE id = ?`,
      [
        title,
        description,
        short_description,
        price,
        duration,
        location,
        image_url,
        JSON.stringify(gallery || []),
        max_people,
        JSON.stringify(included_services || []),
        JSON.stringify(excluded_services || []),
        JSON.stringify(itinerary || []),
        JSON.stringify(available_dates || []),
        status,
        featured,
        req.params.id
      ]
    );

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

    res.json({ message: 'Tur başarıyla güncellendi' });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Sunucu hatası' });
  }
};

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

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

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

exports.getTourBySlug = async (req, res) => {
  try {
    const [tours] = await db.query(
      `SELECT t.*,
              sc.name as sub_category_name,
              sc.slug as sub_category_slug,
              c.name as category_name,
              c.slug as category_slug,
              a.name as airline_name,
              a.code as airline_code,
              a.logo_url as airline_logo
       FROM tours t
       LEFT JOIN sub_categories sc ON t.sub_category_id = sc.id
       LEFT JOIN categories c ON sc.category_id = c.id
       LEFT JOIN airlines a ON t.airline_id = a.id
       WHERE t.slug = ?`,
      [req.params.slug]
    );

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

    const tour = tours[0];

    // Parse JSON fields
    const jsonFields = ['gallery', 'tour_dates', 'important_dates', 'hotel_info', 'pricing', 'included_services', 'excluded_services', 'itinerary'];
    jsonFields.forEach(field => {
      if (tour[field]) {
        try {
          tour[field] = typeof tour[field] === 'string' ? JSON.parse(tour[field]) : tour[field];
        } catch (e) {
          console.error(`Error parsing ${field}:`, e);
          tour[field] = field.includes('services') || field === 'gallery' ? [] : {};
        }
      }
    });

    // Add hotels field for frontend compatibility
    if (tour.hotel_info && Array.isArray(tour.hotel_info)) {
      tour.hotels = tour.hotel_info;
    } else {
      tour.hotels = [];
    }

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

exports.getNearestUmrahTours = async (req, res) => {
  try {
    // Get date range: 2 months ago to 2 months later
    const now = new Date();
    const twoMonthsAgo = new Date();
    twoMonthsAgo.setMonth(now.getMonth() - 2);
    const twoMonthsLater = new Date();
    twoMonthsLater.setMonth(now.getMonth() + 2);

    // Query umre_tours table instead of tours
    const [tours] = await db.query(
      `SELECT t.*,
              sc.name as sub_category_name,
              sc.slug as sub_category_slug,
              c.name as category_name,
              c.slug as category_slug,
              a.name as airline_name,
              a.code as airline_code,
              a.logo_url as airline_logo
       FROM umre_tours t
       LEFT JOIN sub_categories sc ON t.sub_category_id = sc.id
       LEFT JOIN categories c ON sc.category_id = c.id
       LEFT JOIN airlines a ON t.airline_id = a.id
       WHERE t.status = 'active'
       ORDER BY t.tour_date ASC`
    );

    console.log('Found umre tours:', tours.length);

    if (tours.length === 0) {
      return res.json([]);
    }

    // Parse JSON fields and extract dates
    const toursWithDates = [];

    tours.forEach(tour => {
      const jsonFields = ['tour_dates', 'hotel_info', 'pricing', 'gallery', 'included_services', 'excluded_services', 'itinerary', 'important_dates'];
      jsonFields.forEach(field => {
        if (tour[field]) {
          try {
            tour[field] = typeof tour[field] === 'string' ? JSON.parse(tour[field]) : tour[field];
          } catch (e) {
            console.error(`Error parsing ${field}:`, e);
            tour[field] = field === 'tour_dates' ? [] : (field === 'hotel_info' ? [] : (field === 'pricing' ? {} : []));
          }
        }
      });

      // Add hotels field for frontend compatibility
      if (tour.hotel_info && Array.isArray(tour.hotel_info)) {
        tour.hotels = tour.hotel_info;
      }

      // Check if tour_dates array has data
      let dates = [];
      if (tour.tour_dates && Array.isArray(tour.tour_dates) && tour.tour_dates.length > 0) {
        // New format: tour_dates array - filter by date range
        dates = tour.tour_dates
          .filter(d => {
            if (!d.date && !d.departureDate) return false;
            const depDate = new Date(d.date || d.departureDate);
            return depDate >= twoMonthsAgo && depDate <= twoMonthsLater;
          })
          .map(d => ({
            departureDate: d.date || d.departureDate,
            returnDate: d.returnDate || tour.return_date,
            price: d.price || tour.pricing?.double_room || null,
            oldPrice: d.oldPrice || null,
            available_seats: d.available_seats || 0,
            status: d.status || 'open'
          }));
      } else if (tour.tour_date) {
        // Old format: single tour_date field
        const tourDate = new Date(tour.tour_date);
        // Include if within 2 months ago to 2 months later
        if (tourDate >= twoMonthsAgo && tourDate <= twoMonthsLater) {
          dates = [{
            departureDate: tour.tour_date,
            returnDate: tour.return_date,
            price: tour.pricing?.double_room || null,
            oldPrice: null,
            available_seats: tour.max_people || 40,
            status: tour.registration_status || 'open'
          }];
        }
      }

      if (dates.length > 0) {
        toursWithDates.push({
          ...tour,
          dates: dates
        });
      }
    });

    console.log('Tours with dates in range:', toursWithDates.length);
    res.json(toursWithDates);
  } catch (error) {
    console.error('Error in getNearestUmrahTours:', error);
    res.status(500).json({ message: 'Sunucu hatası', error: error.message });
  }
};
