<?php
/**
 * Weekly Specials CRUD Endpoints
 */

$db = Database::getInstance()->getConnection();

// GET all specials
if ($method === 'GET' && !$id) {
    $stmt = $db->query("SELECT * FROM specials LIMIT 100");
    $specials = $stmt->fetchAll();
    
    // Parse JSON highlights
    foreach ($specials as &$special) {
        $special['highlights'] = json_decode($special['highlights'], true);
    }
    
    jsonResponse($specials);
}

// POST create special (admin only)
if ($method === 'POST') {
    requireAuth();
    
    $input = getJsonInput();
    
    $errors = validateRequired($input, ['destination_id', 'discount', 'end_date', 'highlights']);
    if (!empty($errors)) {
        jsonResponse(['error' => implode(', ', $errors)], 400);
    }
    
    // Check if destination exists
    $stmt = $db->prepare("SELECT id FROM destinations WHERE id = ?");
    $stmt->execute([$input['destination_id']]);
    if (!$stmt->fetch()) {
        jsonResponse(['error' => 'Destination not found'], 404);
    }
    
    // Check if special already exists for this destination
    $stmt = $db->prepare("SELECT id FROM specials WHERE destination_id = ?");
    $stmt->execute([$input['destination_id']]);
    if ($stmt->fetch()) {
        jsonResponse(['error' => 'Special already exists for this destination'], 400);
    }
    
    $id = generateUuid();
    $highlights = json_encode($input['highlights']);
    
    $stmt = $db->prepare("
        INSERT INTO specials (id, destination_id, discount, end_date, highlights, created_at)
        VALUES (?, ?, ?, ?, ?, NOW())
    ");
    
    $stmt->execute([
        $id,
        $input['destination_id'],
        $input['discount'],
        $input['end_date'],
        $highlights
    ]);
    
    // Fetch created special
    $stmt = $db->prepare("SELECT * FROM specials WHERE id = ?");
    $stmt->execute([$id]);
    $special = $stmt->fetch();
    $special['highlights'] = json_decode($special['highlights'], true);
    
    jsonResponse($special, 201);
}

// PUT update special (admin only)
if ($method === 'PUT' && $id) {
    requireAuth();
    
    $input = getJsonInput();
    
    $updates = [];
    $params = [];
    
    if (isset($input['discount'])) {
        $updates[] = "discount = ?";
        $params[] = $input['discount'];
    }
    
    if (isset($input['end_date'])) {
        $updates[] = "end_date = ?";
        $params[] = $input['end_date'];
    }
    
    if (isset($input['highlights'])) {
        $updates[] = "highlights = ?";
        $params[] = json_encode($input['highlights']);
    }
    
    if (empty($updates)) {
        jsonResponse(['error' => 'No fields to update'], 400);
    }
    
    $params[] = $id;
    
    $sql = "UPDATE specials SET " . implode(', ', $updates) . " WHERE id = ?";
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    
    // Fetch updated special
    $stmt = $db->prepare("SELECT * FROM specials WHERE id = ?");
    $stmt->execute([$id]);
    $special = $stmt->fetch();
    $special['highlights'] = json_decode($special['highlights'], true);
    
    jsonResponse($special);
}

// DELETE special by destination_id (admin only)
if ($method === 'DELETE' && isset($pathParts[1]) && $pathParts[1] === 'destination' && isset($pathParts[2])) {
    requireAuth();
    
    $destinationId = $pathParts[2];
    
    $stmt = $db->prepare("DELETE FROM specials WHERE destination_id = ?");
    $stmt->execute([$destinationId]);
    
    if ($stmt->rowCount() === 0) {
        jsonResponse(['error' => 'Special not found for this destination'], 404);
    }
    
    jsonResponse(['message' => 'Special removed successfully']);
}

jsonResponse(['error' => 'Invalid specials endpoint'], 404);
