<?php
session_start();

include($_SERVER['DOCUMENT_ROOT']."/SEAT/config/db.php");

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

/* ================= ACCESS CONTROL ================= */

if(
    !isset($_SESSION['role']) ||
    $_SESSION['role'] != "organizer"
){
    echo json_encode([
        "valid"   => false,
        "message" => "Unauthorized access"
    ]);
    exit;
}

/* ================= GET JSON INPUT ================= */

$data = json_decode(
    file_get_contents("php://input"),
    true
);

$token    = trim($data['token'] ?? '');
$event_id = (int)($data['event_id'] ?? 0);

if($token == ''){
    echo json_encode([
        "valid"   => false,
        "message" => "Ticket token missing"
    ]);
    exit;
}

if($event_id <= 0){
    echo json_encode([
        "valid"   => false,
        "message" => "Invalid event selected"
    ]);
    exit;
}

/* =====================================================
   FIND TICKET + MATCH EVENT
===================================================== */

$stmt = $conn->prepare("
SELECT
    r.*,

    e.title,
    e.event_date,
    e.mode,
    e.status AS event_status,

    p.full_name,
    p.matric_no,
    p.staff_no,

    u.email

FROM event_registrations r

JOIN events e
ON r.event_id = e.id

LEFT JOIN participants p
ON r.participant_id = p.id

LEFT JOIN users u
ON p.user_id = u.id

WHERE r.token = ?
AND r.event_id = ?

LIMIT 1
");

$stmt->bind_param("si", $token, $event_id);
$stmt->execute();

$res = $stmt->get_result();

/* ================= NOT FOUND ================= */

if($res->num_rows == 0){

    echo json_encode([
        "valid"   => false,
        "ticket"  => $token,
        "message" => "Ticket not found for selected event"
    ]);
    exit;
}

$row = $res->fetch_assoc();

/* =====================================================
   FORMAT EVENT DATE (dd/mm/yyyy)
===================================================== */

$event_date = !empty($row['event_date'])
    ? date("d/m/Y", strtotime($row['event_date']))
    : "-";

/* =====================================================
   EVENT DATE CHECK (PAST EVENT)
===================================================== */

$today = date("Y-m-d");

if (!empty($row['event_date']) && $row['event_date'] < $today) {

    echo json_encode([
        "valid"       => false,
        "ticket"      => $row['token'],
        "title"       => $row['title'],
        "event_date"  => $event_date,
        "message"     => "Event already ended"
    ]);
    exit;
}

/* =====================================================
   USED TICKET CHECK
===================================================== */

if(strtolower($row['status_ticket']) == "used"){

    $used_time = '';

    if(!empty($row['scanned_at'])){
        $used_time = date(
            "d/m/Y H:i",
            strtotime($row['scanned_at'])
        );
    }

    echo json_encode([
        "valid"       => false,
        "ticket"      => $row['token'],
        "name"        => $row['full_name'],
        "matric"      => $row['matric_no'] ?: $row['staff_no'],
        "title"       => $row['title'],
        "event_date"  => $event_date,
        "scanned_at"  => $used_time,
        "message"     => "Ticket already used on ".$used_time
    ]);

    exit;
}

/* =====================================================
   MARK TICKET USED
===================================================== */

$update = $conn->prepare("
UPDATE event_registrations
SET
    status_ticket = 'used',
    scanned_at = NOW(),
    status = 'attended'
WHERE id = ?
");

$update->bind_param("i", $row['id']);
$update->execute();

/* =====================================================
   CHECK EXISTING ATTENDANCE
===================================================== */

$check = $conn->prepare("
SELECT id
FROM attendances
WHERE registration_id = ?
LIMIT 1
");

$check->bind_param("i", $row['id']);
$check->execute();

$checkRes = $check->get_result();

/* =====================================================
   INSERT ATTENDANCE IF NOT EXISTS
===================================================== */

if($checkRes->num_rows == 0){

    $att = $conn->prepare("
    INSERT INTO attendances
    (event_id, registration_id)
    VALUES (?, ?)
    ");

    $att->bind_param("ii", $row['event_id'], $row['id']);
    $att->execute();
}

/* =====================================================
   SUCCESS RESPONSE
===================================================== */

$scanned_date = date("d/m/Y H:i");

echo json_encode([
    "valid"       => true,
    "ticket"      => $row['token'],
    "name"        => $row['full_name'],
    "matric"      => $row['matric_no'] ?: $row['staff_no'],
    "email"       => $row['email'],
    "title"       => $row['title'],
    "event_date"  => $event_date,
    "scanned_at"  => $scanned_date,
    "message"     => "Check-in successful"
]);
?>