<?php
// Meal Slots API
header('Content-Type: application/json');
require_once 'config.php';

$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : '';

try {
    switch ($action) {
        // ============ MEAL TYPES ============
        case 'get_meal_types':
            getMealTypes($conn);
            break;

        case 'get_meal_type':
            getMealType($conn);
            break;

        case 'create_meal_type':
            createMealType($conn);
            break;

        case 'update_meal_type':
            updateMealType($conn);
            break;

        case 'delete_meal_type':
            deleteMealType($conn);
            break;

        // ============ TIME SLOTS ============
        case 'get_slots':
            getSlots($conn);
            break;

        case 'get_all_slots':
            getAllSlots($conn);
            break;

        case 'get_slot_availability':
            getSlotAvailability($conn);
            break;

        case 'get_time_slot':
            getTimeSlot($conn);
            break;

        case 'create_time_slot':
            createTimeSlot($conn);
            break;

        case 'update_time_slot':
            updateTimeSlot($conn);
            break;

        case 'delete_time_slot':
            deleteTimeSlot($conn);
            break;

        default:
            sendResponse(false, 'Invalid action');
    }
} catch (Exception $e) {
    sendResponse(false, 'Error: ' . $e->getMessage());
}

// ============ MEAL TYPE FUNCTIONS ============
function getMealTypes($conn) {
    $sql = "SELECT id, name, description, icon, color_code, status, display_order, created_at, updated_at 
            FROM meal_types 
            ORDER BY display_order ASC, name ASC";
    
    $result = $conn->query($sql);
    
    if (!$result) {
        sendResponse(false, 'Database error: ' . $conn->error);
    }
    
    $mealTypes = [];
    while ($row = $result->fetch_assoc()) {
        $mealTypes[] = $row;
    }
    
    sendResponse(true, 'Meal types retrieved successfully', $mealTypes);
}

function getMealType($conn) {
    $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
    
    if ($id <= 0) {
        sendResponse(false, 'Invalid meal type ID');
    }
    
    $sql = "SELECT id, name, description, icon, color_code, status, display_order, created_at, updated_at 
            FROM meal_types 
            WHERE id = ?";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        sendResponse(false, 'Meal type not found');
    }
    
    $mealType = $result->fetch_assoc();
    sendResponse(true, 'Meal type retrieved successfully', $mealType);
}

function createMealType($conn) {
    $name = isset($_POST['name']) ? trim($_POST['name']) : '';
    $description = isset($_POST['description']) ? trim($_POST['description']) : '';
    $icon = isset($_POST['icon']) ? trim($_POST['icon']) : 'fas fa-utensils';
    $color_code = isset($_POST['color_code']) ? trim($_POST['color_code']) : '#d4a574';
    $status = isset($_POST['status']) ? trim($_POST['status']) : 'active';
    $display_order = isset($_POST['display_order']) ? intval($_POST['display_order']) : 0;
    
    if (empty($name)) {
        sendResponse(false, 'Meal type name is required');
    }
    
    $sql = "INSERT INTO meal_types (name, description, icon, color_code, status, display_order) 
            VALUES (?, ?, ?, ?, ?, ?)";
    
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        sendResponse(false, 'Prepare failed: ' . $conn->error);
    }
    
    $stmt->bind_param('sssssi', $name, $description, $icon, $color_code, $status, $display_order);
    
    if ($stmt->execute()) {
        sendResponse(true, 'Meal type created successfully', ['id' => $conn->insert_id]);
    } else {
        sendResponse(false, 'Error: ' . $stmt->error);
    }
}

function updateMealType($conn) {
    $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
    $name = isset($_POST['name']) ? trim($_POST['name']) : '';
    $description = isset($_POST['description']) ? trim($_POST['description']) : '';
    $icon = isset($_POST['icon']) ? trim($_POST['icon']) : 'fas fa-utensils';
    $color_code = isset($_POST['color_code']) ? trim($_POST['color_code']) : '#d4a574';
    $status = isset($_POST['status']) ? trim($_POST['status']) : 'active';
    $display_order = isset($_POST['display_order']) ? intval($_POST['display_order']) : 0;
    
    if ($id <= 0 || empty($name)) {
        sendResponse(false, 'Invalid input data');
    }
    
    $sql = "UPDATE meal_types 
            SET name = ?, description = ?, icon = ?, color_code = ?, status = ?, display_order = ?, updated_at = CURRENT_TIMESTAMP 
            WHERE id = ?";
    
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        sendResponse(false, 'Prepare failed: ' . $conn->error);
    }
    
    $stmt->bind_param('sssssii', $name, $description, $icon, $color_code, $status, $display_order, $id);
    
    if ($stmt->execute()) {
        sendResponse(true, 'Meal type updated successfully');
    } else {
        sendResponse(false, 'Error: ' . $stmt->error);
    }
}

function deleteMealType($conn) {
    $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
    
    if ($id <= 0) {
        sendResponse(false, 'Invalid meal type ID');
    }
    
    // First, delete associated time slots (cascade)
    $sql_slots = "DELETE FROM time_slots WHERE meal_type_id = ?";
    $stmt_slots = $conn->prepare($sql_slots);
    $stmt_slots->bind_param('i', $id);
    $stmt_slots->execute();
    
    // Then delete the meal type
    $sql = "DELETE FROM meal_types WHERE id = ?";
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        sendResponse(false, 'Prepare failed: ' . $conn->error);
    }
    
    $stmt->bind_param('i', $id);
    
    if ($stmt->execute()) {
        sendResponse(true, 'Meal type and associated slots deleted successfully');
    } else {
        sendResponse(false, 'Error: ' . $stmt->error);
    }
}

// ============ TIME SLOT FUNCTIONS ============
function getSlots($conn) {
    $meal_type_id = isset($_GET['meal_type_id']) ? intval($_GET['meal_type_id']) : 0;
    
    if ($meal_type_id <= 0) {
        sendResponse(false, 'Invalid meal type ID');
    }
    
    $sql = "SELECT id, meal_type_id, start_time, end_time, slot_name, description, max_capacity, status, display_order, created_at, updated_at 
            FROM time_slots 
            WHERE meal_type_id = ? 
            ORDER BY display_order ASC, start_time ASC";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $meal_type_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $slots = [];
    while ($row = $result->fetch_assoc()) {
        $slots[] = $row;
    }
    
    sendResponse(true, 'Slots retrieved successfully', $slots);
}

function getAllSlots($conn) {
    $sql = "SELECT ts.id, ts.meal_type_id, mt.name as meal_type_name, ts.start_time, ts.end_time, ts.slot_name, ts.description, ts.max_capacity, ts.status, ts.display_order, ts.created_at, ts.updated_at 
            FROM time_slots ts 
            JOIN meal_types mt ON ts.meal_type_id = mt.id 
            ORDER BY mt.display_order ASC, ts.display_order ASC, ts.start_time ASC";
    
    $result = $conn->query($sql);
    
    if (!$result) {
        sendResponse(false, 'Database error: ' . $conn->error);
    }
    
    $slots = [];
    while ($row = $result->fetch_assoc()) {
        $slots[] = $row;
    }
    
    sendResponse(true, 'All slots retrieved successfully', $slots);
}

function getSlotAvailability($conn) {
    $date = isset($_GET['date']) ? trim($_GET['date']) : '';
    $meal_type_id = isset($_GET['meal_type_id']) ? intval($_GET['meal_type_id']) : 0;
    $guests = isset($_GET['guests']) ? intval($_GET['guests']) : 0;

    if (empty($date)) {
        sendResponse(false, 'Date is required');
    }

    $sql = "SELECT 
                ts.id AS slot_id,
                ts.meal_type_id,
                mt.name AS meal_type_name,
                ts.start_time,
                ts.end_time,
                ts.slot_name,
                ts.max_capacity,
                COUNT(b.id) AS booked_count
            FROM time_slots ts
            INNER JOIN meal_types mt ON ts.meal_type_id = mt.id
            LEFT JOIN bookings b 
                ON b.booking_date = ?
                AND TIME(b.slot_time) = TIME(ts.start_time)
                AND LOWER(TRIM(b.meal_type)) = LOWER(TRIM(mt.name))
                AND LOWER(TRIM(b.status)) IN ('pending', 'confirmed', 'checked_in')
            WHERE ts.status = 'active'
            " . ($meal_type_id > 0 ? "AND ts.meal_type_id = ?" : "") . "
            GROUP BY ts.id, ts.meal_type_id, mt.name, ts.start_time, ts.end_time, ts.slot_name, ts.max_capacity
            ORDER BY mt.display_order ASC, ts.display_order ASC, ts.start_time ASC";

    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        sendResponse(false, 'Prepare failed: ' . $conn->error);
    }

    if ($meal_type_id > 0) {
        $stmt->bind_param('si', $date, $meal_type_id);
    } else {
        $stmt->bind_param('s', $date);
    }

    if (!$stmt->execute()) {
        sendResponse(false, 'Execute failed: ' . $stmt->error);
    }

    $result = $stmt->get_result();
    $availability = [];

    while ($row = $result->fetch_assoc()) {
        $maxCapacity = (int)$row['max_capacity'];
        $bookedCount = (int)$row['booked_count'];
        $remaining = max(0, $maxCapacity - $bookedCount);
        $availableTables = null;
        $isFullByTables = false;

        // Also evaluate real online table availability for this slot/date (if guests are provided)
        if ($guests > 0) {
            $tableSql = "SELECT COUNT(*) AS available_tables
                         FROM online_tables ot
                         WHERE ot.status != 'maintenance'
                         AND ot.current_capacity >= ?
                         AND ot.id NOT IN (
                             SELECT otb.online_table_id
                             FROM online_table_bookings otb
                             INNER JOIN bookings b ON otb.booking_id = b.id
                             WHERE b.booking_date = ?
                             AND TIME(b.slot_time) = TIME(?)
                             AND LOWER(TRIM(b.meal_type)) = LOWER(TRIM(?))
                             AND LOWER(TRIM(b.status)) IN ('pending', 'confirmed', 'checked_in')
                             AND otb.allocation_status = 'allocated'
                         )";
            $tableStmt = $conn->prepare($tableSql);
            if ($tableStmt) {
                $tableStmt->bind_param('isss', $guests, $date, $row['start_time'], $row['meal_type_name']);
                if ($tableStmt->execute()) {
                    $tableResult = $tableStmt->get_result();
                    $tableRow = $tableResult ? $tableResult->fetch_assoc() : null;
                    $availableTables = (int)($tableRow['available_tables'] ?? 0);
                    $isFullByTables = $availableTables <= 0;
                }
                $tableStmt->close();
            }
        }

        $isFull = ($remaining <= 0) || $isFullByTables;

        $availability[] = [
            'slot_id' => (int)$row['slot_id'],
            'meal_type_id' => (int)$row['meal_type_id'],
            'meal_type_name' => $row['meal_type_name'],
            'start_time' => $row['start_time'],
            'end_time' => $row['end_time'],
            'slot_name' => $row['slot_name'],
            'max_capacity' => $maxCapacity,
            'booked_count' => $bookedCount,
            'remaining_capacity' => $remaining,
            'available_tables' => $availableTables,
            'is_full' => $isFull
        ];
    }

    $stmt->close();
    sendResponse(true, 'Slot availability retrieved successfully', $availability);
}

function getTimeSlot($conn) {
    $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
    
    if ($id <= 0) {
        sendResponse(false, 'Invalid time slot ID');
    }
    
    $sql = "SELECT id, meal_type_id, start_time, end_time, slot_name, description, max_capacity, status, display_order, created_at, updated_at 
            FROM time_slots 
            WHERE id = ?";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        sendResponse(false, 'Time slot not found');
    }
    
    $slot = $result->fetch_assoc();
    sendResponse(true, 'Time slot retrieved successfully', $slot);
}

function createTimeSlot($conn) {
    $meal_type_id = isset($_POST['meal_type_id']) ? intval($_POST['meal_type_id']) : 0;
    $start_time = isset($_POST['start_time']) ? trim($_POST['start_time']) : '';
    $end_time = isset($_POST['end_time']) ? trim($_POST['end_time']) : '';
    $slot_name = isset($_POST['slot_name']) ? trim($_POST['slot_name']) : '';
    $description = isset($_POST['description']) ? trim($_POST['description']) : '';
    $max_capacity = isset($_POST['max_capacity']) ? intval($_POST['max_capacity']) : 100;
    $status = isset($_POST['status']) ? trim($_POST['status']) : 'active';
    $display_order = isset($_POST['display_order']) ? intval($_POST['display_order']) : 0;
    
    if ($meal_type_id <= 0 || empty($start_time) || empty($end_time)) {
        sendResponse(false, 'Meal type ID, start time, and end time are required');
    }
    
    // Verify meal type exists
    $check_sql = "SELECT id FROM meal_types WHERE id = ?";
    $check_stmt = $conn->prepare($check_sql);
    $check_stmt->bind_param('i', $meal_type_id);
    $check_stmt->execute();
    if ($check_stmt->get_result()->num_rows === 0) {
        sendResponse(false, 'Meal type does not exist');
    }
    
    $sql = "INSERT INTO time_slots (meal_type_id, start_time, end_time, slot_name, description, max_capacity, status, display_order) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
    
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        sendResponse(false, 'Prepare failed: ' . $conn->error);
    }
    
    $stmt->bind_param('issssssi', $meal_type_id, $start_time, $end_time, $slot_name, $description, $max_capacity, $status, $display_order);
    
    if ($stmt->execute()) {
        sendResponse(true, 'Time slot created successfully', ['id' => $conn->insert_id]);
    } else {
        // Check if it's a unique constraint violation
        if (strpos($stmt->error, 'Duplicate') !== false) {
            sendResponse(false, 'A time slot with this meal type and timing already exists');
        }
        sendResponse(false, 'Error: ' . $stmt->error);
    }
}

function updateTimeSlot($conn) {
    $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
    $meal_type_id = isset($_POST['meal_type_id']) ? intval($_POST['meal_type_id']) : 0;
    $start_time = isset($_POST['start_time']) ? trim($_POST['start_time']) : '';
    $end_time = isset($_POST['end_time']) ? trim($_POST['end_time']) : '';
    $slot_name = isset($_POST['slot_name']) ? trim($_POST['slot_name']) : '';
    $description = isset($_POST['description']) ? trim($_POST['description']) : '';
    $max_capacity = isset($_POST['max_capacity']) ? intval($_POST['max_capacity']) : 100;
    $status = isset($_POST['status']) ? trim($_POST['status']) : 'active';
    $display_order = isset($_POST['display_order']) ? intval($_POST['display_order']) : 0;
    
    if ($id <= 0 || $meal_type_id <= 0 || empty($start_time) || empty($end_time)) {
        sendResponse(false, 'Invalid input data');
    }
    
    $sql = "UPDATE time_slots 
            SET meal_type_id = ?, start_time = ?, end_time = ?, slot_name = ?, description = ?, max_capacity = ?, status = ?, display_order = ?, updated_at = CURRENT_TIMESTAMP 
            WHERE id = ?";
    
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        sendResponse(false, 'Prepare failed: ' . $conn->error);
    }
    
    $stmt->bind_param('issssssi', $meal_type_id, $start_time, $end_time, $slot_name, $description, $max_capacity, $status, $display_order, $id);
    
    if ($stmt->execute()) {
        sendResponse(true, 'Time slot updated successfully');
    } else {
        sendResponse(false, 'Error: ' . $stmt->error);
    }
}

function deleteTimeSlot($conn) {
    $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
    
    if ($id <= 0) {
        sendResponse(false, 'Invalid time slot ID');
    }
    
    $sql = "DELETE FROM time_slots WHERE id = ?";
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        sendResponse(false, 'Prepare failed: ' . $conn->error);
    }
    
    $stmt->bind_param('i', $id);
    
    if ($stmt->execute()) {
        sendResponse(true, 'Time slot deleted successfully');
    } else {
        sendResponse(false, 'Error: ' . $stmt->error);
    }
}
?>
