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

class Hajj {
  static async getAll(filters = {}) {
    let query = `
      SELECT t.*,
             a.name as airline_name, a.code as airline_code, a.logo_url as airline_logo
      FROM hajj_tours t
      LEFT JOIN airlines a ON t.airline_id = a.id
      WHERE 1=1
    `;
    const params = [];

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

    if (filters.featured !== undefined) {
      query += ' AND t.featured = ?';
      params.push(filters.featured ? 1 : 0);
    }

    if (filters.vip !== undefined) {
      query += ' AND t.is_vip_program = ?';
      params.push(filters.vip ? 1 : 0);
    }

    if (filters.registration_status) {
      query += ' AND t.registration_status = ?';
      params.push(filters.registration_status);
    }

    // Tarih filtresi - yaklaşan turlar
    if (filters.upcoming) {
      query += ' AND t.tour_date >= CURDATE()';
    }

    query += ' ORDER BY t.tour_date ASC, t.created_at DESC';

    const [rows] = await db.query(query, params);

    return rows.map(tour => this.parseJsonFields(tour));
  }

  static async getById(id) {
    const [rows] = await db.query(
      `SELECT t.*,
              a.name as airline_name, a.code as airline_code, a.logo_url as airline_logo
       FROM hajj_tours t
       LEFT JOIN airlines a ON t.airline_id = a.id
       WHERE t.id = ?`,
      [id]
    );

    if (rows.length === 0) return null;
    return this.parseJsonFields(rows[0]);
  }

  static async getBySlug(slug) {
    const [rows] = await db.query(
      `SELECT t.*,
              a.name as airline_name, a.code as airline_code, a.logo_url as airline_logo
       FROM hajj_tours t
       LEFT JOIN airlines a ON t.airline_id = a.id
       WHERE t.slug = ?`,
      [slug]
    );

    if (rows.length === 0) return null;

    // Increment view count
    await db.query('UPDATE hajj_tours SET views = views + 1 WHERE id = ?', [rows[0].id]);

    return this.parseJsonFields(rows[0]);
  }

  static async create(data) {
    const {
      airline_id, title, slug, description, short_description,
      main_image, gallery, duration, tour_date, return_date, accommodation_type, route,
      important_dates, registration_status, makkah_hotel, madinah_hotel,
      pricing, included_services, excluded_services, itinerary,
      is_vip_program, vip_services, max_people, featured, status
    } = data;

    const [result] = await db.query(
      `INSERT INTO hajj_tours (
        airline_id, title, slug, description, short_description,
        main_image, gallery, duration, tour_date, return_date, accommodation_type, route,
        important_dates, registration_status, makkah_hotel, madinah_hotel,
        pricing, included_services, excluded_services, itinerary,
        is_vip_program, vip_services, max_people, featured, status
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [
        airline_id || null, title, slug, description || null, short_description || null,
        main_image || null, JSON.stringify(gallery || []), duration || null,
        tour_date || null, return_date || null, accommodation_type || null, route || null,
        JSON.stringify(important_dates || []), registration_status || 'open',
        JSON.stringify(makkah_hotel || {}), JSON.stringify(madinah_hotel || {}),
        JSON.stringify(pricing || {}), JSON.stringify(included_services || []),
        JSON.stringify(excluded_services || []), JSON.stringify(itinerary || []),
        is_vip_program || false, JSON.stringify(vip_services || []),
        max_people || 40, featured || false, status || 'draft'
      ]
    );

    return this.getById(result.insertId);
  }

  static async update(id, data) {
    const fields = [];
    const values = [];

    const allowedFields = [
      'airline_id', 'title', 'slug', 'description', 'short_description',
      'main_image', 'gallery', 'duration', 'tour_date', 'return_date',
      'accommodation_type', 'route', 'important_dates', 'registration_status',
      'makkah_hotel', 'madinah_hotel', 'pricing', 'included_services',
      'excluded_services', 'itinerary', 'is_vip_program', 'vip_services',
      'max_people', 'featured', 'status'
    ];

    const jsonFields = [
      'gallery', 'important_dates', 'makkah_hotel', 'madinah_hotel',
      'pricing', 'included_services', 'excluded_services', 'itinerary', 'vip_services'
    ];

    for (const field of allowedFields) {
      if (data[field] !== undefined) {
        fields.push(`${field} = ?`);

        if (jsonFields.includes(field)) {
          values.push(JSON.stringify(data[field]));
        } else {
          values.push(data[field]);
        }
      }
    }

    if (fields.length === 0) {
      throw new Error('No fields to update');
    }

    values.push(id);

    await db.query(
      `UPDATE hajj_tours SET ${fields.join(', ')} WHERE id = ?`,
      values
    );

    return this.getById(id);
  }

  static async delete(id) {
    const [result] = await db.query('DELETE FROM hajj_tours WHERE id = ?', [id]);
    return result.affectedRows > 0;
  }

  static parseJsonFields(tour) {
    if (!tour) return null;

    const jsonFields = [
      'gallery', 'important_dates', 'makkah_hotel', 'madinah_hotel',
      'pricing', 'included_services', 'excluded_services', 'itinerary', 'vip_services'
    ];

    jsonFields.forEach(field => {
      if (tour[field] && typeof tour[field] === 'string') {
        try {
          tour[field] = JSON.parse(tour[field]);
        } catch (e) {
          tour[field] = field === 'pricing' ? {} : [];
        }
      }
    });

    // Otel bilgilerini hotels array'ine dönüştür (UmreDetailPage ile uyumlu)
    tour.hotels = [];

    if (tour.madinah_hotel && Object.keys(tour.madinah_hotel).length > 0) {
      tour.hotels.push({
        ...tour.madinah_hotel,
        location: 'Medine',
        images: tour.madinah_hotel.image ? [tour.madinah_hotel.image] : []
      });
    }

    if (tour.makkah_hotel && Object.keys(tour.makkah_hotel).length > 0) {
      tour.hotels.push({
        ...tour.makkah_hotel,
        location: 'Mekke',
        images: tour.makkah_hotel.image ? [tour.makkah_hotel.image] : []
      });
    }

    // hotel_info field'ini de ekle (UmreDetailPage ile tam uyum için)
    tour.hotel_info = tour.hotels;

    return tour;
  }
}

module.exports = Hajj;
