<?php

require_once("public/connection.php");


/* =========================
   FETCH CLASSES & SESSIONS
   (SAME AS VIEW PAGE)
========================= */
$classes = [];
$class_query = $connection->query("SELECT * FROM classes ORDER BY classes ASC");
if ($class_query && $class_query->num_rows > 0) {
    while ($c = $class_query->fetch_assoc()) {
        $classes[] = $c['classes'];
    }
}

$sessions = [];
$session_query = $connection->query("SELECT * FROM sessions ORDER BY sessions ASC");
if ($session_query && $session_query->num_rows > 0) {
    while ($s = $session_query->fetch_assoc()) {
        $sessions[] = $s['sessions'];
    }
}

/* =========================
   SMS SETTINGS
========================= */
$smsToken = '';
$smsSender = '';
$sms_settings = $connection->query("SELECT token, senderID FROM sms_settings LIMIT 1");
if ($sms_settings && $sms_settings->num_rows > 0) {
    $settings = $sms_settings->fetch_assoc();
    $smsToken = $settings['token'];
    $smsSender = $settings['senderID'];
}

/* =========================
   FEEDBACK STATE
========================= */
$message = '';
$message_type = '';

/* =========================
   PRESERVE FORM VALUES
========================= */
$selectedClass   = $_POST['class'] ?? '';
$selectedDate    = $_POST['date'] ?? date('Y-m-d');
$selectedTerm    = $_POST['term'] ?? 'First Term';
$selectedSession = $_POST['session'] ?? '';
$selectedRoll    = $_POST['roll_type'] ?? 'morning';

/* =========================
   QR ATTENDANCE HANDLER
========================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['qr'])) {

    $reg_number = trim($_POST['qr']);
    $class      = trim($selectedClass);
    $date       = trim($selectedDate);
    $term       = trim($selectedTerm);
    $session    = trim($selectedSession);
    $rollType   = trim($selectedRoll);

    if ($reg_number && $class && $date && $term && $session) {

        /* Fetch student */
        $stmt = $connection->prepare(
            "SELECT firstname, lastname, othername, guardian_phone 
             FROM students WHERE reg_number=? AND class=?"
        );
        $stmt->bind_param("ss", $reg_number, $class);
        $stmt->execute();
        $res = $stmt->get_result();

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

            $student = $res->fetch_assoc();
            $name = trim($student['firstname'] . ' ' . $student['lastname'] . ' ' . $student['othername']);
            $guardianPhone = trim($student['guardian_phone']);

            $col = ($rollType === 'morning') ? 'roll_call' : 'afternoonrollcall';
            $time_col = ($rollType === 'morning') ? 'time_morning' : 'time_afternoon';
            $current_time = date('H:i:s');

            /* Check existing attendance */
            $check = $connection->prepare(
                "SELECT $col FROM student_attendance 
                 WHERE reg_number=? AND date=? AND term=? AND session=? AND class=?"
            );
            $check->bind_param("sssss", $reg_number, $date, $term, $session, $class);
            $check->execute();
            $checkRes = $check->get_result();

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

                $row = $checkRes->fetch_assoc();

                if ($row[$col] !== 'Present') {

                    /* Update attendance */
                    $upd = $connection->prepare(
                        "UPDATE student_attendance 
                         SET $col='Present', $time_col=? 
                         WHERE reg_number=? AND date=? AND class=?"
                    );
                    $upd->bind_param("ssss", $current_time, $reg_number, $date, $class);
                    $upd->execute();

                    $message = "✅ Attendance updated for $name";
                    $message_type = 'success';

                } else {
                    $message = "⚠️ $name already marked present for $rollType roll call";
                    $message_type = 'error';
                }

            } else {

                /* First insert */
                $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 student_attendance
                    (reg_number, name, class, date, term, session,
                     roll_call, afternoonrollcall, time_morning, time_afternoon)
                    VALUES (?,?,?,?,?,?,?,?,?,?)"
                );

                $ins->bind_param(
                    "ssssssssss",
                    $reg_number,
                    $name,
                    $class,
                    $date,
                    $term,
                    $session,
                    $morning,
                    $afternoon,
                    $time_morning,
                    $time_afternoon
                );

                $ins->execute();

                $message = "✅ Attendance marked for $name";
                $message_type = 'success';
            }

            /* SEND SMS */
            if ($guardianPhone && $smsToken && $smsSender && $message_type === 'success') {

                $dateWord = date('l, d F y', strtotime($date));
                $timeNow  = date('h:i A');

                $smsMsg = "Dear Parent, $name has been marked present for $rollType roll call on $dateWord at $timeNow.";

                $curl = curl_init();
                curl_setopt_array($curl, [
                    CURLOPT_URL => "https://my.kudisms.net/api/sms",
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_CUSTOMREQUEST => "POST",
                    CURLOPT_POSTFIELDS => [
                        'token' => $smsToken,
                        'senderID' => $smsSender,
                        'recipients' => $guardianPhone,
                        'message' => $smsMsg,
                        'gateway' => '2'
                    ]
                ]);
                $smsResp = curl_exec($curl);
                curl_close($curl);

                $log = $connection->prepare(
                    "INSERT INTO sent_sms (senderID, recipients, message, response)
                     VALUES (?,?,?,?)"
                );
                $log->bind_param("ssss", $smsSender, $guardianPhone, $smsMsg, $smsResp);
                $log->execute();
            }

        } else {
            $message = "❌ Student not found in selected class";
            $message_type = 'error';
        }

    } else {
        $message = "❌ Missing required fields";
        $message_type = 'error';
    }
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Admin 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{background:#fff;padding:20px;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;font-weight:bold;margin-bottom:10px}
.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">📷 Admin QR Attendance</h3>

<div class="scan-box">
<form id="attendanceForm" method="POST">

<div class="mb-2">
<label>Class</label>
<select name="class" class="form-control" required>
<option value="">--- Select Class ---</option>
<?php foreach($classes as $cls): ?>
<option value="<?= htmlspecialchars($cls) ?>" <?= $selectedClass===$cls?'selected':'' ?>>
<?= htmlspecialchars($cls) ?>
</option>
<?php endforeach; ?>
</select>
</div>

<div class="mb-2">
<label>Date</label>
<input type="date" name="date" class="form-control" value="<?= htmlspecialchars($selectedDate) ?>" required>
</div>

<div class="mb-2">
<label>Term</label>
<select name="term" class="form-control" required>
<option <?= $selectedTerm==='First Term'?'selected':'' ?>>First Term</option>
<option <?= $selectedTerm==='Second Term'?'selected':'' ?>>Second Term</option>
<option <?= $selectedTerm==='Third Term'?'selected':'' ?>>Third Term</option>
</select>
</div>

<div class="mb-2">
<label>Session</label>
<select name="session" class="form-control" required>
<option value="">--- Select Session ---</option>
<?php foreach($sessions as $sess): ?>
<option value="<?= htmlspecialchars($sess) ?>" <?= $selectedSession===$sess?'selected':'' ?>>
<?= htmlspecialchars($sess) ?>
</option>
<?php endforeach; ?>
</select>
</div>

<div class="mb-2">
<label>Roll Call</label>
<select name="roll_type" class="form-control" required>
<option value="morning" <?= $selectedRoll==='morning'?'selected':'' ?>>Morning</option>
<option value="afternoon" <?= $selectedRoll==='afternoon'?'selected':'' ?>>Afternoon</option>
</select>
</div>

<input type="hidden" name="qr" id="qr_input">
</form>

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

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

<script>
const scannedLock = {};
function showToast(msg,type){
 let t=document.createElement('div');
 t.className='toast '+(type==='success'?'toast-success':'toast-error');
 t.innerText=msg;
 document.getElementById('toastContainer').appendChild(t);
 setTimeout(()=>t.remove(),5000);
}
function submitQR(code){
 if(scannedLock[code]) return;
 document.getElementById('qr_input').value=code;
 document.getElementById('attendanceForm').submit();
 scannedLock[code]=true;
 setTimeout(()=>delete scannedLock[code],5000);
}
Html5Qrcode.getCameras().then(c=>{
 let cam=c.find(x=>/back|rear|environment/i.test(x.label))||c[0];
 new Html5Qrcode("reader").start(cam.id,{fps:10,qrbox:250},submitQR);
});
<?php if($message): ?>
showToast("<?= addslashes($message) ?>","<?= $message_type ?>");
<?php endif; ?>
</script>
</body>
</html>
