<?php 
session_start();
$logkanwil = $_SESSION["logkanwil"]; 

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

require 'functions.php';

$id = $_GET["id"];
$sp = query("SELECT * FROM data_student WHERE id = $id")[0];

if (isset($_POST["tombolubah"])) {
    if ($_POST["tgl_lahir"] >= date("Y-m-d")) {
        echo "<script>
                alert('Tanggal lahir harus sebelum hari ini!');
                document.location.href = 'ubah.php?id=$id';
              </script>";
        exit;
    }

    // Simpan foto dari kamera jika ada
    if (!empty($_POST['foto_base64'])) {
        $data = $_POST['foto_base64'];
        $data = str_replace('data:image/jpeg;base64,', '', $data);
        $data = base64_decode($data);
        $fileName = uniqid() . ".jpg";
        file_put_contents("uploads/" . $fileName, $data);
        $_POST['foto'] = $fileName;
    }

    if (ubah($_POST) > 0) {
        echo "<script>
                alert('Data berhasil diubah!');
                document.location.href = 'index.php';
              </script>";
    } else {
        echo "<script>
                alert('Data gagal diubah!');
                document.location.href = 'index.php';
              </script>";
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>Ubah Data Student</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 10px;
        }
        h1 {
            font-size: 20px;
            text-align: center;
        }
        form {
            max-width: 400px;
            margin: auto;
            background: #f9f9f9;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 0 5px rgba(0,0,0,0.1);
        }
        table {
            width: 100%;
        }
        td {
            padding: 6px;
            vertical-align: middle;
        }
        input[type="text"], input[type="file"], input[type="date"] {
            width: 100%;
            padding: 6px;
            font-size: 14px;
        }
        button {
            width: 100%;
            padding: 10px;
            font-size: 14px;
        }
        .radio-group {
            display: flex;
            justify-content: space-between;
            padding: 4px 0;
        }
        @media screen and (max-width: 380px) {
            h1 {
                font-size: 18px;
            }
            input[type="text"], button {
                font-size: 12px;
                padding: 6px;
            }
            .radio-group {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>

<div class="mb-2 text-center">
    <span>USER: <?= $logkanwil ?></span>
    <br>
    <a href="logout.php">Logout</a> | 
    <a href="index.php">Home</a>
</div>

<h1>Ubah Data Student</h1>

<form action="" method="post">
    <input type="hidden" name="id" value="<?= $sp["id"]; ?>">
    <table>
        <tr>
            <td><label for="nama">Nama:</label></td>
            <td><input type="text" name="nama" id="nama" required maxlength="20" value="<?= $sp['nama']; ?>" onkeyup="this.value = this.value.toUpperCase()" autofocus></td>
        </tr>
        <tr>
            <td><label for="sekolah">Nama Sekolah:</label></td>
            <td><input type="text" name="sekolah" id="sekolah" required maxlength="50" value="<?= $sp['sekolah']; ?>" onkeyup="this.value = this.value.toUpperCase()"></td>
        </tr>
        <tr>
            <td><label for="kelas">Kelas:</label></td>
            <td><input type="text" name="kelas" id="kelas" required maxlength="5" value="<?= $sp['kelas']; ?>" onkeyup="this.value = this.value.toUpperCase()"></td>
        </tr>
        <tr>
            <td>Gender:</td>
            <td>
                <label><input type="radio" name="jk" value="Pria" <?= ($sp['jk'] == 'Pria') ? 'checked' : ''; ?>> Pria</label>
                <label style="margin-left: 15px;"><input type="radio" name="jk" value="Wanita" <?= ($sp['jk'] == 'Wanita') ? 'checked' : ''; ?>> Wanita</label>
            </td>
        </tr>
        <tr>
            <td><label for="tgl_lahir">Tgl Lahir:</label></td>
            <td><input required type="date" name="tgl_lahir" id="tgl_lahir" value="<?= date('Y-m-d', strtotime($sp['tgl_lahir'])); ?>"></td>
        </tr>
        <tr>
            <td><label for="wawa">No. WA:</label></td>
            <td><input type="text" name="wawa" id="wawa" required maxlength="100" value="<?= $sp['wawa']; ?>" onkeyup="this.value = this.value.toUpperCase()"></td>
        </tr>
        <tr>
            <td><label for="alamat">Alamat Tinggal:</label></td>
            <td><input type="text" name="alamat" id="alamat" required maxlength="100" value="<?= $sp['alamat']; ?>" onkeyup="this.value = this.value.toUpperCase()"></td>
        </tr>

         <tr>
            <td colspan="2">
                <label for="ramalan_ai">Ramalan AI:</label><br>
                <textarea name="ramalan_ai" id="ramalan_ai" rows="2" required style="width: 100%;"><?= $sp['ramalan_ai']; ?></textarea>
            </td>
        </tr>
        <tr>
            <td><label for="terima_uang">Uang Jajan Sebulan:</label></td>
            <td><input required type="text" name="terima_uang" id="terima_uang" size="5" value="<?= $sp['terima_uang']; ?>"></td>
        </tr>
        <tr>
            <td colspan="2">
                <label for="testimoni">Testimoni:</label><br>
                <textarea name="testimoni" id="testimoni" rows="5" required style="width: 100%;"><?= $sp['testimoni']; ?></textarea>
            </td>
        </tr>

        <!-- Ambil Foto -->
        <tr>
            <td colspan="2">
                <button type="button" class="btn btn-primary mb-2" onclick="startCamera()">Ambil Foto, lihat kamera!!!</button>
                <video id="camera" autoplay playsinline width="100%" style="display: none; border-radius: 8px;"></video>
                <canvas id="canvas" style="display:none;"></canvas>
                <input type="hidden" name="foto_base64" id="foto_base64">
            </td>
        </tr>

        <tr>
            <td colspan="2">
                <button class="btn btn-danger" type="submit" name="tombolubah">Ubah Data</button>
            </td>
        </tr>
    </table>
</form>

<!-- Suara klik -->
<audio id="shutterSound" src="kamera.mp3" preload="auto"></audio>

<script>
let streaming = false;
let video = document.getElementById('camera');
let canvas = document.getElementById('canvas');
let foto_base64 = document.getElementById('foto_base64');
let audio = document.getElementById('shutterSound');

function startCamera() {
    navigator.mediaDevices.getUserMedia({ video: true, audio: false })
        .then(function(stream) {
            video.style.display = 'block';
            video.srcObject = stream;
            streaming = true;

            showCountdown(3, () => {
                takeSnapshot();
                stopCamera(stream);
            });

        })
        .catch(function(err) {
            alert("Tidak bisa mengakses kamera!");
        });
}

function takeSnapshot() {
    if (streaming) {
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        canvas.getContext('2d').drawImage(video, 0, 0);
        let dataURL = canvas.toDataURL('image/jpeg');
        foto_base64.value = dataURL;
        audio.play(); // play suara klik
    }
}

function stopCamera(stream) {
    let tracks = stream.getTracks();
    tracks.forEach(track => track.stop());
    video.style.display = 'none';
}

function showCountdown(seconds, callback) {
    let countdownDiv = document.createElement('div');
    countdownDiv.style.position = 'fixed';
    countdownDiv.style.top = '50%';
    countdownDiv.style.left = '50%';
    countdownDiv.style.transform = 'translate(-50%, -50%)';
    countdownDiv.style.backgroundColor = 'rgba(0,0,0,0.8)';
    countdownDiv.style.color = 'white';
    countdownDiv.style.fontSize = '48px';
    countdownDiv.style.padding = '20px 40px';
    countdownDiv.style.borderRadius = '10px';
    countdownDiv.style.zIndex = 9999;
    countdownDiv.innerText = seconds;
    document.body.appendChild(countdownDiv);

    let interval = setInterval(() => {
        seconds--;
        if (seconds <= 0) {
            clearInterval(interval);
            document.body.removeChild(countdownDiv);
            callback(); // ambil foto
        } else {
            countdownDiv.innerText = seconds;
        }
    }, 1000);
}
</script>

</body>
</html>
