<?php
require 'db_config.php';
date_default_timezone_set('Africa/Blantyre');
header('Content-Type: application/json');

$response = ['status'=>'error','message'=>'Invalid user.'];

if (!empty($_POST['user_id'])) {
    $user_id = intval($_POST['user_id']);
    $now = date('Y-m-d H:i:s');
    $today = date('Y-m-d');

    // get user
    $stmt = $conn->prepare("SELECT fullname, participant_type, meals_allocated, meals_remaining FROM users WHERE id=?");
    $stmt->bind_param("i",$user_id);
    $stmt->execute();
    $user = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if ($user) {
        $response = ['status'=>'success','message'=>"<span style='color:green;'>✅ {$user['fullname']}</span>"];
        $response += logAttendance($conn, $user_id, $user);
        $response += processMeal($conn, $user_id, $user, $today, $now);
        $response += processPromo($conn, $user_id, $user, $today, $now);
    } else {
        $response['message'] = "<span style='color:red;'>User not found.</span>";
    }
}
echo json_encode($response);

function logAttendance($conn,$uid,$user){
    $today = date('Y-m-d');
    $stmt = $conn->prepare("SELECT COUNT(*) FROM attendance WHERE user_id=? AND DATE(checkin_time)=?");
    $stmt->bind_param("is",$uid,$today);
    $stmt->execute();
    $cnt = $stmt->get_result()->fetch_row()[0];
    $stmt->close();
    if ($cnt>0) return [];
    $stmt = $conn->prepare("INSERT INTO attendance(user_id,participant_type,fullname) VALUES(?,?,?)");
    $stmt->bind_param("iss",$uid,$user['participant_type'],$user['fullname']);
    $stmt->execute(); $stmt->close();
    return ['attendance'=>[$user['fullname'], date('H:i:s')]];
}

function processMeal($conn,$uid,$user,$today,$now){
    // only one lunch and one dinner per day allowed
    $hour = intval(date('H'));
    if ($user['meals_remaining']<=0) return ['meal'=>[$user['fullname'],$user['meals_allocated'],0,'0']];
    $meal_type = ($hour<15?'Lunch':'Dinner');
    // already collected same meal_type?
    $stmt = $conn->prepare("SELECT COUNT(*) FROM meal_deductions WHERE user_id=? AND meal_type=? AND DATE(deduction_time)=?");
    $stmt->bind_param("iss",$uid,$meal_type,$today);
    $stmt->execute();
    if ($stmt->get_result()->fetch_row()[0]>0) { $stmt->close(); return []; }
    $stmt->close();

    // insert deduction
    $stmt = $conn->prepare("INSERT INTO meal_deductions(user_id,fullname,meal_type) VALUES(?,?,?)");
    $stmt->bind_param("iss",$uid,$user['fullname'],$meal_type);
    $stmt->execute(); $stmt->close();

    // update users
    $stmt = $conn->prepare("UPDATE users SET meals_remaining=meals_remaining-1 WHERE id=?");
    $stmt->bind_param("i",$uid); $stmt->execute(); $stmt->close();

    $remaining = $user['meals_remaining']-1;
    return ['meal'=>[$user['fullname'],$user['meals_allocated'],$remaining,date('H:i:s')]];
}

function processPromo($conn,$uid,$user,$today,$now){
    // one promo per day
    $stmt = $conn->prepare("SELECT COUNT(*) FROM promotional_materials WHERE user_id=? AND DATE(collection_time)=? AND status=1");
    $stmt->bind_param("is",$uid,$today);
    $stmt->execute();
    if ($stmt->get_result()->fetch_row()[0]>0) { $stmt->close(); return []; }
    $stmt->close();

    $stmt = $conn->prepare("INSERT INTO promotional_materials(user_id,fullname,material_collected) VALUES(?,?, 'Yes')");
    $stmt->bind_param("is",$uid,$user['fullname']);
    $stmt->execute(); $stmt->close();

    return ['promo'=>[$user['fullname'],'Collected',date('H:i:s')]];
}
?>
