<?php

require_once '../includes/auth.php';

require_login();

$user = current_user();


/*
|--------------------------------------------------------------------------
| Only POST
|--------------------------------------------------------------------------
*/

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {

    header("Location: ../dashboard/cds_attendance.php");

    exit;
}


/*
|--------------------------------------------------------------------------
| Logged-in User
|--------------------------------------------------------------------------
*/

$userId = (int) ($user['id'] ?? 0);


if ($userId <= 0) {

    $_SESSION['error'] =
        "Invalid user session.";

    header("Location: ../dashboard/cds_attendance.php");

    exit;
}


/*
|--------------------------------------------------------------------------
| Get Session Token
|--------------------------------------------------------------------------
*/

$sessionToken =
    trim($_POST['session_token'] ?? '');


if (empty($sessionToken)) {

    $_SESSION['error'] =
        "Invalid attendance session.";

    header("Location: ../dashboard/cds_attendance.php");

    exit;
}


/*
|--------------------------------------------------------------------------
| Find Corps Member
|--------------------------------------------------------------------------
*/

$memberStmt = $db->prepare("
    SELECT
        id,
        user_id,
        state_code,
        status

    FROM corps_members

    WHERE user_id = ?

    LIMIT 1
");


$memberStmt->execute([$userId]);


$corpsMember =
    $memberStmt->fetch(PDO::FETCH_ASSOC);


if (!$corpsMember) {

    $_SESSION['error'] =
        "Corps member profile not found.";

    header("Location: ../dashboard/cds_attendance.php");

    exit;
}


$corpsMemberId =
    (int) $corpsMember['id'];


/*
|--------------------------------------------------------------------------
| Find Member's Active CDS Group
|--------------------------------------------------------------------------
*/

$groupStmt = $db->prepare("
    SELECT
        cgm.cds_group_id

    FROM cds_group_members cgm

    INNER JOIN cds_groups cg
        ON cg.id = cgm.cds_group_id

    WHERE cgm.corps_member_id = ?

    AND cgm.status = 'Active'

    AND cg.status = 'Active'

    LIMIT 1
");


$groupStmt->execute([$corpsMemberId]);


$membership =
    $groupStmt->fetch(PDO::FETCH_ASSOC);


if (!$membership) {

    $_SESSION['error'] =
        "You are not assigned to an active CDS group.";

    header("Location: ../dashboard/cds_attendance.php");

    exit;
}


$cdsGroupId =
    (int) $membership['cds_group_id'];


/*
|--------------------------------------------------------------------------
| Validate Attendance Session
|--------------------------------------------------------------------------
*/

$sessionStmt = $db->prepare("
    SELECT
        id,
        cds_group_id,
        session_token,
        session_date,
        valid_from,
        valid_until,
        status

    FROM qr_attendance_sessions

    WHERE session_token = ?

    AND cds_group_id = ?

    AND session_date = CURDATE()

    AND status = 'Active'

    AND NOW() BETWEEN valid_from AND valid_until

    LIMIT 1
");


$sessionStmt->execute([

    $sessionToken,

    $cdsGroupId

]);


$attendanceSession =
    $sessionStmt->fetch(PDO::FETCH_ASSOC);


if (!$attendanceSession) {

    $_SESSION['error'] =
        "This attendance session is invalid, expired, or closed.";

    header("Location: ../dashboard/cds_attendance.php");

    exit;
}


/*
|--------------------------------------------------------------------------
| Prevent Duplicate Attendance
|--------------------------------------------------------------------------
*/

$checkStmt = $db->prepare("
    SELECT id

    FROM cds_attendance

    WHERE cds_group_id = ?

    AND corps_member_id = ?

    AND attendance_date = CURDATE()

    LIMIT 1
");


$checkStmt->execute([

    $cdsGroupId,

    $corpsMemberId

]);


if ($checkStmt->fetch()) {

    $_SESSION['error'] =
        "You have already marked attendance for today's CDS meeting.";

    header("Location: ../dashboard/cds_attendance.php");

    exit;
}


/*
|--------------------------------------------------------------------------
| Mark Attendance
|--------------------------------------------------------------------------
*/

try {

    $attendanceStmt = $db->prepare("
        INSERT INTO cds_attendance
        (
            cds_group_id,
            corps_member_id,
            attendance_date,
            attendance_time,
            attendance_method,
            attendance_status,
            qr_token,
            remarks,
            marked_by
        )

        VALUES
        (
            ?,
            ?,
            CURDATE(),
            NOW(),
            'QR Code',
            'Present',
            ?,
            ?,
            ?
        )
    ");


    $attendanceStmt->execute([

        $cdsGroupId,

        $corpsMemberId,

        $sessionToken,

        'Attendance marked by corps member',

        $userId

    ]);


    $_SESSION['success'] =
        "Your CDS attendance has been marked successfully.";


} catch (PDOException $e) {


    /*
    |--------------------------------------------------------------------------
    | Handle Duplicate Entry
    |--------------------------------------------------------------------------
    */

    if ($e->getCode() == 23000) {

        $_SESSION['error'] =
            "You have already marked attendance for this CDS meeting.";

    } else {

        $_SESSION['error'] =
            "Unable to mark attendance. Please try again.";

    }

}


header("Location: ../dashboard/cds_attendance.php");

exit;