-- ====================================================================
-- HAC TURLARI İÇİN REZERVASYON SİSTEMİ DESTEĞI
-- ====================================================================
-- Bu dosya hajj_tours tablosuna rezervasyon sistemi desteği ekler
-- ====================================================================

USE tour_management;

-- 1. hajj_tours tablosuna kontenjan alanları ekle
ALTER TABLE hajj_tours
ADD COLUMN IF NOT EXISTS current_bookings INT DEFAULT 0 COMMENT 'Mevcut rezervasyon sayısı',
ADD COLUMN IF NOT EXISTS available_seats INT GENERATED ALWAYS AS (IFNULL(max_people, 40) - current_bookings) STORED COMMENT 'Kalan kontenjan';

-- 2. Orders tablosuna tour_type kolonu ekle (eğer yoksa)
-- Bu sayede hangi tabloya ait olduğunu biliyoruz
ALTER TABLE orders
ADD COLUMN IF NOT EXISTS tour_type ENUM('tour', 'umre', 'hajj') DEFAULT 'tour' COMMENT 'Tur tipi: tour (yurtdışı), umre, hajj';

-- 3. Mevcut trigger'ları güncelle - HAC desteği ekle
DROP TRIGGER IF EXISTS after_order_insert;
DROP TRIGGER IF EXISTS after_order_cancel;

DELIMITER $$

-- Rezervasyon oluşturulduğunda kontenjanı güncelle (HAC dahil)
CREATE TRIGGER after_order_insert
AFTER INSERT ON orders
FOR EACH ROW
BEGIN
  DECLARE total_people INT;

  -- JSON'dan toplam kişi sayısını çıkar
  IF NEW.number_of_people IS NOT NULL THEN
    SET total_people = JSON_EXTRACT(NEW.number_of_people, '$.adults') +
                       JSON_EXTRACT(NEW.number_of_people, '$.children') +
                       JSON_EXTRACT(NEW.number_of_people, '$.infants');

    -- Tour type'a göre ilgili tabloyu güncelle
    IF NEW.tour_type = 'tour' THEN
      -- Normal turlar için kontenjan güncelle
      UPDATE tours
      SET current_bookings = current_bookings + total_people
      WHERE id = NEW.tour_id;
    ELSEIF NEW.tour_type = 'umre' THEN
      -- Umre turları için kontenjan güncelle
      UPDATE umre_tours
      SET current_bookings = current_bookings + total_people
      WHERE id = NEW.tour_id;
    ELSEIF NEW.tour_type = 'hajj' THEN
      -- Hac turları için kontenjan güncelle
      UPDATE hajj_tours
      SET current_bookings = current_bookings + total_people
      WHERE id = NEW.tour_id;
    END IF;
  END IF;
END$$

-- Rezervasyon iptal edildiğinde kontenjanı geri al (HAC dahil)
CREATE TRIGGER after_order_cancel
AFTER UPDATE ON orders
FOR EACH ROW
BEGIN
  DECLARE total_people INT;

  -- Eğer durum cancelled'a çekildiyse
  IF OLD.booking_status != 'cancelled' AND NEW.booking_status = 'cancelled' THEN
    IF NEW.number_of_people IS NOT NULL THEN
      SET total_people = JSON_EXTRACT(NEW.number_of_people, '$.adults') +
                         JSON_EXTRACT(NEW.number_of_people, '$.children') +
                         JSON_EXTRACT(NEW.number_of_people, '$.infants');

      -- Tour type'a göre ilgili tabloyu güncelle
      IF NEW.tour_type = 'tour' THEN
        -- Normal turlar için kontenjan geri al
        UPDATE tours
        SET current_bookings = GREATEST(0, current_bookings - total_people)
        WHERE id = NEW.tour_id;
      ELSEIF NEW.tour_type = 'umre' THEN
        -- Umre turları için kontenjan geri al
        UPDATE umre_tours
        SET current_bookings = GREATEST(0, current_bookings - total_people)
        WHERE id = NEW.tour_id;
      ELSEIF NEW.tour_type = 'hajj' THEN
        -- Hac turları için kontenjan geri al
        UPDATE hajj_tours
        SET current_bookings = GREATEST(0, current_bookings - total_people)
        WHERE id = NEW.tour_id;
      END IF;
    END IF;
  END IF;
END$$

DELIMITER ;

-- 4. Hac turları için istatistik view oluştur
CREATE OR REPLACE VIEW v_hajj_statistics AS
SELECT
  h.id,
  h.title,
  h.tour_date,
  h.max_people,
  h.current_bookings,
  h.available_seats,
  h.is_vip_program,
  COUNT(DISTINCT o.id) as total_orders,
  SUM(CASE WHEN o.booking_status = 'confirmed' THEN 1 ELSE 0 END) as confirmed_orders,
  SUM(CASE WHEN o.payment_status = 'paid' THEN o.total_amount ELSE 0 END) as total_revenue
FROM hajj_tours h
LEFT JOIN orders o ON h.id = o.tour_id AND o.tour_type = 'hajj'
GROUP BY h.id, h.title, h.tour_date, h.max_people, h.current_bookings, h.available_seats, h.is_vip_program;

-- 5. Index ekle (performans için)
ALTER TABLE orders
ADD INDEX IF NOT EXISTS idx_tour_type (tour_type);

-- 6. Mevcut orders verilerini kontrol et ve düzelt
-- Eğer varsa eski veriler için tour_type'ı belirle
-- (Bu kısım manuel kontrol gerektirebilir)

-- Kontrol query'leri:
-- SELECT id, tour_id, tour_type FROM orders WHERE tour_type IS NULL;

-- ====================================================================
-- KULLANIM ÖRNEĞİ
-- ====================================================================

-- Hac turu rezervasyonu oluştururken:
/*
INSERT INTO orders (
  tour_id,
  tour_type,  -- 'hajj' olarak belirt
  customer_name,
  customer_email,
  number_of_people,
  total_amount,
  ...
) VALUES (
  1,
  'hajj',  -- ÖNEMLI: Bu alan mutlaka belirtilmeli
  'Ahmet Yılmaz',
  'ahmet@example.com',
  '{"adults": 2, "children": 1, "infants": 0}',
  150000,
  ...
);
*/

-- ====================================================================
-- KONTROL
-- ====================================================================

-- Hajj tours tablosunu kontrol et
SELECT
  id,
  title,
  max_people,
  current_bookings,
  available_seats
FROM hajj_tours;

-- Trigger'ların oluştuğunu kontrol et
SHOW TRIGGERS LIKE 'orders';

-- View'ı kontrol et
SELECT * FROM v_hajj_statistics;

-- Tamamlandı
SELECT '✅ Hac turları rezervasyon sistemi hazır!' as message;
