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

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

$staff_id = $_SESSION['staff'];
$staff = $connection->query("SELECT id, username, name FROM staff WHERE id='$staff_id'")->fetch_assoc();

$season = $connection->query("SELECT current_term, current_session FROM current_season LIMIT 1")->fetch_assoc();
$term = $season['current_term'];
$session_val = $season['current_session'];

$messages = [];

/* ================= GEO ================= */
$geo = $connection->query("
    SELECT latitude, longitude, radius_meters, is_active 
    FROM geo_fence_settings LIMIT 1
")->fetch_assoc();

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

    $device = $_POST['device'] ?? '';
    $lat    = $_POST['lat'] ?? null;
    $lng    = $_POST['lng'] ?? null;
    $roll   = $_POST['roll_type'] ?? '';
    $qr_code= $_POST['qr'] ?? '';
    $date   = $_POST['date'] ?? date('Y-m-d');
    $ip     = $_SERVER['REMOTE_ADDR'];
    $now    = date('H:i:s');

    if (!$device) {
        $messages[] = ["❌ Device not detected", "error"];
        goto END;
    }

    /* ========= DEVICE BINDING (SOFT WARN) ========= */
    $chk = $connection->prepare("
        SELECT id, device_hash 
        FROM staff_device_binding 
        WHERE staff_id=? LIMIT 1
    ");
    $chk->bind_param("i", $staff_id);
    $chk->execute();
    $res = $chk->get_result();

    $ua = $_SERVER['HTTP_USER_AGENT'];

    if ($res->num_rows === 0) {
        // first time bind
        $ins = $connection->prepare("
            INSERT INTO staff_device_binding
            (staff_id, device_hash, device_info, ip_address, first_bound_at, last_used_at, is_active)
            VALUES (?, ?, ?, ?, NOW(), NOW(), 1)
        ");
        $ins->bind_param("isss", $staff_id, $device, $ua, $ip);
        $ins->execute();
    } else {
        $row = $res->fetch_assoc();

        if ($row['device_hash'] !== $device) {
            $messages[] = ["⚠️ New device detected (attendance recorded)", "info"];
        }

        // NEVER INSERT AGAIN
        $upd = $connection->prepare("
            UPDATE staff_device_binding
            SET device_hash=?, device_info=?, ip_address=?, last_used_at=NOW(), is_active=1
            WHERE staff_id=?
        ");
        $upd->bind_param("sssi", $device, $ua, $ip, $staff_id);
        $upd->execute();
    }

    /* ========= LOG SCAN ========= */
    $log = $connection->prepare("
        INSERT INTO staff_attendance_logs
        (staff_id, ip_address, latitude, longitude, device_hash, roll_type, status)
        VALUES (?,?,?,?,?,?,?)
    ");
    $status = 'scanned';
    $log->bind_param("issddss", $staff_id, $ip, $lat, $lng, $device, $roll, $status);
    $log->execute();

    /* ========= QR ========= */
    $qr = $connection->query("
        SELECT qr_token FROM attendance_qr ORDER BY id DESC LIMIT 1
    ")->fetch_assoc();

    if (!$qr || $qr['qr_token'] !== $qr_code) {
        $messages[] = ["❌ Invalid QR Code", "error"];
        goto END;
    }

    $roll_col = $roll === 'morning' ? 'morning_roll' : 'afternoon_roll';
    $time_col = $roll === 'morning' ? 'time_morning' : 'time_afternoon';

    $check = $connection->prepare("
        SELECT * FROM staff_attendance 
        WHERE staff_id=? AND date=? AND term=? AND session=?
    ");
    $check->bind_param("isss", $staff_id, $date, $term, $session_val);
    $check->execute();
    $res = $check->get_result();

    if ($res->num_rows > 0) {

        $row = $res->fetch_assoc();
        if ($row[$roll_col] === 'Present') {
            $messages[] = ["⚠️ Attendance already marked", "info"];
        } else {

            if ($roll === 'morning') {
                $set = $connection->query("
                    SELECT morning_resumption, lateness_penalty 
                    FROM attendance_settings LIMIT 1
                ")->fetch_assoc();

                $late = (new DateTime($now) > new DateTime($set['morning_resumption'])) ? 1 : 0;
                $fee  = $late ? floatval($set['lateness_penalty']) : 0;

                $upd = $connection->prepare("
                    UPDATE staff_attendance SET
                    morning_roll='Present',
                    time_morning=?,
                    late_flag=?,
                    lateness_fee=?,
                    marked_by=?
                    WHERE id=?
                ");
                $upd->bind_param("siiid", $now, $late, $fee, $staff_id, $row['id']);
                $upd->execute();
            } else {
                $upd = $connection->prepare("
                    UPDATE staff_attendance SET
                    afternoon_roll='Present',
                    time_afternoon=?,
                    marked_by=?
                    WHERE id=?
                ");
                $upd->bind_param("ssi", $now, $staff_id, $row['id']);
                $upd->execute();
            }

            $messages[] = ["✅ Attendance marked successfully", "success"];
        }

    } else {

        // ======== NEW INSERT, treat morning and afternoon separately ========
        if ($roll === 'morning') {
            $set = $connection->query("
                SELECT morning_resumption, lateness_penalty 
                FROM attendance_settings LIMIT 1
            ")->fetch_assoc();

            $late = (new DateTime($now) > new DateTime($set['morning_resumption'])) ? 1 : 0;
            $fee  = $late ? floatval($set['lateness_penalty']) : 0;

            $morning = 'Present';
            $ins = $connection->prepare("
                INSERT INTO staff_attendance
                (staff_id, username, name, date, term, session,
                 morning_roll, time_morning, late_flag, marked_by, lateness_fee, created_at)
                VALUES (?,?,?,?,?,?,?,?,?,?,?,NOW())
            ");
            $ins->bind_param("isssssssiid",
                $staff_id,
                $staff['username'],
                $staff['name'],
                $date,
                $term,
                $session_val,
                $morning,
                $now,
                $late,
                $staff_id,
                $fee
            );
            $ins->execute();
            $messages[] = ["✅ Morning attendance marked" . ($late ? " ⚠️ Late ₦$fee" : ""), "success"];

        } else { // afternoon
            $afternoon = 'Present';
            $ins = $connection->prepare("
                INSERT INTO staff_attendance
                (staff_id, username, name, date, term, session,
                 afternoon_roll, time_afternoon, marked_by, created_at)
                VALUES (?,?,?,?,?,?,?,?,NOW())
            ");
            $ins->bind_param("issssssss",
                $staff_id,
                $staff['username'],
                $staff['name'],
                $date,
                $term,
                $session_val,
                $afternoon,
                $now,
                $staff_id
            );
            $ins->execute();
            $messages[] = ["✅ Afternoon attendance marked", "success"];
        }
    }
}
END:
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Staff QR Attendance</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://unpkg.com/html5-qrcode"></script>
<style>
.toast{padding:15px;color:#fff;margin-bottom:10px;border-radius:6px;font-weight:bold}
.toast-success{background:#28a745}
.toast-error{background:#dc3545}
.toast-info{background:#17a2b8}
#reader{max-width:420px;margin:auto}
</style>
</head>
<body>

<form method="POST" id="attendanceForm">
    <input type="hidden" name="qr" id="qr">
    <input type="hidden" name="device" id="device">
    <input type="hidden" name="lat" id="lat">
    <input type="hidden" name="lng" id="lng">
    <input type="date" name="date" value="<?=date('Y-m-d')?>">
    <select name="roll_type" id="roll_type">
        <option value="morning">Morning</option>
        <option value="afternoon">Afternoon</option>
    </select>
</form>

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

<script>
const deviceInput=document.getElementById("device");
const qrInput=document.getElementById("qr");
const latInput=document.getElementById("lat");
const lngInput=document.getElementById("lng");
const form=document.getElementById("attendanceForm");
const container=document.getElementById("toastContainer");

const GEOFENCE_ACTIVE = <?= $geo['is_active'] ? 'true':'false' ?>;
const SCHOOL_LAT = <?= floatval($geo['latitude']) ?>;
const SCHOOL_LNG = <?= floatval($geo['longitude']) ?>;

function toast(msg,type){
 const t=document.createElement("div");
 t.className="toast toast-"+type;
 t.innerText=msg;
 container.appendChild(t);
 setTimeout(()=>t.remove(),4000);
}

function getDistance(lat1, lon1, lat2, lon2){
 const R=6371e3;
 const φ1=lat1*Math.PI/180;
 const φ2=lat2*Math.PI/180;
 const Δφ=(lat2-lat1)*Math.PI/180;
 const Δλ=(lon2-lon1)*Math.PI/180;
 const a=Math.sin(Δφ/2)**2+
 Math.cos(φ1)*Math.cos(φ2)*Math.sin(Δλ/2)**2;
 return R*(2*Math.atan2(Math.sqrt(a),Math.sqrt(1-a)));
}

function deviceFingerprint(){
 return btoa(
  navigator.userAgent+
  screen.width+screen.height+
  navigator.language+
  navigator.platform
 );
}

function onScanSuccess(code){
 deviceInput.value=deviceFingerprint();
 qrInput.value=code;

 const loader=document.createElement("div");
 loader.style="position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,.5);color:#fff;display:flex;align-items:center;justify-content:center;font-size:1.4rem;z-index:9999";
 loader.innerText="Processing attendance...";
 document.body.appendChild(loader);

 navigator.geolocation.getCurrentPosition(pos=>{
   latInput.value=pos.coords.latitude;
   lngInput.value=pos.coords.longitude;

   if(GEOFENCE_ACTIVE){
     const d=getDistance(latInput.value,lngInput.value,SCHOOL_LAT,SCHOOL_LNG);
     toast(`📍 You are ${Math.round(d)} meters from school`,"info");
   }
   form.submit();
 },()=>{
   toast("⚠️ Location unavailable","info");
   form.submit();
 });
}

Html5Qrcode.getCameras().then(cams=>{
 const cam=cams.find(c=>/back|rear|environment/i.test(c.label))||cams[0];
 new Html5Qrcode("reader").start(
  { facingMode:{ exact:"environment" } },
  { fps:10, qrbox:250 },
  onScanSuccess
 );
});

<?php foreach($messages as $m): ?>
toast("<?=addslashes($m[0])?>","<?=$m[1]?>");
<?php endforeach; ?>
</script>

</body>
</html>
