<?php
require_once __DIR__ . '/config/db.php';

/* =============================
   GET LAST PRESENSI BY UID
============================= */
$uid = $_GET['uid'] ?? '';
$presensi = null;
$status   = '';
$foto     = '';

if ($uid !== '') {
    $stmt = $pdo->prepare("
        SELECT p.*, s.nama, s.nis, s.kelas, s.jurusan, s.rombel, s.foto
        FROM presensi p
        LEFT JOIN siswa s ON s.id = p.siswa_id
        WHERE p.uid = :uid
        ORDER BY p.created_at DESC
        LIMIT 1
    ");
    $stmt->execute([':uid'=>$uid]);
    $presensi = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($presensi) {
        $foto = $presensi['foto'] ? "/presensi_v1/upload/siswa/".$presensi['foto'] : "";

        if ($presensi['keterangan']=="H") $status="HADIR";
        else if ($presensi['keterangan']=="T") $status="TERLAMBAT";
    }
}

/* =============================
   TANGGAL INDONESIA
============================= */
$hariIndo = ['Sunday'=>'Minggu','Monday'=>'Senin','Tuesday'=>'Selasa','Wednesday'=>'Rabu','Thursday'=>'Kamis','Friday'=>'Jumat','Saturday'=>'Sabtu'];
$bulanIndo = ['01'=>'Januari','02'=>'Februari','03'=>'Maret','04'=>'April','05'=>'Mei','06'=>'Juni','07'=>'Juli','08'=>'Agustus','09'=>'September','10'=>'Oktober','11'=>'November','12'=>'Desember'];

$hari  = $hariIndo[date('l')];
$tgl   = date('d');
$bln   = $bulanIndo[date('m')];
$thn   = date('Y');
$formatTanggal = "$tgl $bln $thn";
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<title>Preview Presensi</title>
<link rel="stylesheet" href="/presensi_v1/assets/css/preview_attendance.css">
</head>

<body>

<button class="fullscreen-toggle" onclick="toggleFullscreen()">⤢ Fullscreen</button>

<!-- HEADER -->
<div class="header-area">
    <div class="header-title">PRESENSI v1</div>
    <div class="header-subtitle">Realtime Attendance Preview</div>
    <div class="date-time-wide">
        <div class="date-box glass" id="textTanggalHeader">
            <?= $hari . ', ' . $formatTanggal ?>
        </div>

        <div class="clock-box glass">
            <span id="jamRealtime">00:00:00</span>
            <span class="zona-waktu">WIB</span>
        </div>
    </div>
</div>

<!-- STANDBY -->
<div id="standbyBox" class="standby-box" style="display:none;">
    <div class="standby-title">STANDBY MODE</div>
    <div class="standby-desc">Presensi dibuka pukul 05.00 WIB</div>
</div>

<!-- PORTRAIT -->
<div id="portraitMode" class="preview-wrapper" style="display:none;">
    <div class="portrait-card glass">

        <div class="photo-frame">
            <?php if ($foto): ?>
                <img id="fotoBoxP" src="<?= $foto ?>">
            <?php else: ?>
                <img id="fotoBoxP" style="display:none;">
            <?php endif; ?>
        </div>

        <div class="portrait-info">
            <div class="student-name" id="textNamaP"><?= $presensi['nama'] ?? '-' ?></div>
            <div class="student-meta" id="textKelasP">
                <?= $presensi ? ($presensi['kelas']." ".$presensi['jurusan']."-".$presensi['rombel']) : '-' ?>
            </div>

            <div class="info-grid">
                <div>
                    <div class="info-label">NIS</div>
                    <div class="info-value" id="textNisP"><?= $presensi['nis'] ?? '-' ?></div>
                </div>
                <div>
                    <div class="info-label">Jam</div>
                    <div class="info-value" id="textJamP"><?= $presensi['waktu'] ?? '-' ?></div>
                </div>
                <div>
                    <div class="info-label">Tanggal</div>
                    <div class="info-value" id="textTglP">
                        <?= isset($presensi['tanggal']) ? date('d-m-Y', strtotime($presensi['tanggal'])) : '-' ?>
                    </div>
                </div>
                <div>
                    <div class="info-label">Status</div>
                    <span class="status-pill 
                        <?= $status=='HADIR' ? 'status-hadir' : '' ?> 
                        <?= $status=='TERLAMBAT' ? 'status-terlambat' : '' ?>"
                        id="textStatusP"
                        style="<?= $status ? '' : 'display:none;' ?>">
                        <?= $status ?>
                    </span>
                </div>
            </div>
        </div>

    </div>
</div>

<!-- LANDSCAPE -->
<div id="landscapeMode" class="landscape-wrapper" style="display:none;">

    <div class="photo-frame glass">
        <?php if ($foto): ?>
            <img id="fotoBoxL" src="<?= $foto ?>">
        <?php else: ?>
            <img id="fotoBoxL" style="display:none;">
        <?php endif; ?>
    </div>

    <div class="info-glass glass">

        <div class="student-name" id="textNamaL"><?= $presensi['nama'] ?? '-' ?></div>
        <div class="student-meta" id="textKelasL">
            <?= $presensi ? ($presensi['kelas']." ".$presensi['jurusan']."-".$presensi['rombel']) : '-' ?>
        </div>

        <div class="info-grid">
            <div>
                <div class="info-label">NIS</div>
                <div class="info-value" id="textNisL"><?= $presensi['nis'] ?? '-' ?></div>
            </div>
            <div>
                <div class="info-label">Jam</div>
                <div class="info-value" id="textJamL"><?= $presensi['waktu'] ?? '-' ?></div>
            </div>
            <div>
                <div class="info-label">Tanggal</div>
                <div class="info-value" id="textTglL">
                    <?= isset($presensi['tanggal']) ? date('d-m-Y', strtotime($presensi['tanggal'])) : '-' ?>
                </div>
            </div>
            <div>
                <div class="info-label">Status</div>
                <span class="status-pill
                    <?= $status=='HADIR' ? 'status-hadir' : '' ?> 
                    <?= $status=='TERLAMBAT' ? 'status-terlambat' : '' ?>"
                    id="textStatusL"
                    style="<?= $status ? '' : 'display:none;' ?>">
                    <?= $status ?>
                </span>
            </div>
        </div>
    </div>

</div>

<!-- JAM -->
<script>
function updateClock(){
    const now = new Date();
    document.getElementById("jamRealtime").textContent =
        now.toLocaleTimeString('id-ID',{hour12:false});
}
setInterval(updateClock,1000);
updateClock();
</script>

<!-- ORIENTATION AUTO SWITCH -->
<script>
function checkMode() {
    let portrait = window.innerHeight > window.innerWidth;
    document.getElementById("portraitMode").style.display = portrait ? "flex" : "none";
    document.getElementById("landscapeMode").style.display = portrait ? "none" : "flex";
}
window.addEventListener("resize", checkMode);
checkMode();
</script>

<!-- STANDBY -->
<script>
function handleStandbyMode(){
    let h=new Date().getHours();
    let standby=document.getElementById("standbyBox");
    let p=document.getElementById("portraitMode");
    let l=document.getElementById("landscapeMode");

    if (h>=16 || h<5){
        standby.style.display="block";
        p.style.display="none";
        l.style.display="none";
        return true;
    }
    standby.style.display="none";
    checkMode();
    return false;
}
setInterval(handleStandbyMode,1000);
</script>

<!-- AUTO UPDATE -->
<script>
setInterval(()=>{

    if (handleStandbyMode()) return;

    fetch("/presensi_v1/api/check_latest_tap.php")
    .then(r=>r.json())
    .then(data=>{
        if(!data.uid) return;

        let foto = data.foto ? "/presensi_v1/upload/siswa/"+data.foto : "";

        /* UPDATE BOTH MODES */
        ["P","L"].forEach(mode=>{

            let img = document.getElementById("fotoBox"+mode);
            if (foto){
                if (img.src !== foto){
                    img.src=foto;
                    img.style.display="block";
                }
            }

            document.getElementById("textNis"+mode).textContent = data.nis ?? "-";
            document.getElementById("textNama"+mode).textContent = data.nama ?? "-";
            document.getElementById("textKelas"+mode).textContent = 
                `${data.kelas} ${data.jurusan}-${data.rombel}`;
            document.getElementById("textJam"+mode).textContent = data.waktu ?? "-";

            if (data.tanggal){
                const d=new Date(data.tanggal);
                let dd=d.getDate().toString().padStart(2,'0');
                let mm=(d.getMonth()+1).toString().padStart(2,'0');
                let yy=d.getFullYear();
                document.getElementById("textTgl"+mode).textContent = `${dd}-${mm}-${yy}`;
            }

            let st=document.getElementById("textStatus"+mode);
            st.classList.remove("status-hadir","status-terlambat");

            let s=data.status;
            if (s=="H") s="HADIR";
            if (s=="T") s="TERLAMBAT";

            if (s=="HADIR"){
                st.style.display="inline-block";
                st.textContent="HADIR";
                st.classList.add("status-hadir");
            } else if (s=="TERLAMBAT"){
                st.style.display="inline-block";
                st.textContent="TERLAMBAT";
                st.classList.add("status-terlambat");
            } else st.style.display="none";

        });

    });

},1000);
</script>

<!-- FULLSCREEN -->
<script>
function toggleFullscreen(){
    let btn=document.querySelector('.fullscreen-toggle');
    if(!document.fullscreenElement){
        document.documentElement.requestFullscreen();
        btn.innerHTML="⤺ Exit Fullscreen";
    } else {
        document.exitFullscreen();
        btn.innerHTML="⤢ Fullscreen";
    }
}
</script>

</body>
</html>
