<?php
// ====================================================================
// QR ATTENDANCE — Students & Staff with full Anti-Cheat
// QR format:  STUDENT:<reg_number>  |  STAFF:<username>
// Anti-cheat: Time window, Present/Late/Absent, GPS, Audit log
// ====================================================================

// ── Ensure tables exist ──────────────────────────────────────────────
mysqli_query($connection,
    "CREATE TABLE IF NOT EXISTS `attendance_settings` (
        `id`                INT AUTO_INCREMENT PRIMARY KEY,
        `school_lat`        DECIMAL(10,7) DEFAULT NULL,
        `school_lng`        DECIMAL(10,7) DEFAULT NULL,
        `geo_radius_meters` INT DEFAULT 200,
        `geo_enforce`       ENUM('strict','warn','off') DEFAULT 'warn',
        `open_time`         TIME DEFAULT '07:00:00',
        `grace_time`        TIME DEFAULT '08:00:00',
        `close_time`        TIME DEFAULT '09:00:00',
        `updated_at`        TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"
);
mysqli_query($connection,
    "CREATE TABLE IF NOT EXISTS `staff_attendance` (
        `id`               INT AUTO_INCREMENT PRIMARY KEY,
        `username`         VARCHAR(100) NOT NULL,
        `name`             VARCHAR(200) NOT NULL,
        `date`             DATE NOT NULL,
        `term`             VARCHAR(50) NOT NULL,
        `session`          VARCHAR(50) NOT NULL,
        `status`           ENUM('Present','Late','Absent') DEFAULT 'Absent',
        `scan_time`        TIME DEFAULT NULL,
        `scan_lat`         DECIMAL(10,7) DEFAULT NULL,
        `scan_lng`         DECIMAL(10,7) DEFAULT NULL,
        `ip_address`       VARCHAR(45) DEFAULT NULL,
        `operator_username` VARCHAR(100) DEFAULT NULL,
        `geo_distance_m`   INT DEFAULT NULL,
        `created_at`       TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        UNIQUE KEY unique_staff_day (username, date, term, session)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"
);
mysqli_query($connection,
    "CREATE TABLE IF NOT EXISTS `staff_attendance_log` (
        `id`             INT AUTO_INCREMENT PRIMARY KEY,
        `username`       VARCHAR(100) NOT NULL,
        `name`           VARCHAR(200) NOT NULL,
        `scanned_by`     VARCHAR(100) NOT NULL DEFAULT 'system',
        `scan_at`        DATETIME NOT NULL,
        `ip_address`     VARCHAR(45) DEFAULT NULL,
        `scan_lat`       DECIMAL(10,7) DEFAULT NULL,
        `scan_lng`       DECIMAL(10,7) DEFAULT NULL,
        `geo_distance_m` INT DEFAULT NULL,
        `result`         ENUM('accepted','rejected','warned') DEFAULT 'accepted',
        `reason`         VARCHAR(255) DEFAULT NULL,
        INDEX idx_scan_at (scan_at),
        INDEX idx_username (username)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"
);

// ── Load anti-cheat settings ─────────────────────────────────────────
$att_cfg = mysqli_fetch_assoc(mysqli_query($connection,
    "SELECT * FROM attendance_settings LIMIT 1"
)) ?: [
    'school_lat'        => null,
    'school_lng'        => null,
    'geo_radius_meters' => 50,
    'geo_enforce'       => 'strict',
    'open_time'         => '07:00:00',
    'grace_time'        => '08:00:00',
    'close_time'        => '09:00:00',
];

// Role & Staff authorization
$role_id_current  = (int)($_SESSION['role'] ?? 0);
$staff_id_current = (int)($_SESSION['staff'] ?? 0);
$is_admin_user    = !empty($is_super_admin) || in_array($role_id_current, [1, 2, 3, 11]);

// Helper: get operator username from session
$operator = $_SESSION['username'] ?? $_SESSION['user'] ?? 'system';

// Helper: get client IP
function getClientIp() {
    return $_SERVER['HTTP_X_FORWARDED_FOR']
        ?? $_SERVER['HTTP_X_REAL_IP']
        ?? $_SERVER['REMOTE_ADDR']
        ?? null;
}

// Helper: Haversine distance in meters
function haversineMeters($lat1, $lng1, $lat2, $lng2) {
    $R = 6371000;
    $phi1 = deg2rad($lat1); $phi2 = deg2rad($lat2);
    $dphi  = deg2rad($lat2 - $lat1);
    $dlam  = deg2rad($lng2 - $lng1);
    $a = sin($dphi/2)**2 + cos($phi1)*cos($phi2)*sin($dlam/2)**2;
    return (int)round(2 * $R * asin(sqrt($a)));
}

// Helper: validate time window → returns [status, reason]
// status = 'open_present' | 'open_late' | 'closed' | 'not_open_yet'
function checkTimeWindow($cfg) {
    $now   = strtotime(date('H:i:s'));
    $open  = strtotime($cfg['open_time']);
    $grace = strtotime($cfg['grace_time']);
    $close = strtotime($cfg['close_time']);
    if ($now < $open)  return ['not_open_yet', 'Attendance window has not opened yet. Opens at ' . date('g:i A', $open)];
    if ($now > $close) return ['closed',        'Attendance window is closed. It closed at ' . date('g:i A', $close)];
    if ($now > $grace) return ['open_late',     'Late (after ' . date('g:i A', $grace) . ')'];
    return ['open_present', 'Present'];
}

// Helper: geo check → returns [distance_m|null, result, reason]
function checkGeo($att_cfg, $scan_lat, $scan_lng) {
    $mode       = $att_cfg['geo_enforce'];
    $school_lat = $att_cfg['school_lat'];
    $school_lng = $att_cfg['school_lng'];
    $radius     = (int)$att_cfg['geo_radius_meters'];

    if ($mode === 'off' || !$school_lat || !$school_lng) {
        return [null, 'accepted', 'Geo check off'];
    }
    if (!$scan_lat || !$scan_lng) {
        $reason = 'GPS not provided by scanner';
        return [null, $mode === 'strict' ? 'rejected' : 'warned', $reason];
    }
    $dist = haversineMeters($school_lat, $school_lng, $scan_lat, $scan_lng);
    if ($dist <= $radius) {
        return [$dist, 'accepted', "Within school radius ({$dist}m ≤ {$radius}m)"];
    }
    $reason = "Outside school — {$dist}m away (limit {$radius}m)";
    return [$dist, $mode === 'strict' ? 'rejected' : 'warned', $reason];
}

// ── SAVE STUDENT ROLL CALL ──────────────────────────────────────────
if (isset($_POST['save_qr_attendance'])) {
    $roll_call_date  = inject_checker($connection, $_POST['roll_call_date']);
    $current_term    = inject_checker($connection, $_POST['current_term']);
    $current_session = inject_checker($connection, $_POST['current_session']);
    $class           = inject_checker($connection, $_POST['attendance_class']);
    $scanned_raw     = $_POST['reg_numbers'] ?? '';

    if (empty($roll_call_date) || empty($class)) {
        $_SESSION['msg']  = "Date and Class fields cannot be empty.";
        $_SESSION['type'] = "danger";
        header("Location: qr_attendance"); exit;
    }

    // Server-side check: teacher must be assigned to this class
    if (!$is_admin_user) {
        $chk_assigned = $connection->prepare("SELECT 1 FROM teacher_classes WHERE teacher_id = ? AND class = ?");
        $chk_assigned->bind_param("is", $staff_id_current, $class);
        $chk_assigned->execute();
        if ($chk_assigned->get_result()->num_rows === 0) {
            $_SESSION['msg']  = "Access denied: You are not assigned to class " . htmlspecialchars($class);
            $_SESSION['type'] = "danger";
            header("Location: qr_attendance"); exit;
        }
        $chk_assigned->close();
    }

    $scanned_reg_nos = array_unique(array_filter(array_map('trim', explode(",", $scanned_raw))));

    $check_stmt = $connection->prepare("SELECT id FROM student_attendance WHERE date = ? AND term = ? AND session = ? AND class = ?");
    $check_stmt->bind_param("ssss", $roll_call_date, $current_term, $current_session, $class);
    $check_stmt->execute();
    $check_stmt->store_result();

    if ($check_stmt->num_rows > 0) {
        $_SESSION['msg']  = "Roll call already recorded for this class today.";
        $_SESSION['type'] = "danger";
    } else {
        $run_query = mysqli_query($connection, "SELECT reg_number, firstname, lastname, othername FROM students WHERE class = '" . mysqli_real_escape_string($connection, $class) . "' AND status = 'active'");
        if ($run_query && mysqli_num_rows($run_query) > 0) {
            $insert_query = "INSERT INTO student_attendance (reg_number, name, date, term, session, class, roll_call) VALUES ";
            $values = []; $params = []; $types = "";
            while ($student = mysqli_fetch_assoc($run_query)) {
                $reg_no    = $student['reg_number'];
                $name      = trim($student['firstname'] . ' ' . $student['lastname'] . ' ' . $student['othername']);
                $roll_call = in_array($reg_no, $scanned_reg_nos) ? "Present" : "Absent";
                $values[]  = "(?, ?, ?, ?, ?, ?, ?)";
                $types    .= "sssssss";
                array_push($params, $reg_no, $name, $roll_call_date, $current_term, $current_session, $class, $roll_call);
            }
            if (!empty($values)) {
                $insert_query .= implode(", ", $values);
                $stmt = $connection->prepare($insert_query);
                $stmt->bind_param($types, ...$params);
                $stmt->execute();
                $_SESSION['msg']  = "Student Roll Call saved successfully.";
                $_SESSION['type'] = "success";
            }
        } else {
            $_SESSION['msg']  = "No active students in this class.";
            $_SESSION['type'] = "danger";
        }
    }
    header("Location: qr_attendance"); exit;
}

// ── SAVE STAFF ATTENDANCE (with Anti-Cheat) ──────────────────────────
if (isset($_POST['save_staff_attendance'])) {
    $att_date        = inject_checker($connection, $_POST['staff_att_date']);
    $current_term    = inject_checker($connection, $_POST['staff_term']);
    $current_session = inject_checker($connection, $_POST['staff_session']);
    $scanned_raw     = $_POST['staff_usernames'] ?? '';
    $client_ip       = getClientIp();
    $now_datetime    = date('Y-m-d H:i:s');

    if (empty($att_date)) {
        $_SESSION['msg']  = "Date cannot be empty.";
        $_SESSION['type'] = "danger";
        header("Location: qr_attendance"); exit;
    }

    // ── 1. TIME WINDOW CHECK ─────────────────────────────────────────
    [$time_status, $time_reason] = checkTimeWindow($att_cfg);
    if (in_array($time_status, ['closed', 'not_open_yet'])) {
        $_SESSION['msg']  = "⏱ Attendance Blocked: {$time_reason}";
        $_SESSION['type'] = "danger";
        header("Location: qr_attendance"); exit;
    }

    $auto_status = ($time_status === 'open_late') ? 'Late' : 'Present';

    $scanned_usernames = array_unique(array_filter(array_map('trim', explode(",", $scanned_raw))));

    // ── 2. GPS COORDS from POST ──────────────────────────────────────
    $form_lat = isset($_POST['gps_lat']) && is_numeric($_POST['gps_lat']) ? floatval($_POST['gps_lat']) : null;
    $form_lng = isset($_POST['gps_lng']) && is_numeric($_POST['gps_lng']) ? floatval($_POST['gps_lng']) : null;

    // ── 3. GEO CHECK (applies to the entire session, not per scan) ───
    [$geo_dist, $geo_result, $geo_reason] = checkGeo($att_cfg, $form_lat, $form_lng);

    if ($geo_result === 'rejected') {
        // Log the blocked attempt
        $ins_log = $connection->prepare(
            "INSERT INTO staff_attendance_log (username, name, scanned_by, scan_at, ip_address, scan_lat, scan_lng, geo_distance_m, result, reason)
             VALUES ('BULK_SAVE', 'All Staff', ?, ?, ?, ?, ?, ?, 'rejected', ?)"
        );
        $ins_log->bind_param("sssddis", $operator, $now_datetime, $client_ip, $form_lat, $form_lng, $geo_dist, $geo_reason);
        $ins_log->execute();

        $_SESSION['msg']  = "📍 Attendance Blocked: {$geo_reason}";
        $_SESSION['type'] = "danger";
        header("Location: qr_attendance"); exit;
    }

    // ── 4. SAVE ATTENDANCE + LOG ─────────────────────────────────────
    $all_staff = [];
    $r = mysqli_query($connection, "SELECT username, name FROM staff");
    while ($s = mysqli_fetch_assoc($r)) { $all_staff[] = $s; }

    $saved = 0; $scan_time = date('H:i:s');

    foreach ($all_staff as $s) {
        $uname   = $s['username'];
        $sname   = $s['name'];
        $is_scanned = in_array($uname, $scanned_usernames);
        $status  = $is_scanned ? $auto_status : 'Absent';

        // Only log scanned (present/late) staff in audit; absent is implicit
        if ($is_scanned) {
            $log_result = ($geo_result === 'warned') ? 'warned' : 'accepted';
            $log_reason = $geo_result === 'warned'
                ? "Marked {$auto_status}. GEO WARNING: {$geo_reason}"
                : "Marked {$auto_status}. {$time_reason}";

            $ins_log = $connection->prepare(
                "INSERT INTO staff_attendance_log (username, name, scanned_by, scan_at, ip_address, scan_lat, scan_lng, geo_distance_m, result, reason)
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
            );
            $ins_log->bind_param("sssssddiss", $uname, $sname, $operator, $now_datetime, $client_ip,
                                 $form_lat, $form_lng, $geo_dist, $log_result, $log_reason);
            $ins_log->execute();
        }

        // Insert attendance record (IGNORE duplicate = already saved)
        $ins = $connection->prepare(
            "INSERT IGNORE INTO staff_attendance
             (username, name, date, term, session, status, scan_time, scan_lat, scan_lng, ip_address, operator_username, geo_distance_m)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
        );
        $ins->bind_param("sssssssddssi", $uname, $sname, $att_date, $current_term, $current_session,
                         $status, $scan_time, $form_lat, $form_lng, $client_ip, $operator, $geo_dist);
        if ($ins->execute() && $ins->affected_rows > 0) $saved++;
    }

    $geo_msg = ($geo_result === 'warned') ? " ⚠️ GPS warning: {$geo_reason}" : '';
    $_SESSION['msg']  = $saved > 0
        ? "✅ Staff attendance saved ({$saved} records). Marked as: {$auto_status}.{$geo_msg}"
        : "⚠️ Attendance already recorded for today.";
    $_SESSION['type'] = $saved > 0 ? ($geo_result === 'warned' ? 'warning' : 'success') : 'warning';
    header("Location: qr_attendance"); exit;
}

// ── Build live status for page display ──────────────────────────────
$now_time   = date('H:i');
[$win_status, $win_reason] = checkTimeWindow($att_cfg);
$win_open   = substr($att_cfg['open_time'],  0, 5);
$win_grace  = substr($att_cfg['grace_time'], 0, 5);
$win_close  = substr($att_cfg['close_time'], 0, 5);
$geo_mode   = $att_cfg['geo_enforce'];
$geo_configured = !empty($att_cfg['school_lat']) && !empty($att_cfg['school_lng']);
?>

<style>
    .att-tabs { display:flex; gap:0; margin-bottom:20px; border-radius:10px; overflow:hidden; border:1px solid #d1d5db; }
    .att-tabs label { flex:1; text-align:center; padding:12px 20px; cursor:pointer; background:#f9fafb; font-weight:600; font-size:14px; color:#6b7280; transition:all .2s; }
    .att-tabs input[type=radio] { display:none; }
    .att-tabs input[type=radio]:checked + label { background:linear-gradient(135deg,#7c3aed,#db2777); color:#fff; }

    .window-status { display:flex; align-items:center; gap:10px; padding:12px 18px; border-radius:12px; font-weight:600; font-size:13px; margin-bottom:16px; }
    .ws-present  { background:#d1fae5; color:#065f46; border:1.5px solid #6ee7b7; }
    .ws-late     { background:#fef3c7; color:#92400e; border:1.5px solid #fcd34d; }
    .ws-closed   { background:#fee2e2; color:#991b1b; border:1.5px solid #fca5a5; }
    .ws-waiting  { background:#ede9fe; color:#5b21b6; border:1.5px solid #c4b5fd; }

    .geo-pill { display:inline-flex; align-items:center; gap:6px; padding:6px 14px; border-radius:20px; font-size:12px; font-weight:600; }
    .geo-strict { background:#fee2e2; color:#991b1b; }
    .geo-warn   { background:#fef3c7; color:#92400e; }
    .geo-off    { background:#f3f4f6; color:#6b7280; }
    .gps-live   { padding:8px 14px; border-radius:10px; font-size:12px; font-weight:600; background:#f0f9ff; border:1px solid #bae6fd; color:#0369a1; }

    .scan-badge-student { background:#7c3aed; color:#fff; border-radius:20px; padding:2px 10px; font-size:12px; }
    .scan-badge-staff   { background:#0ea5e9; color:#fff; border-radius:20px; padding:2px 10px; font-size:12px; }
    #scanner-box      { border:3px dashed #7c3aed; border-radius:12px; padding:6px; }
    #staff-scanner-box{ border:3px dashed #0ea5e9; border-radius:12px; padding:6px; }
</style>

<div class="page-title">
  <div>
    <h1><i class="fa fa-qrcode"></i> QR-Code Attendance Tracker</h1>
    <p>Scan student or staff QR codes — protected by time window & GPS verification</p>
  </div>
  <div>
    <a href="staff_attendance_settings" class="btn btn-warning btn-sm" style="border-radius:8px;font-weight:600;">
        <i class="fa fa-cog"></i> Anti-Cheat Settings
    </a>
    <a href="staff_attendance_log" class="btn btn-secondary btn-sm ml-2" style="border-radius:8px;font-weight:600;">
        <i class="fa fa-list-alt"></i> Audit Log
    </a>
  </div>
</div>

<!-- ── LIVE WINDOW STATUS BANNER ── -->
<?php
$ws_class = match($win_status) {
    'open_present' => 'ws-present',
    'open_late'    => 'ws-late',
    'closed'       => 'ws-closed',
    default        => 'ws-waiting'
};
$ws_icon = match($win_status) {
    'open_present' => '✅',
    'open_late'    => '⏰',
    'closed'       => '🔒',
    default        => '⌛'
};
?>
<div class="window-status <?= $ws_class ?>">
    <?= $ws_icon ?> <b>Staff Attendance Window:</b>&nbsp;
    <?php if ($win_status === 'open_present'): ?>
        OPEN — Scans marked <b>Present</b> until <?= $win_grace ?> &nbsp;|&nbsp; Late window closes at <?= $win_close ?>
    <?php elseif ($win_status === 'open_late'): ?>
        LATE WINDOW — Scans now marked <b>Late</b> (grace closed at <?= $win_grace ?>) &nbsp;|&nbsp; Closes at <?= $win_close ?>
    <?php elseif ($win_status === 'closed'): ?>
        CLOSED — Window closed at <?= $win_close ?>. Staff attendance cannot be saved.
    <?php else: ?>
        NOT OPEN YET — Window opens at <?= $win_open ?>
    <?php endif; ?>
    &nbsp;&nbsp;
    <span class="geo-pill <?= $geo_mode === 'strict' ? 'geo-strict' : ($geo_mode === 'warn' ? 'geo-warn' : 'geo-off') ?>">
        <i class="fa fa-map-marker-alt"></i>
        GPS: <?= strtoupper($geo_mode) ?> <?= $geo_configured ? '' : '(not configured)' ?>
    </span>
</div>

<!-- ── MODE TABS ── -->
<div class="att-tabs no-print">
    <input type="radio" name="att_mode" id="mode_student" value="student" checked>
    <label for="mode_student">🎓 Student Attendance</label>
    <input type="radio" name="att_mode" id="mode_staff" value="staff">
    <label for="mode_staff">👤 Staff Attendance</label>
</div>

<?php
// Preload student records for JavaScript validation
$students_by_class = [];
if ($is_admin_user) {
    $st_res = mysqli_query($connection, "SELECT reg_number, firstname, lastname, othername, class FROM students WHERE status = 'active' ORDER BY firstname ASC");
} else {
    $st_res = mysqli_query($connection, "SELECT s.reg_number, s.firstname, s.lastname, s.othername, s.class FROM students s JOIN teacher_classes tc ON s.class = tc.class WHERE tc.teacher_id = '$staff_id_current' AND s.status = 'active' ORDER BY s.firstname ASC");
}
if ($st_res) {
    while ($st = mysqli_fetch_assoc($st_res)) {
        $c = $st['class'];
        $reg = trim($st['reg_number']);
        $fullname = trim($st['firstname'] . ' ' . $st['lastname'] . ' ' . $st['othername']);
        if (!isset($students_by_class[$c])) {
            $students_by_class[$c] = [];
        }
        $students_by_class[$c][$reg] = $fullname;
    }
}
?>

<!-- ==================================================================
     STUDENT PANEL
================================================================== -->
<div id="panel_student">
<div class="row">
    <div class="col-xs-12 col-sm-12 col-md-5 mb-4">
        <div class="card" style="padding:10px;">
            <h4 class="card-title text-center">📷 QR Scanner — Students</h4>
            <div id="reader" style="width:100%;"></div>
            <div id="scanner-box" class="mt-2 text-center text-muted" style="padding:8px;font-size:12px;">
                <i class="fa fa-info-circle"></i> Point camera at <b>Student ID Card</b> QR code
            </div>
            <div id="student_scan_alert" class="mt-2" style="display:none; font-size:13px; font-weight:600; padding:8px 12px; border-radius:8px;"></div>
        </div>
    </div>
    <div class="col-xs-12 col-sm-12 col-md-7">
        <div class="card" style="padding:10px;">
            <h4 class="card-title">Session Setup — Students</h4>
            <form method="POST" action="">
                <div class="row">
                    <div class="col-xs-12 col-sm-6 col-md-6 form-group">
                        <label>Date</label>
                        <input type="date" name="roll_call_date" class="form-control" required value="<?php echo date('Y-m-d'); ?>" />
                    </div>
                    <div class="col-xs-12 col-sm-6 col-md-6 form-group">
                        <label>Student Class</label>
                        <select class="form-control" name="attendance_class" id="attendance_class" required>
                            <option value="" disabled selected>Select Class</option>
                            <?php
                                if ($is_admin_user) {
                                    $q = mysqli_query($connection, "SELECT classes FROM `classes` ORDER BY classes ASC");
                                } else {
                                    $q = mysqli_query($connection, "SELECT DISTINCT class AS classes FROM `teacher_classes` WHERE teacher_id = '$staff_id_current' ORDER BY class ASC");
                                }
                                if ($q && mysqli_num_rows($q) > 0) {
                                    while($r2 = mysqli_fetch_assoc($q)) {
                                        $c_val = htmlspecialchars($r2['classes']);
                                        echo "<option value='{$c_val}'>{$c_val}</option>";
                                    }
                                } else {
                                    echo "<option value='' disabled>No class assigned to you</option>";
                                }
                            ?>
                        </select>
                    </div>
                    <div class="col-xs-12 col-sm-6 col-md-6 form-group">
                        <label>Term</label>
                        <select class="form-control" name="current_term" required>
                            <?php
                                $term_array = ["First Term", "Second Term", "Third Term"];
                                foreach ($term_array as $term_item) {
                                    $selected = ($term_item === $current_term) ? "selected" : "";
                                    echo "<option value='{$term_item}' {$selected}>{$term_item}</option>";
                                }
                            ?>
                        </select>
                    </div>
                    <div class="col-xs-12 col-sm-6 col-md-6 form-group">
                        <label>Session</label>
                        <select class="form-control" name="current_session" required>
                            <option value="<?php echo htmlspecialchars($current_session); ?>"><?php echo htmlspecialchars($current_session); ?></option>
                        </select>
                    </div>
                </div>
                <div class="form-group mt-3">
                    <h5>Present Students <span class="scan-badge-student" id="scan_count">0</span></h5>
                    <ul id="scanned_list" class="list-group mb-3" style="max-height:220px;overflow-y:auto;">
                        <li class="list-group-item text-muted">No students scanned yet.</li>
                    </ul>
                    <input type="hidden" name="reg_numbers" id="reg_numbers" value="" />
                </div>
                <button type="submit" name="save_qr_attendance" class="btn btn-primary btn-block">
                    <i class="fa fa-save"></i> Save Student Attendance
                </button>
            </form>
        </div>
    </div>
</div>
</div>

<!-- ==================================================================
     STAFF PANEL
================================================================== -->
<div id="panel_staff" style="display:none;">

<?php if ($win_status === 'closed' || $win_status === 'not_open_yet'): ?>
<!-- ── WINDOW BLOCKED UI ── -->
<div class="alert alert-danger" style="border-radius:12px;font-size:14px;padding:20px;">
    <h5><i class="fa fa-lock"></i> Staff Attendance Blocked</h5>
    <p><?= $win_reason ?></p>
    <p>Configured window: <b><?= $win_open ?></b> → Present until <b><?= $win_grace ?></b> → Late until <b><?= $win_close ?></b></p>
    <a href="staff_attendance_settings" class="btn btn-warning btn-sm"><i class="fa fa-cog"></i> Adjust Settings</a>
</div>
<?php else: ?>

<div class="row">
    <div class="col-xs-12 col-sm-12 col-md-5 mb-4">
        <div class="card" style="padding:10px;">
            <h4 class="card-title text-center">📷 QR Scanner — Staff</h4>
            <div id="staff_reader" style="width:100%;"></div>
            <div id="staff-scanner-box" class="mt-2 text-center text-muted" style="padding:8px;font-size:12px;">
                <i class="fa fa-info-circle"></i> Point camera at <b>Staff ID Card</b> QR code
            </div>
            <!-- GPS LIVE STATUS -->
            <div id="gps_status" class="gps-live mt-3 text-center">
                <i class="fa fa-spinner fa-spin"></i> Acquiring GPS location…
            </div>
        </div>
    </div>

    <div class="col-xs-12 col-sm-12 col-md-7">
        <div class="card" style="padding:10px;">
            <h4 class="card-title">
                Session Setup — Staff
                <small class="badge badge-<?= $win_status === 'open_present' ? 'success' : 'warning' ?> ml-2" style="font-size:12px;">
                    <?= $win_status === 'open_present' ? '🟢 Present Window' : '🟡 Late Window' ?>
                </small>
            </h4>
            <form method="POST" action="" id="staffAttForm">
                <!-- Hidden GPS fields — populated by JS -->
                <input type="hidden" name="gps_lat" id="gps_lat" value="">
                <input type="hidden" name="gps_lng" id="gps_lng" value="">

                <div class="row">
                    <div class="col-xs-12 col-sm-6 col-md-6 form-group">
                        <label>Date</label>
                        <input type="date" name="staff_att_date" class="form-control" required value="<?php echo date('Y-m-d'); ?>" />
                    </div>
                    <div class="col-xs-12 col-sm-6 col-md-6 form-group">
                        <label>Term</label>
                        <select class="form-control" name="staff_term" required>
                            <?php
                                $term_array = ["First Term", "Second Term", "Third Term"];
                                foreach ($term_array as $term_item) {
                                    $selected = ($term_item === $current_term) ? "selected" : "";
                                    echo "<option value='{$term_item}' {$selected}>{$term_item}</option>";
                                }
                            ?>
                        </select>
                    </div>
                    <div class="col-xs-12 col-sm-6 col-md-6 form-group">
                        <label>Session</label>
                        <select class="form-control" name="staff_session" required>
                            <option value="<?php echo htmlspecialchars($current_session); ?>"><?php echo htmlspecialchars($current_session); ?></option>
                        </select>
                    </div>
                </div>

                <div class="form-group mt-2">
                    <h5>Present Staff (Scanned) <span class="scan-badge-staff" id="staff_scan_count">0</span></h5>
                    <ul id="staff_scanned_list" class="list-group mb-3" style="max-height:220px;overflow-y:auto;">
                        <li class="list-group-item text-muted">No staff scanned yet.</li>
                    </ul>
                    <input type="hidden" name="staff_usernames" id="staff_usernames" value="" />
                </div>

                <button type="submit" name="save_staff_attendance" id="staffSaveBtn" class="btn btn-info btn-block">
                    <i class="fa fa-save"></i> Save Staff Attendance
                </button>
            </form>
        </div>
    </div>
</div>
<?php endif; ?>
</div>

<!-- ── SCANNER LIBRARY ── -->
<script src="https://unpkg.com/html5-qrcode" type="text/javascript"></script>
<script>
document.addEventListener("DOMContentLoaded", function () {

    // ── Audio beep ───────────────────────────────────────────────────
    function playBeep(freq) {
        try {
            const ctx = new (window.AudioContext || window.webkitAudioContext)();
            const osc = ctx.createOscillator(), gain = ctx.createGain();
            osc.connect(gain); gain.connect(ctx.destination);
            osc.type = 'sine'; osc.frequency.value = freq || 880;
            gain.gain.setValueAtTime(0.4, ctx.currentTime);
            gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.3);
            osc.start(ctx.currentTime); osc.stop(ctx.currentTime + 0.3);
        } catch(e) {}
    }

    function qrboxFn(w, h) {
        const s = Math.floor(Math.min(w, h) * 0.7);
        return { width: s, height: s };
    }

    // ── STUDENT SCANNER ──────────────────────────────────────────────
    const validStudentsByClass = <?php echo json_encode($students_by_class); ?>;
    const studentScanned = new Set();
    const scList  = document.getElementById('scanned_list');
    const scCount = document.getElementById('scan_count');
    const hiddenReg = document.getElementById('reg_numbers');
    const classSelect = document.getElementById('attendance_class');
    const scanAlert = document.getElementById('student_scan_alert');

    function showScanAlert(msg, type) {
        if (!scanAlert) return;
        scanAlert.style.display = 'block';
        if (type === 'danger') {
            scanAlert.className = 'mt-2 alert alert-danger';
            scanAlert.innerHTML = '<i class="fa fa-times-circle"></i> ' + msg;
        } else if (type === 'warning') {
            scanAlert.className = 'mt-2 alert alert-warning';
            scanAlert.innerHTML = '<i class="fa fa-exclamation-triangle"></i> ' + msg;
        } else {
            scanAlert.className = 'mt-2 alert alert-success';
            scanAlert.innerHTML = '<i class="fa fa-check-circle"></i> ' + msg;
        }
    }

    if (classSelect) {
        classSelect.addEventListener('change', function() {
            studentScanned.clear();
            scList.innerHTML = '<li class="list-group-item text-muted">No students scanned yet for ' + this.value + '.</li>';
            scCount.innerText = '0';
            hiddenReg.value = '';
            if (scanAlert) scanAlert.style.display = 'none';
        });
    }

    function onStudentScan(text) {
        let reg = text.trim().replace(/^STUDENT:/i, '');
        if (!reg) return;

        const selectedClass = classSelect ? classSelect.value : '';

        if (!selectedClass) {
            playBeep(300);
            showScanAlert('Please select a class before scanning student QR codes.', 'warning');
            return;
        }

        const classStudents = validStudentsByClass[selectedClass] || {};
        if (!classStudents[reg]) {
            playBeep(300);
            showScanAlert('Student (' + reg + ') does not belong to ' + selectedClass + ' or is not assigned to you.', 'danger');
            return;
        }

        if (studentScanned.has(reg)) {
            showScanAlert('Student ' + classStudents[reg] + ' (' + reg + ') is already marked present.', 'warning');
            return;
        }

        const studentName = classStudents[reg];
        studentScanned.add(reg);
        if (studentScanned.size === 1) scList.innerHTML = '';
        const li = document.createElement('li');
        li.className = 'list-group-item list-group-item-success d-flex justify-content-between align-items-center';
        li.innerHTML = '<span><i class="fa fa-check-circle"></i> <b>' + studentName + '</b> (' + reg + ')</span>'
                     + '<span class="badge badge-success">' + studentScanned.size + '</span>';
        scList.prepend(li);
        scCount.innerText = studentScanned.size;
        hiddenReg.value   = Array.from(studentScanned).join(',');
        playBeep(880);
        showScanAlert('Scanned: ' + studentName + ' (' + reg + ')', 'success');
    }

    const studentScanner = new Html5QrcodeScanner('reader', { fps:10, qrbox:qrboxFn, rememberLastUsedCamera:true }, false);
    studentScanner.render(onStudentScan, function(){});

    // ── STAFF SCANNER + GPS ──────────────────────────────────────────
    const staffScanned     = new Set();
    const staffList        = document.getElementById('staff_scanned_list');
    const staffCount       = document.getElementById('staff_scan_count');
    const hiddenUsernames  = document.getElementById('staff_usernames');
    const gpsStatus        = document.getElementById('gps_status');
    const gpsLatInput      = document.getElementById('gps_lat');
    const gpsLngInput      = document.getElementById('gps_lng');
    let   staffScannerObj  = null;
    let   gpsWatchId       = null;

    // GPS: watch position continuously
    function startGPS() {
        if (!navigator.geolocation) {
            if (gpsStatus) gpsStatus.innerHTML = '<i class="fa fa-times-circle text-danger"></i> GPS not available in this browser';
            return;
        }
        gpsWatchId = navigator.geolocation.watchPosition(function(pos) {
            const lat = pos.coords.latitude.toFixed(7);
            const lng = pos.coords.longitude.toFixed(7);
            const acc = Math.round(pos.coords.accuracy);
            if (gpsLatInput) gpsLatInput.value = lat;
            if (gpsLngInput) gpsLngInput.value = lng;

            <?php if ($geo_configured): ?>
            // Calculate distance from school
            const schoolLat = <?= floatval($att_cfg['school_lat']) ?>;
            const schoolLng = <?= floatval($att_cfg['school_lng']) ?>;
            const dist = haversineMeters(schoolLat, schoolLng, parseFloat(lat), parseFloat(lng));
            const radius = <?= intval($att_cfg['geo_radius_meters']) ?>;
            const mode   = "<?= $geo_mode ?>";

            if (dist <= radius) {
                if (gpsStatus) gpsStatus.innerHTML =
                    '<i class="fa fa-check-circle" style="color:#059669;"></i> <b style="color:#059669;">Within school</b> — ' + dist + 'm away (acc ±' + acc + 'm)';
            } else {
                const col = mode === 'strict' ? '#dc2626' : '#d97706';
                const icon = mode === 'strict' ? '🔒' : '⚠️';
                if (gpsStatus) gpsStatus.innerHTML =
                    icon + ' <b style="color:' + col + ';">' + dist + 'm from school</b> — limit ' + radius + 'm (acc ±' + acc + 'm)';
            }
            <?php else: ?>
            if (gpsStatus) gpsStatus.innerHTML =
                '<i class="fa fa-map-marker-alt" style="color:#0ea5e9;"></i> GPS acquired (lat ' + lat + ', lng ' + lng + ') — school location not configured';
            <?php endif; ?>
        }, function(err) {
            if (gpsStatus) gpsStatus.innerHTML = '<i class="fa fa-exclamation-triangle text-warning"></i> GPS error: ' + err.message;
        }, { enableHighAccuracy: true, maximumAge: 5000 });
    }

    // Haversine in JS
    function haversineMeters(lat1, lng1, lat2, lng2) {
        const R = 6371000;
        const phi1 = lat1 * Math.PI/180, phi2 = lat2 * Math.PI/180;
        const dphi = (lat2-lat1) * Math.PI/180;
        const dlam = (lng2-lng1) * Math.PI/180;
        const a = Math.sin(dphi/2)**2 + Math.cos(phi1)*Math.cos(phi2)*Math.sin(dlam/2)**2;
        return Math.round(2 * R * Math.asin(Math.sqrt(a)));
    }

    function onStaffScan(text) {
        let username = text.trim().replace(/^STAFF:/i, '');
        if (!username || staffScanned.has(username)) return;
        staffScanned.add(username);
        if (staffScanned.size === 1 && staffList) staffList.innerHTML = '';
        const li = document.createElement('li');
        li.className = 'list-group-item list-group-item-info d-flex justify-content-between align-items-center';
        li.innerHTML = '<span><i class="fa fa-user-check"></i> ' + username + '</span>'
                     + '<span class="badge badge-info">' + staffScanned.size + '</span>';
        if (staffList) staffList.prepend(li);
        if (staffCount) staffCount.innerText = staffScanned.size;
        if (hiddenUsernames) hiddenUsernames.value = Array.from(staffScanned).join(',');
        playBeep(660);
    }

    function launchStaffScanner() {
        if (staffScannerObj) return;
        startGPS();
        if (document.getElementById('staff_reader')) {
            staffScannerObj = new Html5QrcodeScanner('staff_reader', { fps:10, qrbox:qrboxFn, rememberLastUsedCamera:true }, false);
            staffScannerObj.render(onStaffScan, function(){});
        }
    }

    // ── TAB SWITCHER ────────────────────────────────────────────────
    document.querySelectorAll('input[name="att_mode"]').forEach(function(radio) {
        radio.addEventListener('change', function() {
            var isStaff = this.value === 'staff';
            document.getElementById('panel_student').style.display = isStaff ? 'none' : '';
            document.getElementById('panel_staff').style.display   = isStaff ? ''     : 'none';
            if (isStaff) launchStaffScanner();
        });
    });

    // ── LIVE WINDOW COUNTDOWN (auto-refresh status) ──────────────────
    function refreshWindowStatus() {
        // Refresh page every 60 seconds so the banner reflects current time
        setTimeout(function() { location.reload(); }, 60000);
    }
    refreshWindowStatus();
});
</script>
