<?php

session_start();
define('SECURE_ACCESS', true);
require_once "koneksi.php";

/* SECURITY HEADER */
header("X-Frame-Options: SAMEORIGIN");
header("X-Content-Type-Options: nosniff");
header("X-XSS-Protection: 1; mode=block");

/* GENERATE CSRF TOKEN */
if(empty($_SESSION['csrf_token'])){
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

/* JIKA FORM DISUBMIT */
if(isset($_POST['simpan'])){

    /* RATE LIMIT ANTI SPAM */
    if(isset($_SESSION['last_submit'])){
        if(time() - $_SESSION['last_submit'] < 5){
            die("Terlalu cepat mengirim data");
        }
    }
    $_SESSION['last_submit'] = time();

    /* VALIDASI CSRF */
    if(!isset($_POST['csrf_token']) ||
       !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])){
        die("CSRF token tidak valid!");
    }

    unset($_SESSION['csrf_token']);
    /* SANITASI INPUT */
    $nama       = trim($_POST['nama_lengkap']);
    $identitas  = trim($_POST['nomor_identitas']);
    $alamat     = trim($_POST['alamat']);
    $hp         = trim($_POST['no_hp']);
    $pekerjaan  = trim($_POST['pekerjaan']);
    $bertemu    = trim($_POST['bertemu_dengan']);
    $keperluan  = trim($_POST['keperluan']);
    $fotoBase64 = $_POST['foto'] ?? '';

    /* VALIDASI IDENTITAS */
    if(strlen($identitas) < 8 || strlen($identitas) > 20){
        die("Nomor identitas tidak valid");
    }

    if(empty($fotoBase64)){
        echo "<script>alert('Foto belum diambil');</script>";
        exit;
    }

    if(strlen($fotoBase64) > 3000000){
        die("Data gambar terlalu besar");
    }

    if(!preg_match('/^data:image\/jpeg;base64,/', $fotoBase64)){
        die("Format foto tidak valid");
    }

    $fotoBase64 = str_replace('data:image/jpeg;base64,', '', $fotoBase64);
    $fotoBase64 = str_replace(' ', '+', $fotoBase64);
    $data = base64_decode($fotoBase64);

    if($data === false){
        die("Gagal decode gambar");
    }

    if(strlen($data) > 2 * 1024 * 1024){
        die("Ukuran foto terlalu besar (maksimal 2MB)");
    }

    if(getimagesizefromstring($data) === false){
        die("File bukan gambar valid");
    }

    /* FOLDER UPLOAD */
    $folder = __DIR__ . "/upload/";

    if(!is_dir($folder)){
        mkdir($folder, 0755, true);
    }

    $nama_file = "foto_" . bin2hex(random_bytes(8)) . ".jpg";

    if(!file_put_contents($folder.$nama_file, $data)){
        die("Gagal menyimpan foto");
    }

    /* INSERT DATABASE */
    $stmt = $conn->prepare("INSERT INTO survey_responden
    (nama_lengkap, nomor_identitas, alamat, no_hp, pekerjaan, foto, bertemu_dengan, keperluan)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?)");

    $stmt->bind_param("ssssssss",
        $nama,
        $identitas,
        $alamat,
        $hp,
        $pekerjaan,
        $nama_file,
        $bertemu,
        $keperluan
    );

    if(!$stmt->execute()){
        error_log($stmt->error);
        die("Terjadi kesalahan sistem");
    }

    $_SESSION['responden_id'] = $conn->insert_id;

    $stmt->close();

    echo "<script>alert('Data berhasil disimpan'); window.location='index.php';</script>";
    exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">

<style>
body{
font-family: Arial;
background:#f2f2f2;
}

.container{
max-width:600px;
margin:40px auto;
background:white;
padding:20px;
border-radius:12px;
box-shadow:0 2px 8px rgba(0,0,0,0.1);
}

h2{
text-align:center;
margin-bottom:20px;
}

input, textarea{
width:100%;
padding:10px;
margin:5px 0 15px;
border-radius:8px;
border:1px solid #ccc;
}

button{
padding:12px 25px;
background:#8B2E2E;
color:white;
border:none;
border-radius:8px;
font-weight:bold;
cursor:pointer;
}

.submit-btn{
width:100%;
margin-top:10px;
}

.camera-wrapper{
position:relative;
width:320px;       /* samakan dengan max-width video */
margin:15px auto;  /* biar tetap di tengah */
}

video{
  width:100%;
  border-radius:12px;
  display:block;
  transform: scaleX(-1); /* mirror preview */
}

.ambil-btn{
position:absolute;
bottom:15px;
left:50%;
transform:translateX(-50%);
padding:10px 25px;
background:#8B2E2E;
color:white;
border:none;
border-radius:30px;
font-weight:bold;
cursor:pointer;
}

#ulangBtn{
background:#555;
}

canvas{
display:none;
}
</style>
</head>

<body>

<?php include "banner.php"; ?>

<div class="container">

<h2>Buku Tamu</h2>

<form method="POST">
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
<input type="text" name="nama_lengkap" placeholder="Nama" required>
<input type="text" name="nomor_identitas" placeholder="Nomor KTP / SIM" required>
<input type="text" name="alamat" placeholder="Alamat" required>

<input type="text" name="no_hp" placeholder="No HP" maxlength="15"
oninput="this.value = this.value.replace(/[^0-9]/g, '')" required>

<input type="text" name="pekerjaan" placeholder="Pekerjaan" required>

<label><b>Ambil Foto Selfie</b></label>

<div class="camera-wrapper">
    <video id="video" autoplay playsinline></video>

    <button type="button" id="ambilBtn" class="ambil-btn" onclick="ambilFoto()">Ambil</button>

    <br><br>
    <img id="preview" style="display:none; max-width:320px; border-radius:10px;">
    <button type="button" id="ulangBtn" class="ambil-btn"
    style="display:none;"
    onclick="ambilUlang()">Ambil Ulang</button>
</div>

<canvas id="canvas"></canvas>
<input type="hidden" name="foto" id="foto">

<input type="text" name="bertemu_dengan" placeholder="Bertemu dengan" required>
<textarea name="keperluan" placeholder="Keperluan" required></textarea>

<button type="submit" name="simpan" class="submit-btn">Submit</button>

</form>

</div>

<script>
const video = document.getElementById('video');
const canvas = document.getElementById('canvas');
const fotoInput = document.getElementById('foto');
const preview = document.getElementById('preview');

let stream;

function startCamera(){

if(!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia){
alert("Browser tidak mendukung kamera");
return;
}

navigator.mediaDevices.getUserMedia({
audio: false,
video: {
    facingMode: { ideal: "user" },
    width: { ideal: 640 },
    height: { ideal: 480 }
}
})
.then(s => {

stream = s;
video.srcObject = stream;

video.style.display = "block";
preview.style.display = "none";

document.getElementById("ambilBtn").style.display = "inline-block";
document.getElementById("ulangBtn").style.display = "none";

})
.catch(err => {

console.log(err);
alert("Kamera tidak bisa diakses. Pastikan izin kamera diaktifkan di browser.");

});
}

function stopCamera(){
if(stream){
stream.getTracks().forEach(track => track.stop());
}
}

function ambilFoto(){
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;

const ctx = canvas.getContext('2d');

/* balik lagi supaya foto tidak mirror */
ctx.translate(canvas.width, 0);
ctx.scale(-1, 1);

ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

let imageData = canvas.toDataURL("image/jpeg", 0.7);
fotoInput.value = imageData;

preview.src = imageData;
preview.style.display = "block";

stopCamera();
video.style.display = "none";

document.getElementById("ambilBtn").style.display = "none";
document.getElementById("ulangBtn").style.display = "inline-block";
}

function ambilUlang(){
fotoInput.value = "";
startCamera();
}

document.querySelector("form").addEventListener("submit", function(e){
if(fotoInput.value == ""){
alert("Foto wajib diambil terlebih dahulu!");
e.preventDefault();
}
});

startCamera();
</script>

</body>
</html>
