<?php
error_reporting(E_ALL);
date_default_timezone_set('Asia/Jakarta');
$tgl = date('d-m-Y H:i:s');

$logFile = 'siapa_berkunjung_indexstudent.txt';
$visitorIP = $_SERVER['REMOTE_ADDR'];
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';
$visitTime = date('Y-m-d H:i:s');
$logEntry = "$visitTime - IP: $visitorIP - User Agent: $userAgent" . PHP_EOL;
file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);

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

require 'functions.php';

$logkanwil = $_SESSION["logkanwil"];
$username = $_SESSION["username"];

if ($logkanwil == "") {
    header("Location: login.php");
    exit;
}

$keyword = $_GET['cari'] ?? '';
$where = ($logkanwil == "KP") ? "1" : "pengelola='$logkanwil'";

if (!empty($keyword)) {
    $safeKeyword = htmlspecialchars($keyword);
    $where .= " AND (nama LIKE '%$safeKeyword%' OR jk LIKE '%$safeKeyword%' OR sekolah LIKE '%$safeKeyword%'  OR kelas LIKE '%$safeKeyword%' OR alamat LIKE '%$safeKeyword%' OR ramalan_ai LIKE '%$safeKeyword%' OR testimoni LIKE '%$safeKeyword%')";
}

$perPage = 20;
$totalData = count(query("SELECT id FROM data_student WHERE $where"));
$totalPages = ceil($totalData / $perPage);
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$start = ($page - 1) * $perPage;

$moni = query("SELECT * FROM data_student WHERE $where ORDER BY nama LIMIT $start, $perPage");
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>Data Student</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="siswa.png">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
    <style>
        img {
            max-width: 60px;
            cursor: pointer;
            transition: transform 0.3s ease;
        }
        .zoom-img {
            max-width: 90vw;
            max-height: 90vh;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) scale(0) rotate(0deg);
            z-index: 1001;
            border: 4px solid white;
            box-shadow: 0 0 10px rgba(0,0,0,0.8);
            animation: zoomSpin 0.8s forwards ease-in-out;
        }
        @keyframes zoomSpin {
            0% {
                transform: translate(-50%, -50%) scale(0) rotate(0deg);
            }
            50% {
                transform: translate(-50%, -50%) scale(1.1) rotate(360deg);
            }
            100% {
                transform: translate(-50%, -50%) scale(1) rotate(720deg);
            }
        }
        .overlay {
            position: fixed;
            top: 0; left: 0;
            width: 100%; height: 100%;
            background-color: rgba(0,0,0,0.7);
            z-index: 1000;
        }
    </style>
</head>
<body class="container-fluid py-4">




<div class="d-flex align-items-center mb-4" style="gap: 20px;">
    <img src="homealone.jpg" alt="myfoto" style="
        opacity: 0.5;
        max-width: 120px;
        z-index: 0;
    ">
    <h2 class="mb-0">ABH's Student</h2>
</div>



<div class="mb-3 d-flex justify-content-between align-items-center flex-wrap">
    <div>
        <a href="tambah.php" class="btn btn-primary btn-sm">Tambah Data</a>
        <a href="grafik_jenkel1.php" class="btn btn-warning btn-sm">Grafik Venn</a>
        <a href="grafik_jenkel2.php" class="btn btn-success btn-sm">Grafik Bar</a>
        <a href="export_ke_excel/index.php" class="btn btn-primary btn-sm">Export Excel</a>
        <a href="tabel_ramalan_ai.php" class="btn btn-info btn-sm">Tb Ramalan AI</a>
            <a href="registrasi.php" class="btn btn-success btn-sm">ID Gov</a>
        <a href="logout.php" class="btn btn-danger btn-sm">Logout</a>
         <small><?= $tgl; ?> | USER: <?= $logkanwil; ?></small><br>
    </div>
    <form class="form-inline mt-2 mt-md-0" method="get">
        <input type="text" name="cari" class="form-control form-control-sm mr-2" placeholder="Cari..." value="<?= htmlspecialchars($keyword); ?>">
        <button type="submit" class="btn btn-sm btn-secondary">Cari</button>
    </form>
</div>

<table class="table table-bordered table-sm table-hover">
    <thead class="thead-dark">
        <tr>
            <th>No.</th>
            <th>Action</th>
            <th>Nama</th>
            <th>Nama Sekolah</th>
            <th>Kelas</th>
            <th>Gender</th>
            <th>Tgl Lahir</th>
            <th>No. WA</th>
            <th>Alamat Tinggal</th>
            <th>Ramalan AI</th>
            <th>Uang Jajan sebulan</th>
            <th>Foto</th>
            <th>Testimoni</th>
        </tr>
    </thead>
    <tbody>
    <?php if (count($moni) === 0): ?>
        <tr><td colspan="12" class="text-center text-muted">Data tidak ditemukan.</td></tr>
    <?php else: ?>
        <?php $i = $start + 1; foreach ($moni as $row): ?>
            <tr>
                <td><?= $i++; ?></td>
                <td>
                    <a href="ubah.php?id=<?= $row["id"]; ?>" class="btn btn-warning btn-sm">Ubah</a>
                    <a href="hapus.php?id=<?= $row["id"]; ?>" class="btn btn-sm" style="background-color: purple; color: white;" onclick="return confirm('Yakin ingin menghapus data <?= htmlspecialchars($row["nama"]); ?>?')">Hapus</a>
                    <a href="cetak_kw.php?id=<?= $row["id"]; ?>" class="btn btn-sm" style="background-color: green; color: white;">Cetak Uang Jajan</a>
                    <button class="btn btn-sm" style="background-color: blue; color: white;" onclick="bacaTestimoni('<?= htmlspecialchars($row["nama"]); ?>', `<?= htmlspecialchars($row["testimoni"]); ?>`)">Baca Testimoni</button>
                </td>
                <td><?= htmlspecialchars($row["nama"]); ?></td>
                <td><?= htmlspecialchars($row["sekolah"]); ?></td>
                <td><?= htmlspecialchars($row["kelas"]); ?></td>
                <td><?= htmlspecialchars($row["jk"]); ?></td>
                <td><?= date("d-m-Y", strtotime($row['tgl_lahir'])); ?></td>
                <td><?= htmlspecialchars($row["wawa"]); ?></td>
                <td><?= htmlspecialchars($row["alamat"]); ?></td>
                <td><?= htmlspecialchars($row["ramalan_ai"]); ?></td>
                <td><?= number_format($row['terima_uang'], 0, ",", "."); ?></td>
                <td>
                    <?php if (!empty($row["foto"])): ?>
                        <img src="uploads/<?= htmlspecialchars($row["foto"]) ?>" alt="foto" onclick="zoomImage(this)">
                    <?php else: ?>
                        <span class="text-muted">(Tidak ada)</span>
                    <?php endif; ?>
                </td>
                <td><?= nl2br(htmlspecialchars($row["testimoni"])); ?></td>
            </tr>
        <?php endforeach; ?>
    <?php endif; ?>
    </tbody>
</table>

<nav>
    <ul class="pagination justify-content-center">
        <?php for ($p = 1; $p <= $totalPages; $p++): ?>
            <li class="page-item <?= ($p == $page) ? 'active' : ''; ?>">
                <a class="page-link" href="?page=<?= $p ?>&cari=<?= urlencode($keyword) ?>"><?= $p ?></a>
            </li>
        <?php endfor; ?>
    </ul>
</nav>

<script>
function zoomImage(imgElement) {
    const src = imgElement.src;
    const audio1 = new Audio('pusing.mp3');
    const audio2 = new Audio('kamera.mp3');
    audio1.play();
    audio1.addEventListener('ended', () => { audio2.play(); });

    const zoomedImg = document.createElement("img");
    zoomedImg.src = src;
    zoomedImg.className = "zoom-img";
    zoomedImg.onclick = () => {
        document.body.removeChild(overlay);
        document.body.removeChild(zoomedImg);
    };

    const overlay = document.createElement("div");
    overlay.className = "overlay";
    overlay.onclick = () => {
        document.body.removeChild(overlay);
        document.body.removeChild(zoomedImg);
    };

    document.body.appendChild(overlay);
    document.body.appendChild(zoomedImg);
}


function bacaTestimoni(nama, testimoni) {
    const maxLength = 175;
    let currentPos = 0;

    function getNextPart(text, start, maxLength) {
        let end = start + maxLength;
        if (end >= text.length) return text.slice(start);

        let lastSpace = text.lastIndexOf(' ', end);
        if (lastSpace > start) {
            return text.slice(start, lastSpace);
        }
        return text.slice(start, end);
    }

    function readNextPart() {
        if (currentPos < testimoni.length) {
            let part = getNextPart(testimoni, currentPos, maxLength);
            currentPos += part.length + 1; // +1 untuk skip spasi
            const suara = new Audio(`tts.php?text=${encodeURIComponent(part)}&lang=id`);
            suara.play();
            suara.addEventListener('ended', readNextPart);
        }
    }

    // Putar sapaan 1x di awal
    const sapaan = new Audio(`tts.php?text=${encodeURIComponent(`Hai ${nama}, ini testimoni kamu.`)}&lang=id`);
    sapaan.play();
    sapaan.addEventListener('ended', readNextPart);
}


</script>

</body>
</html>
