<?php
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
// CORS Headers - Essential for cross-origin requests
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With, Accept, Origin");
header("Access-Control-Max-Age: 3600");

// Content Type
header("Content-Type: application/json; charset=UTF-8");

// Security Headers
header("X-Content-Type-Options: nosniff");
header("X-Frame-Options: DENY");
header("X-XSS-Protection: 1; mode=block");
header("Referrer-Policy: strict-origin-when-cross-origin");

// Handle OPTIONS preflight request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Cache Control
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");

require_once 'config.php';
    
// Check database connection
if (!$conn) {
    throw new Exception("Database connection failed");
}

// Fetch exclusive deals with error handling
$exclusive_deals = [];
$deals_stmt = $conn->prepare("SELECT * FROM app_menu_deals_items");
if ($deals_stmt) {
    $deals_stmt->execute();
    $deals_result = $deals_stmt->get_result();
    if ($deals_result && $deals_result->num_rows > 0) {
        while ($row = $deals_result->fetch_assoc()) {
            $exclusive_deals[] = $row;
        }
    }
    $deals_stmt->close();
}

// Fetch featured dishes with error handling
$featured_dishes = [];
$featured_stmt = $conn->prepare("SELECT id, name, dish_description, price, category_id, image, is_featured, rating FROM menu_items WHERE is_featured = 1");
if ($featured_stmt) {
    $featured_stmt->execute();
    $featured_result = $featured_stmt->get_result();
    if ($featured_result && $featured_result->num_rows > 0) {
        while ($row = $featured_result->fetch_assoc()) {
            $featured_dishes[] = $row;
        }
    }
    $featured_stmt->close();
}

// Fetch available categories with error handling
$available_categories = [];
$categories_stmt = $conn->prepare("SELECT id, name FROM categories");
if ($categories_stmt) {
    $categories_stmt->execute();
    $categories_result = $categories_stmt->get_result();
    if ($categories_result && $categories_result->num_rows > 0) {
        while ($row = $categories_result->fetch_assoc()) {
            $available_categories[] = $row;
        }
    }
    $categories_stmt->close();
}

// Close database connection
$conn->close();

// Output successful response
http_response_code(200);
echo json_encode([
    'success' => true,
    'exclusive_deals' => $exclusive_deals,
    'featured_dishes' => $featured_dishes,
    'available_categories' => $available_categories,
    'timestamp' => time()
]);
?>