<?php




require_once("public/connection.php");
require_once("public/functions.php");

/* ===========================
   STAFF LOGIN SESSION CHECK
=========================== */

if (!isset($_SESSION['staff']) || empty($_SESSION['staff'])) {
    header("Location: login.php");
    exit;
}

$marked_by = $_SESSION['staff'];

/* ===========================
   FETCH CURRENT TERM & SESSION
=========================== */
$cs = $connection->query("SELECT current_term, current_session FROM current_season LIMIT 1");
$current_season = $cs->fetch_assoc();
$term = $current_season['current_term'];
$session_val = $current_season['current_session'];

/* ===========================
   STAFF ATTENDANCE LOGIC
=========================== */
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['qr'])) {

    $username  = trim($_POST['qr']);
    $date      = $_POST['date'];
    $rollType  = $_POST['roll_type'];
    $current_time = date('H:i:s');

    // Fetch staff by username (QR)
    $stmt = $connection->prepare(
        "SELECT id, name FROM staff WHERE username=? AND status='Active'"
    );
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $res = $stmt->get_result();

    if ($res && $res->num_rows === 1) {

        $staff = $res->fetch_assoc();

        $roll_col = ($rollType === 'morning') ? 'morning_roll' : 'afternoon_roll';
        $time_col = ($rollType === 'morning') ? 'time_morning' : 'time_afternoon';

        // Check if attendance exists
        $check = $connection->prepare(
            "SELECT id FROM staff_attendance 
             WHERE staff_id=? AND date=? AND term=? AND session=?"
        );
        $check->bind_param("isss", $staff['id'], $date, $term, $session_val);
        $check->execute();
        $chk = $check->get_result();

        if ($chk->num_rows > 0) {

            // Update attendance
            $upd = $connection->prepare(
                "UPDATE staff_attendance 
                 SET $roll_col='Present', $time_col=? 
                 WHERE staff_id=? AND date=? AND term=? AND session=?"
            );
            $upd->bind_param(
                "sisss",
                $current_time,
                $staff['id'],
                $date,
                $term,
                $session_val
            );
            $upd->execute();

            $message = "✅ Attendance updated for {$staff['name']} at $current_time";
            $message_type = 'success';

        } else {

            // Insert new attendance
            $morning   = ($rollType === 'morning') ? 'Present' : 'Absent';
            $afternoon = ($rollType === 'afternoon') ? 'Present' : 'Absent';

            $time_morning   = ($rollType === 'morning') ? $current_time : null;
            $time_afternoon = ($rollType === 'afternoon') ? $current_time : null;

            $ins = $connection->prepare(
                "INSERT INTO staff_attendance
                (staff_id, username, name, date, term, session,
                 morning_roll, afternoon_roll, time_morning, time_afternoon, marked_by)
                 VALUES (?,?,?,?,?,?,?,?,?,?,?)"
            );

            $ins->bind_param(
                "isssssssssi",
                $staff['id'],
                $username,
                $staff['name'],
                $date,
                $term,
                $session_val,
                $morning,
                $afternoon,
                $time_morning,
                $time_afternoon,
                $marked_by
            );
            $ins->execute();

            $message = "✅ Attendance marked for {$staff['name']} at $current_time";
            $message_type = 'success';
        }

    } else {
        $message = "❌ Invalid staff QR / username";
        $message_type = 'error';
    }
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Staff QR Attendance</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="assets/css/bootstrap.min.css">
<script src="https://unpkg.com/html5-qrcode"></script>

<style>
#reader { max-width:420px; margin:20px auto; }
.scan-box { padding:20px; background:#fff; border-radius:16px; box-shadow:0 10px 30px rgba(0,0,0,.1); }
.toast-container { position: fixed; top: 20px; right: 20px; z-index: 9999; }
.toast { padding:15px 20px; border-radius:6px; color:#fff; margin-bottom:10px; font-weight:bold; min-width:250px; }
.toast-success { background:#28a745; }
.toast-error { background:#dc3545; }
</style>
</head>

<body class="bg-light">

<div class="container mt-4">
<h3 class="text-center mb-3">📷 Staff QR Attendance</h3>

<div class="scan-box">
<form method="POST" id="attendanceForm">
    <input type="hidden" name="qr" id="qr_input">

    <label>Date</label>
    <input type="date" name="date" class="form-control mb-2" value="<?=date('Y-m-d')?>" required>

    <label>Roll Call</label>
    <select name="roll_type" class="form-control mb-2" required>
        <option value="morning">Morning</option>
        <option value="afternoon">Afternoon</option>
    </select>
</form>

<div id="reader"></div>
</div>
</div>

<div class="toast-container" id="toastContainer"></div>

<audio id="successSound" src="assets/sounds/success.mp3"></audio>
<audio id="errorSound" src="assets/sounds/error.mp3"></audio>

<script>
const qrInput = document.getElementById("qr_input");
const attendanceForm = document.getElementById("attendanceForm");
const toastContainer = document.getElementById("toastContainer");
const successSound = document.getElementById("successSound");
const errorSound = document.getElementById("errorSound");

function showToast(message, type){
    const toast = document.createElement("div");
    toast.className = "toast " + (type==="success" ? "toast-success" : "toast-error");
    toast.innerText = message;
    toastContainer.appendChild(toast);
    type==="success" ? successSound.play() : errorSound.play();
    setTimeout(()=>toast.remove(), 2500);
}

function submitQR(code){
    qrInput.value = code;
    attendanceForm.submit();
}

Html5Qrcode.getCameras().then(cams => {
    if (!cams || cams.length === 0) {
        showToast("No camera found", "error");
        return;
    }

    // Prefer back / rear / environment camera
    const backCam = cams.find(cam =>
        /back|rear|environment/i.test(cam.label)
    ) || cams[0];

    new Html5Qrcode("reader").start(
        backCam.id,
        { fps: 10, qrbox: 250 },
        submitQR
    ).catch(err => showToast("Camera error: " + err, "error"));
});

<?php if($message): ?>
showToast("<?= addslashes($message) ?>","<?= $message_type ?>");
<?php endif; ?>
</script>

</body>
</html>
