<?php

include '../config/koneksi.php';
include '../session.php';

$role_kadiv = [
    'kadiv_ops',
    'kadiv_cs',
    'kadiv_kasir',
    'kadiv_gudang',
    'merchandiser',
    'Human_capital',
    'marcom',
    'It'
];

if(!in_array($_SESSION['role'], $role_kadiv)){
    die("Akses ditolak");
}

$id_checklist = (int)($_GET['id'] ?? 0);
$id_user      = $_SESSION['id_user'];
$role_user    = $_SESSION['role']; // ✅ ambil role user yang login
$tanggal      = date('Y-m-d');

if($id_checklist == 0){
    header("Location: dashboard.php");
    exit;
}

// ✅ Cek checklist berdasarkan role user yang login, bukan hardcode 
$role_esc = mysqli_real_escape_string($conn, $role_user);

$check = mysqli_query($conn,"
    SELECT cm.*
    FROM checklist_master cm
    JOIN checklist_pic cp ON cm.id_checklist = cp.id_checklist
    WHERE cm.id_checklist = '$id_checklist'
    AND   cm.status       = 'aktif'
    AND   cp.jabatan      = '$role_esc'
    LIMIT 1
");

$data = mysqli_fetch_assoc($check);

// Fallback: cek di kolom jabatan di checklist_master
if(!$data){
    $check2 = mysqli_query($conn,"
        SELECT * FROM checklist_master
        WHERE id_checklist = '$id_checklist'
        AND   status       = 'aktif'
        AND   jabatan LIKE '%$role_esc%'
        LIMIT 1
    ");
    $data = mysqli_fetch_assoc($check2);
}

if(!$data){
    echo "<script>alert('Checklist tidak ditemukan atau tidak sesuai jabatan Anda'); window.location='dashboard.php';</script>";
    exit;
}

$cek = mysqli_query($conn,"
    SELECT id_harian FROM checklist_harian
    WHERE id_user      = '$id_user'
    AND   id_checklist = '$id_checklist'
    AND   tanggal      = '$tanggal'
    LIMIT 1
");

if(mysqli_num_rows($cek) > 0){
    echo "<script>alert('Checklist ini sudah dikerjakan hari ini'); window.location='dashboard.php';</script>";
    exit;
}

$bukti_foto = (int)($data['foto_wajib'] ?? 0);

$foto_mode_db = $data['foto_mode'] ?? 'keduanya';

if($foto_mode_db == 'kamera'){
    $sumber_foto = 'kamera';
} elseif($foto_mode_db == 'upload'){
    $sumber_foto = 'upload';
} else {
    $sumber_foto = 'both';
}

if(isset($_POST['simpan'])){

    $keterangan = mysqli_real_escape_string($conn, $_POST['keterangan'] ?? '');
    $foto       = '';
    $upload_dir = '../upload/';

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

    $aktif_mode = $sumber_foto;
    if($sumber_foto == 'both'){
        $aktif_mode = !empty($_POST['foto_camera_base64']) ? 'kamera' : 'upload';
    }

    if($aktif_mode == 'kamera' && !empty($_POST['foto_camera_base64'])){

        $base64_str = $_POST['foto_camera_base64'];

        if(preg_match('/^data:image\/(\w+);base64,/', $base64_str, $m)){

            $ext = $m[1] == 'jpeg' ? 'jpg' : $m[1];

            $allowed = ['jpg','png','webp'];
            if(!in_array($ext, $allowed)){
                $error_foto = "Format foto dari kamera tidak didukung.";
            } else {
                $data_img = substr($base64_str, strpos($base64_str, ',') + 1);
                $data_img = base64_decode($data_img);

                if($data_img === false){
                    $error_foto = "Gagal memproses foto dari kamera.";
                } elseif(strlen($data_img) > 5 * 1024 * 1024){
                    $error_foto = "Ukuran foto maksimal 5 MB.";
                } else {
                    $foto = time().'_'.rand(1000,9999).'.'.$ext;
                    file_put_contents($upload_dir.$foto, $data_img);
                }
            }

        } else {
            $error_foto = "Format data foto tidak valid.";
        }

    } elseif(!empty($_FILES['foto_upload']['name']) && $_FILES['foto_upload']['error'] == 0){

        $allowed = ['jpg','jpeg','png','gif','webp'];
        $ext     = strtolower(pathinfo($_FILES['foto_upload']['name'], PATHINFO_EXTENSION));

        if(!in_array($ext, $allowed)){
            $error_foto = "Format foto tidak didukung. Gunakan JPG, PNG, atau WEBP.";
        } elseif($_FILES['foto_upload']['size'] > 5 * 1024 * 1024){
            $error_foto = "Ukuran foto maksimal 5 MB.";
        } else {
            $foto = time().'_'.rand(1000,9999).'.'.$ext;
            move_uploaded_file($_FILES['foto_upload']['tmp_name'], $upload_dir.$foto);
        }

    } elseif($bukti_foto === 1){
        $error_foto = "Foto bukti wajib diisi.";
    }

    if(!isset($error_foto)){

        $q = mysqli_query($conn,"
            INSERT INTO checklist_harian
                (tanggal, id_user, id_checklist, status, keterangan, foto, waktu_selesai)
            VALUES
                ('$tanggal','$id_user','$id_checklist','Selesai','$keterangan','$foto',NOW())
        ");

        if($q){
            echo "<script>
                alert('Checklist berhasil disimpan! ✅');
                window.location='dashboard.php';
            </script>";
            exit;
        } else {
            $error_simpan = "Gagal menyimpan: " . mysqli_error($conn);
        }
    }
}

$nama_checklist = $data['job_list'] ?? $data['nama_checklist'] ?? 'Checklist';
$job_desc       = $data['job_desc'] ?? '';
$waktu          = $data['waktu'] ?? '';
$jenis          = $data['jenis'] ?? '';

// ✅ Label jabatan untuk ditampilkan di meta bar (lebih rapi dari role mentah)
$label_jabatan  = ucwords(str_replace('_', ' ', $role_user));

$label_foto = 'Foto Bukti';
$sub_text   = 'JPG, PNG, WEBP — maks. 5 MB';

if($sumber_foto == 'kamera'){
    $label_foto = 'Foto Bukti (Wajib via Kamera)';
    $sub_text   = 'Ambil foto langsung dari kamera laptop/HP — maks. 5 MB';
} elseif($sumber_foto == 'upload'){
    $label_foto = 'Foto Bukti (Upload File)';
    $sub_text   = 'Upload dari galeri/file — JPG, PNG, WEBP, maks. 5 MB';
} else {
    $label_foto = 'Foto Bukti (Kamera atau Upload)';
    $sub_text   = 'Ambil foto atau upload — JPG, PNG, WEBP, maks. 5 MB';
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Kerjakan Checklist — <?= htmlspecialchars($nama_checklist) ?></title>
<link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@300;400;500;600;700&family=Space+Mono:wght@400;700&display=swap" rel="stylesheet">
<style>

*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

:root {
    --green-400: #16a34a;
    --green-500: #15803d;
    --green-600: #166534;
    --green-700: #14532d;

    --green-glow:   rgba(22, 163, 74, 0.10);
    --green-border: rgba(22, 163, 74, 0.22);
    --green-border-h: rgba(22, 163, 74, 0.45);

    --surface:   #f8fafb;
    --surface-1: #ffffff;
    --surface-2: #f1f5f2;
    --surface-3: #e6f0e9;

    --text:   #111827;
    --text-2: #374151;
    --text-3: #4b7a5c;
    --text-m: #9ca3af;

    --danger:    #dc2626;
    --danger-bg: rgba(220, 38, 38, 0.06);
    --danger-br: rgba(220, 38, 38, 0.2);
}

body {
    font-family: 'DM Sans', sans-serif;
    background: var(--surface);
    min-height: 100vh;
    display: flex;
    align-items: flex-start;
    justify-content: center;
    padding: 40px 16px 60px;
    color: var(--text);
}

.page-wrap {
    width: 100%;
    max-width: 580px;
    animation: fadeUp 0.45s cubic-bezier(0.16,1,0.3,1) both;
}

.btn-back {
    display: inline-flex;
    align-items: center;
    gap: 7px;
    color: var(--text-3);
    font-size: 0.82rem;
    font-weight: 500;
    text-decoration: none;
    margin-bottom: 20px;
    padding: 6px 12px 6px 8px;
    border-radius: 8px;
    border: 1px solid transparent;
    transition: color 0.2s, background 0.2s, border-color 0.2s;
}

.btn-back:hover {
    color: var(--green-400);
    background: var(--green-glow);
    border-color: var(--green-border);
}

.btn-back svg {
    width: 16px; height: 16px;
    stroke: currentColor; fill: none;
    stroke-width: 2; stroke-linecap: round; stroke-linejoin: round;
    flex-shrink: 0;
}

.form-card {
    background: var(--surface-1);
    border: 1px solid var(--green-border);
    border-radius: 18px;
    overflow: hidden;
    box-shadow: 0 2px 16px rgba(0,0,0,0.07), 0 1px 4px rgba(0,0,0,0.04);
    transition: border-color 0.3s, box-shadow 0.3s;
}

.form-card:hover {
    border-color: var(--green-border-h);
    box-shadow: 0 4px 28px rgba(22,163,74,0.10), 0 2px 8px rgba(0,0,0,0.06);
}

.card-stripe {
    height: 3px;
    background: linear-gradient(90deg, var(--green-700), var(--green-500), var(--green-400));
    background-size: 200% 100%;
    animation: shimmer 3s linear infinite;
}

.card-head {
    padding: 22px 28px 18px;
    background: #f0fdf4;
    border-bottom: 1px solid var(--green-border);
    display: flex;
    align-items: flex-start;
    gap: 14px;
}

.head-icon {
    width: 44px; height: 44px;
    border-radius: 12px;
    background: #dcfce7;
    border: 1px solid var(--green-border);
    display: flex; align-items: center; justify-content: center;
    flex-shrink: 0;
    font-size: 20px;
}

.head-text h2 {
    font-size: 1rem;
    font-weight: 700;
    color: var(--text);
    line-height: 1.4;
    margin-bottom: 4px;
}

.head-meta {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
    margin-top: 2px;
}

.head-meta-pill {
    font-size: 0.68rem;
    font-family: 'Space Mono', monospace;
    color: var(--green-600);
    background: #dcfce7;
    border: 1px solid var(--green-border);
    padding: 2px 8px;
    border-radius: 999px;
}

.info-box {
    margin: 18px 28px 0;
    background: #f0fdf4;
    border: 1px solid var(--green-border);
    border-radius: 10px;
    padding: 12px 14px;
    font-size: 0.8rem;
    color: var(--text-2);
    line-height: 1.6;
    display: none;
}

.info-box.show { display: block; }

.card-body { padding: 22px 28px 26px; }

.alert-err {
    background: var(--danger-bg);
    border: 1px solid var(--danger-br);
    border-radius: 10px;
    color: var(--danger);
    font-size: 0.83rem;
    padding: 11px 14px;
    margin-bottom: 18px;
    display: flex;
    align-items: center;
    gap: 8px;
}

.field { margin-bottom: 20px; }

.field label {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 0.73rem;
    font-weight: 600;
    color: var(--text-3);
    letter-spacing: 0.08em;
    text-transform: uppercase;
    margin-bottom: 9px;
}

.field label svg {
    width: 13px; height: 13px;
    stroke: currentColor; fill: none;
    stroke-width: 2; stroke-linecap: round; stroke-linejoin: round;
    opacity: 0.7;
}

.file-drop {
    position: relative;
    border: 1.5px dashed var(--green-border);
    border-radius: 12px;
    background: var(--surface-2);
    padding: 28px 20px;
    text-align: center;
    cursor: pointer;
    transition: border-color 0.2s, background 0.2s;
    overflow: hidden;
}

.file-drop:hover {
    border-color: var(--green-400);
    background: #f0fdf4;
}

.file-drop input[type="file"] {
    position: absolute; inset: 0;
    opacity: 0; cursor: pointer;
    width: 100%; height: 100%;
}

.file-drop-icon  { font-size: 28px; margin-bottom: 8px; display: block; }
.file-drop-text  { font-size: 0.83rem; color: var(--text-2); font-weight: 500; }
.file-drop-sub   { font-size: 0.73rem; color: var(--text-m); margin-top: 4px; }
.file-name-preview {
    margin-top: 10px;
    font-size: 0.75rem;
    color: var(--green-500);
    font-family: 'Space Mono', monospace;
    min-height: 18px;
}

.source-toggle {
    display: flex;
    gap: 10px;
    margin-bottom: 14px;
}

.source-btn {
    flex: 1;
    padding: 11px 14px;
    border: 1.5px solid var(--green-border);
    border-radius: 10px;
    background: var(--surface-2);
    color: var(--text-2);
    font-family: 'DM Sans', sans-serif;
    font-size: 0.82rem;
    font-weight: 600;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    transition: all 0.2s;
}

.source-btn.active {
    background: #dcfce7;
    border-color: var(--green-400);
    color: var(--green-700);
    box-shadow: 0 0 0 3px var(--green-glow);
}

.source-btn:hover { border-color: var(--green-400); }

.camera-box {
    border: 1.5px dashed var(--green-border);
    border-radius: 12px;
    background: var(--surface-2);
    padding: 16px;
    text-align: center;
}

#cameraPreview,
#cameraResult {
    width: 100%;
    border-radius: 10px;
    background: #000;
    display: block;
}

.camera-actions {
    display: flex;
    gap: 10px;
    margin-top: 12px;
}

.field textarea {
    width: 100%;
    background: var(--surface-2);
    border: 1px solid #d1d5db;
    border-radius: 12px;
    color: var(--text);
    font-family: 'DM Sans', sans-serif;
    font-size: 0.88rem;
    padding: 13px 16px;
    resize: vertical;
    min-height: 110px;
    outline: none;
    transition: border-color 0.22s, background 0.22s, box-shadow 0.22s;
    line-height: 1.6;
}

.field textarea::placeholder { color: var(--text-m); }

.field textarea:focus {
    background: #ffffff;
    border-color: var(--green-400);
    box-shadow: 0 0 0 3px var(--green-glow);
}

.btn-submit {
    width: 100%;
    height: 52px;
    border: none;
    border-radius: 13px;
    font-family: 'DM Sans', sans-serif;
    font-size: 0.95rem;
    font-weight: 700;
    color: #fff;
    background: linear-gradient(135deg, var(--green-700), var(--green-500), var(--green-400));
    background-size: 200% 200%;
    cursor: pointer;
    display: flex; align-items: center; justify-content: center;
    gap: 9px;
    position: relative;
    overflow: hidden;
    transition: background-position 0.4s, transform 0.18s, box-shadow 0.18s;
    box-shadow: 0 4px 14px rgba(22,163,74,0.28);
    margin-top: 8px;
}

.btn-submit:hover {
    background-position: right center;
    transform: translateY(-2px);
    box-shadow: 0 8px 24px rgba(22,163,74,0.35);
}
.btn-submit:active { transform: translateY(1px); }

.btn-submit::after {
    content: '';
    position: absolute;
    top: 0; left: -60%;
    width: 40%; height: 100%;
    background: linear-gradient(to right, transparent, rgba(255,255,255,0.18), transparent);
    transform: skewX(-20deg);
    transition: left 0.6s;
}

.btn-submit:hover::after { left: 130%; }

.btn-submit svg {
    width: 17px; height: 17px;
    stroke: currentColor; fill: none;
    stroke-width: 2.2; stroke-linecap: round; stroke-linejoin: round;
    flex-shrink: 0;
}

.meta-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 13px 28px;
    border-top: 1px solid var(--green-border);
    background: #f0fdf4;
    flex-wrap: wrap;
    gap: 8px;
}

.meta-item {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 0.71rem;
    color: var(--text-m);
    font-family: 'Space Mono', monospace;
}

.meta-item span {
    color: var(--green-600);
    font-weight: 700;
}

@keyframes fadeUp {
    from { opacity: 0; transform: translateY(18px); }
    to   { opacity: 1; transform: translateY(0); }
}

@keyframes shimmer {
    0%   { background-position: 200% 0; }
    100% { background-position: -200% 0; }
}

</style>
</head>
<body>

<div class="page-wrap">

    <a href="dashboard.php" class="btn-back">
        <svg viewBox="0 0 24 24"><polyline points="15 18 9 12 15 6"/></svg>
        Kembali ke Dashboard
    </a>

    <div class="form-card">

        <div class="card-stripe"></div>

        <div class="card-head">
            <div class="head-icon">✅</div>
            <div class="head-text">
                <h2><?= htmlspecialchars($nama_checklist) ?></h2>
                <div class="head-meta">
                    <?php if($waktu): ?>
                    <span class="head-meta-pill">🕐 <?= htmlspecialchars($waktu) ?></span>
                    <?php endif; ?>
                    <?php if($jenis): ?>
                    <span class="head-meta-pill">📋 <?= htmlspecialchars($jenis) ?></span>
                    <?php endif; ?>
                    <span class="head-meta-pill">📅 <?= date('d/m/Y') ?></span>
                </div>
            </div>
        </div>

        <?php if(!empty($job_desc)): ?>
        <div class="info-box show">
            📝 <?= htmlspecialchars($job_desc) ?>
        </div>
        <?php endif; ?>

        <div class="card-body">

            <?php if(isset($error_foto)): ?>
            <div class="alert-err">⚠️ <?= htmlspecialchars($error_foto) ?></div>
            <?php endif; ?>

            <?php if(isset($error_simpan)): ?>
            <div class="alert-err">❌ <?= htmlspecialchars($error_simpan) ?></div>
            <?php endif; ?>

            <form method="POST" enctype="multipart/form-data" id="checklistForm">

                <div class="field">
                    <label>
                        <svg viewBox="0 0 24 24"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
                        <?= htmlspecialchars($label_foto) ?><?= $bukti_foto ? ' *' : ' (Opsional)' ?>
                    </label>

                    <?php if($sumber_foto == 'both'): ?>
                    <div class="source-toggle">
                        <button type="button" class="source-btn active" id="btnKamera" onclick="setSource('kamera')">
                            📸 Kamera
                        </button>
                        <button type="button" class="source-btn" id="btnUpload" onclick="setSource('upload')">
                            🖼️ Upload File
                        </button>
                    </div>
                    <?php endif; ?>

                    <div id="cameraArea" style="<?= ($sumber_foto == 'upload') ? 'display:none;' : '' ?>">
                        <div class="camera-box">
                            <video id="cameraPreview" autoplay playsinline style="display:none;"></video>
                            <canvas id="cameraCanvas" style="display:none;"></canvas>
                            <img id="cameraResult" style="display:none;">
                            <div class="camera-actions">
                                <button type="button" class="source-btn" id="btnStartCam" onclick="startCamera()">
                                    📸 Buka Kamera
                                </button>
                                <button type="button" class="source-btn" id="btnCapture" onclick="captureCamera()" style="display:none;">
                                    📷 Ambil Foto
                                </button>
                                <button type="button" class="source-btn" id="btnRetake" onclick="startCamera()" style="display:none;">
                                    🔄 Ambil Ulang
                                </button>
                            </div>
                            <div class="file-drop-sub" style="margin-top:10px;">
                                <?= htmlspecialchars($sub_text) ?>
                            </div>
                        </div>
                    </div>

                    <div class="file-drop" id="dropArea" style="<?= ($sumber_foto == 'kamera') ? 'display:none;' : '' ?>">
                        <input type="file" name="foto_upload" accept="image/*"
                               id="fotoInputUpload"
                               onchange="showFileName(this)">
                        <span class="file-drop-icon">🖼️</span>
                        <div class="file-drop-text">Klik atau seret foto ke sini</div>
                        <div class="file-drop-sub"><?= htmlspecialchars($sub_text) ?></div>
                        <div class="file-name-preview" id="filePreview"></div>
                    </div>

                    <input type="hidden" name="foto_camera_base64" id="fotoCameraBase64">
                </div>

                <div class="field">
                    <label>
                        <svg viewBox="0 0 24 24"><line x1="17" y1="10" x2="3" y2="10"/><line x1="21" y1="6" x2="3" y2="6"/><line x1="21" y1="14" x2="3" y2="14"/><line x1="17" y1="18" x2="3" y2="18"/></svg>
                        Keterangan
                    </label>
                    <textarea name="keterangan"
                              placeholder="Tuliskan keterangan atau catatan (opsional)…"></textarea>
                </div>

                <button type="submit" name="simpan" class="btn-submit">
                    <svg viewBox="0 0 24 24"><polyline points="20 6 9 17 4 12"/></svg>
                    Simpan Checklist
                </button>

            </form>
        </div>

        <!-- ✅ Meta bar: jabatan ditampilkan dinamis sesuai role login -->
        <div class="meta-bar">
            <div class="meta-item">
                👤 <span><?= htmlspecialchars($_SESSION['nama'] ?? '') ?></span>
            </div>
            <div class="meta-item">
                📅 <span><?= date('d M Y') ?></span>
            </div>
            <div class="meta-item">
                🏷️ <span><?= htmlspecialchars($label_jabatan) ?></span>
            </div>
        </div>

    </div>
</div>

<script>
const sumberFoto = <?= json_encode($sumber_foto) ?>;
const wajibFoto  = <?= json_encode((bool)$bukti_foto) ?>;
let stream = null;

function showFileName(input) {
    const preview = document.getElementById('filePreview');
    if (input.files && input.files[0]) {
        const f    = input.files[0];
        const size = (f.size / 1024).toFixed(1);
        preview.textContent = '📎 ' + f.name + ' (' + size + ' KB)';
    }
}

function setSource(mode) {
    const cameraArea = document.getElementById('cameraArea');
    const dropArea   = document.getElementById('dropArea');

    if(mode == 'kamera'){
        cameraArea.style.display = 'block';
        dropArea.style.display   = 'none';
        document.getElementById('btnKamera').classList.add('active');
        document.getElementById('btnUpload').classList.remove('active');
        document.getElementById('fotoInputUpload').value = '';
        document.getElementById('filePreview').textContent = '';
    } else {
        cameraArea.style.display = 'none';
        dropArea.style.display   = 'block';
        document.getElementById('btnUpload').classList.add('active');
        document.getElementById('btnKamera').classList.remove('active');
        stopCamera();
        document.getElementById('fotoCameraBase64').value = '';
        document.getElementById('cameraResult').style.display   = 'none';
        document.getElementById('cameraPreview').style.display  = 'none';
        document.getElementById('btnStartCam').style.display    = 'inline-flex';
        document.getElementById('btnCapture').style.display     = 'none';
        document.getElementById('btnRetake').style.display      = 'none';
    }
}

async function startCamera(){
    const video  = document.getElementById('cameraPreview');
    const result = document.getElementById('cameraResult');

    try{
        stream = await navigator.mediaDevices.getUserMedia({
            video: { facingMode: 'environment' }
        });
        video.srcObject = stream;
        video.style.display  = 'block';
        result.style.display = 'none';
        document.getElementById('btnStartCam').style.display = 'none';
        document.getElementById('btnCapture').style.display  = 'inline-flex';
        document.getElementById('btnRetake').style.display   = 'none';
        document.getElementById('fotoCameraBase64').value    = '';
    } catch(err){
        alert('Tidak bisa mengakses kamera: ' + err.message + '\n\nPastikan browser mengizinkan akses kamera dan halaman dibuka via HTTPS atau localhost.');
    }
}

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

function captureCamera(){
    const video  = document.getElementById('cameraPreview');
    const canvas = document.getElementById('cameraCanvas');
    const result = document.getElementById('cameraResult');

    canvas.width  = video.videoWidth;
    canvas.height = video.videoHeight;
    canvas.getContext('2d').drawImage(video, 0, 0);

    const dataUrl = canvas.toDataURL('image/jpeg', 0.9);
    document.getElementById('fotoCameraBase64').value = dataUrl;

    result.src = dataUrl;
    result.style.display = 'block';
    video.style.display  = 'none';

    stopCamera();

    document.getElementById('btnCapture').style.display = 'none';
    document.getElementById('btnRetake').style.display  = 'inline-flex';
}

document.getElementById('checklistForm').addEventListener('submit', function(e){
    if(!wajibFoto) return;

    let activeMode = sumberFoto;
    if(sumberFoto == 'both'){
        activeMode = document.getElementById('btnKamera').classList.contains('active') ? 'kamera' : 'upload';
    }

    if(activeMode == 'kamera'){
        if(!document.getElementById('fotoCameraBase64').value){
            alert('Silakan ambil foto menggunakan kamera terlebih dahulu.');
            e.preventDefault();
        }
    } else {
        const fi = document.getElementById('fotoInputUpload');
        if(!fi.files || fi.files.length === 0){
            alert('Silakan upload foto terlebih dahulu.');
            e.preventDefault();
        }
    }
});

<?php if($sumber_foto == 'upload' || $sumber_foto == 'both'): ?>
const drop = document.getElementById('dropArea');
drop.addEventListener('dragover',  e => { e.preventDefault(); drop.style.borderColor = 'var(--green-400)'; drop.style.background = '#f0fdf4'; });
drop.addEventListener('dragleave', () => { drop.style.borderColor = ''; drop.style.background = ''; });
drop.addEventListener('drop', e => {
    e.preventDefault();
    drop.style.borderColor = '';
    drop.style.background  = '';
    const fi = document.getElementById('fotoInputUpload');
    fi.files = e.dataTransfer.files;
    showFileName(fi);
});
<?php endif; ?>

window.addEventListener('beforeunload', stopCamera);
</script>

</body>
</html>