<?php
session_start();
require_once("public/connection.php");

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

$staff_id = $_SESSION['staff'];

// Fetch KudiSMS token & senderID
$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'];
}

$message = '';
$message_type = ''; // 'success' or 'error'

// Preserve form values
$selectedClass   = $_POST['class'] ?? '';
$selectedDate    = $_POST['date'] ?? date('Y-m-d');
$selectedTerm    = $_POST['term'] ?? '';
$selectedSession = $_POST['session'] ?? '';
$selectedRoll    = $_POST['roll_type'] ?? '';

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) {

        // Fetch student & guardian_phone
        $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 if attendance already exists for this student/date/roll call
            $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
                    $stmtUpd = $connection->prepare("UPDATE student_attendance SET $col='Present', $time_col=? WHERE reg_number=? AND date=? AND class=?");
                    $stmtUpd->bind_param("ssss",$current_time,$reg_number,$date,$class);
                    $stmtUpd->execute();

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

                    // Send SMS
                    if($guardianPhone && $smsToken && $smsSender){
                        $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);
                        if($smsResp===false){ 
                            $smsResp = "Error: ".curl_error($curl); 
                            $message .= " ⚠️ SMS failed"; 
                            $message_type = 'error';
                        }
                        curl_close($curl);

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

                } else {
                    $message = "⚠️ $name has already been marked present for $rollType roll call";
                    $message_type = 'error';
                }
            } else {
                // Insert first attendance record
                $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 at $current_time";
                $message_type = 'success';

                // Send SMS
                if($guardianPhone && $smsToken && $smsSender){
                    $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);
                    if($smsResp===false){ 
                        $smsResp = "Error: ".curl_error($curl); 
                        $message .= " ⚠️ SMS failed"; 
                        $message_type = 'error';
                    }
                    curl_close($curl);

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

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

    } else {
        $message = "❌ Invalid QR Code or missing class/date";
        $message_type = 'error';
    }
}
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>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 { width:100%; 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; box-shadow:0 5px 15px rgba(0,0,0,.2);}
.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">📷 QR Code Attendance</h3>
<div class="scan-box">
<form id="attendanceForm" method="POST">
    <div class="mb-2">
        <label>Class</label>
        <select name="class" id="class" class="form-control" required>
            <option value="">Select Class</option>
            <?php
            $q=mysqli_query($connection,"SELECT DISTINCT class FROM teacher_classes WHERE teacher_id='$staff_id'");
            while($r=mysqli_fetch_assoc($q)){ 
                $sel = ($r['class'] === $selectedClass) ? "selected" : "";
                echo "<option value='{$r['class']}' $sel>{$r['class']}</option>"; 
            }
            ?>
        </select>
    </div>
    <div class="mb-2">
        <label>Date</label>
        <input type="date" name="date" id="date" class="form-control" value="<?= htmlspecialchars($selectedDate) ?>" required>
    </div>
    <div class="mb-2">
        <label>Term</label>
        <select name="term" id="term" class="form-control" required>
            <?php 
            $c=mysqli_fetch_assoc(mysqli_query($connection,"SELECT * FROM current_season")); 
            $selectedTerm = $selectedTerm ?: $c['current_term'];
            echo "<option>".htmlspecialchars($selectedTerm)."</option>"; 
            ?>
        </select>
    </div>
    <div class="mb-2">
        <label>Session</label>
        <select name="session" id="session" class="form-control" required>
            <?php 
            $selectedSession = $selectedSession ?: $c['current_session'];
            echo "<option>".htmlspecialchars($selectedSession)."</option>"; 
            ?>
        </select>
    </div>
    <div class="mb-2">
        <label>Roll Call</label>
        <select name="roll_type" id="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>
<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");

// Track recently scanned students to prevent double scanning for 5 seconds
const scannedLock = {};

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

function submitQR(regNumber){
    if(scannedLock[regNumber]){
        // Block rapid double scan
        showToast(`⚠️ ${regNumber} already scanned, wait a few seconds`, 'error');
        return;
    }

    qrInput.value = regNumber;
    attendanceForm.submit();

    // Lock student for 5 seconds
    scannedLock[regNumber] = true;
    setTimeout(()=>{
        delete scannedLock[regNumber];
    }, 5000);
}

// Initialize camera
Html5Qrcode.getCameras().then(cams=>{
    if(cams && cams.length){
        const backCam = cams.find(c=>/back|rear|environment/i.test(c.label)) || cams[0];
        new Html5Qrcode("reader").start(backCam.id,{fps:10, qrbox:250}, submitQR)
        .catch(err=>showToast("Cannot start camera: "+err,"error"));
    } else { showToast("No camera found","error"); }
}).catch(err=>showToast("Cannot access camera: "+err,"error"));

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