<?php
require_once 'db_config.php';

header('Content-Type: application/json');

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user_id = isset($_POST['user_id']) ? trim($_POST['user_id']) : '';
    $scan_type = isset($_POST['scan_type']) ? trim($_POST['scan_type']) : '';

    if (empty($user_id) || $scan_type !== 'meal') {
        echo json_encode(['status' => 'error', 'message' => 'Invalid or missing data.']);
        exit;
    }

    $user_id_safe = $conn->real_escape_string($user_id);

    // Fetch user
    $result = $conn->query("SELECT fullname, participant_type, meals_allocated FROM users WHERE id = '$user_id_safe'");
    if (!$result || $result->num_rows === 0) {
        echo json_encode(['status' => 'error', 'message' => '❌ User not found.']);
        exit;
    }

    $user = $result->fetch_assoc();
    $fullname = $conn->real_escape_string($user['fullname']);
    $participant_type = $conn->real_escape_string($user['participant_type']);
    $meals_allocated = (int)$user['meals_allocated'];

    // Count total meals used
    $usedResult = $conn->query("SELECT COUNT(*) AS used FROM meal_deductions WHERE user_id = '$user_id_safe'");
    $meals_used = (int)($usedResult->fetch_assoc()['used'] ?? 0);

    if ($meals_used >= $meals_allocated) {
        echo json_encode(['status' => 'error', 'message' => '⚠️ No meals remaining.']);
        exit;
    }

    // Determine meal type and time
    date_default_timezone_set("Africa/Blantyre"); // Ensure timezone is correct

       $now = date("Y-m-d H:i:s");
       $today = date("Y-m-d");

       $current_time = date("H:i"); // Get current time in hours and minutes
       $meal_type = ($current_time < "15:00") ? "Lunch" : "Dinner";


    // Check today's meals
    $todayResult = $conn->query("SELECT COUNT(*) AS today_count FROM meal_deductions WHERE user_id = '$user_id_safe' AND DATE(time) = '$today'");
    $meals_today = (int)($todayResult->fetch_assoc()['today_count'] ?? 0);

    if ($meals_today >= 2) {
        echo json_encode(['status' => 'error', 'message' => '🍽️ Daily meal limit reached (2 meals per day).']);
        exit;
    }

    // OPTIONAL: prevent duplicate Lunch/Dinner on the same day
    $checkMeal = $conn->query("SELECT id FROM meal_deductions WHERE user_id = '$user_id_safe' AND meal_type = '$meal_type' AND DATE(time) = '$today'");
    if ($checkMeal && $checkMeal->num_rows > 0) {
        echo json_encode(['status' => 'error', 'message' => "⚠️ Already received $meal_type today."]);
        exit;
    }

    // Deduct meal
    $insert_sql = "INSERT INTO meal_deductions (user_id, name, time, meal_type) 
                   VALUES ('$user_id_safe', '$fullname', '$now', '$meal_type')";

    if ($conn->query($insert_sql)) {
        echo json_encode([
            'status' => 'success',
            'message' => "✅ $meal_type deducted for $fullname",
            'fullname' => $fullname,
            'meal_type' => $meal_type,
            'meals_remaining' => $meals_allocated - $meals_used - 1
        ]);
    } else {
        echo json_encode(['status' => 'error', 'message' => '❌ Failed to insert deduction: ' . $conn->error]);
    }

} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method.']);
}
?>
