<?php
declare(strict_types=1);
/* ====================================================
SAFETY TALK SYSTEM - PT CITRA LAMPIA MANDIRI
File        : formulir/edit_safety_talk.php
Versi       : 2.5.0
Revisi      : 002 - Fix form action path + CSV 10 kolom
Tanggal     : 20-02-2026
Fitur       : - ✅ Edit existing safety talk record
              - ✅ CSV Structure: 10 columns [0-9]
              - ✅ Field "peserta_seharusnya" (index 8)
              - ✅ CSRF Protection + Strict Types
              - ✅ XSS Prevention (htmlspecialchars)
              - ✅ Input Validation & Sanitization
              - ✅ Consistent UI with Dashboard
              - ✅ Accessibility & Loading States
              
📋 CSV Structure (10 columns):
  [0]tanggal, [1]hari, [2]departemen, [3]divisi, 
  [4]nama, [5]jabatan, [6]topik, [7]peserta, 
  [8]peserta_seharusnya, [9]foto
  
⚠️ SERVER-SIDE VALIDATION (update_proses.php MUST):
  1. Validasi CSRF token: hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])
  2. Validasi row_id: harus integer valid dan ada di CSV
  3. Validasi tanggal: format YYYY-MM-DD, tidak future date
  4. Validasi divisi: hanya HS/EF/QMS
  5. Validasi nama/jabatan/topik: sanitize & length check
  6. Validasi peserta & peserta_seharusnya: integer 1-999
  7. Validasi file upload: MIME type via finfo_file(), max size, sanitize filename
  8. Hapus foto lama dari folder uploads/ jika ada upload baru
  9. Update CSV dengan fputcsv() yang aman (10 kolom)
 10. Log aktivitas edit ke activity_log.csv
====================================================
*/

// ===== KONFIGURASI GLOBAL (Readonly Class - PHP 8.2+) =====
final readonly class AppConfig
{
    public function __construct(
        public string $appVersion = '2.5.0',
        public string $revision = '002',
        public string $timezone = 'Asia/Jakarta',
        public int $maxUploadFiles = 3,
        public int $maxFileSizeBytes = 3_145_728, // 3MB
        public array $allowedMimeTypes = ['image/jpeg', 'image/png', 'image/webp'],
        public array $allowedDivisi = ['HS', 'EF', 'QMS'],
        public int $sessionTimeout = 1800,
    ) {}
}

$config = new AppConfig();
date_default_timezone_set($config->timezone);

// ===== AUTH & SECURITY CHECK =====
if(session_status() === PHP_SESSION_NONE && !@session_start()) {
    error_log('[EDIT_FORM] Failed to start session');
    exit('❌ Gagal memulai sesi. Hubungi administrator.');
}

// Cek login
if(!isset($_SESSION['user_logged_in']) || $_SESSION['user_logged_in'] !== true) {
    header('Location: ../login.php');
    exit;
}

// Session timeout: 30 minutes inactivity
if(isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > $config->sessionTimeout)) {
    session_unset();
    session_destroy();
    header('Location: ../login.php?timeout=1');
    exit;
}
$_SESSION['last_activity'] = time();

// Generate CSRF token using modern randomizer (PHP 8.2+)
if(empty($_SESSION['csrf_token'])) {
    $randomizer = new \Random\Randomizer();
    $_SESSION['csrf_token'] = $randomizer->getBytesFromString('0123456789abcdef', 32);
}

// ===== GET & VALIDATE ID PARAMETER =====
$id = isset($_GET['id']) ? (int)$_GET['id'] : -1;
if($id < 0) {
    $_SESSION['error_msg'] = 'ID tidak valid!';
    header('Location: ../rekap.php');
    exit;
}

// ===== LOAD DATA FROM CSV (10 columns support) =====
$dataLama = [];
$csvPath = __DIR__ . '/../data/safety_talk.csv';

if($id >= 0 && file_exists($csvPath) && is_readable($csvPath)) {
    $file = fopen($csvPath, 'r');
    if($file !== FALSE) {
        $currentIndex = 0;
        while(($row = fgetcsv($file, 1000, ",")) !== FALSE) {
            // ✅ Validasi minimal 9 kolom (data lama) atau 10 kolom (data baru)
            if(!is_array($row) || count($row) < 9) { 
                $currentIndex++; 
                continue; 
            }
            
            if($currentIndex == $id) {
                $dataLama = $row;
                break;
            }
            $currentIndex++;
        }
        fclose($file);
    }
}

// ✅ Handle data not found via session (no JS alert)
if(!$dataLama || empty($dataLama[0])) {
    $_SESSION['error_msg'] = 'Data tidak ditemukan!';
    header('Location: ../rekap.php');
    exit;
}

// ===== PREPARE EXISTING PHOTOS =====
// Foto ada di index 9 untuk data baru, atau index 8 untuk data lama
$fotoIndex = count($dataLama) >= 10 ? 9 : 8;
$fotoLama = !empty($dataLama[$fotoIndex]) ? array_filter(explode("|", $dataLama[$fotoIndex])) : [];

// ===== PREPARE ATTENDANCE DATA =====
$peserta = (int)($dataLama[7] ?? 0);
// Backward compatible: jika kolom 8 belum ada, anggap sama dengan peserta
$peserta_seharusnya = isset($dataLama[8]) ? (int)$dataLama[8] : $peserta;
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Safety Talk | PT Citra Lampia Mandiri v<?= $config->appVersion ?></title>
    
    <!-- ✅ CDN URLs FIXED (no trailing spaces) -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400:500:600:700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <style>
        :root {
            /* ✅ Consistent with dashboard */
            --primary: #0f172a;
            --primary-dark: #1e3a8a;
            --accent: #2563eb;
            --success: #059669;
            --danger: #dc2626;
            --warning: #f59e0b;
            --gray-50: #f8fafc;
            --gray-100: #f1f5f9;
            --gray-200: #e2e8f0;
            --gray-300: #cbd5e1;
            --gray-500: #64748b;
            --gray-700: #334155;
            --gray-900: #0f172a;
            --shadow-sm: 0 1px 2px rgba(0,0,0,0.05);
            --shadow-md: 0 4px 6px -1px rgba(0,0,0,0.1);
            --shadow-lg: 0 10px 15px -3px rgba(0,0,0,0.1);
            --radius: 8px;
            --radius-lg: 12px;
            --transition: all 0.2s ease;
        }

        * { box-sizing: border-box; margin: 0; padding: 0; }
        
        body { 
            font-family: 'Inter', system-ui, -apple-system, sans-serif; 
            background: var(--gray-50); 
            color: var(--gray-900);
            line-height: 1.5;
            padding: 24px;
            min-height: 100vh;
        }

        .container { 
            background: white; 
            max-width: 850px; 
            margin: auto; 
            border-radius: var(--radius-lg); 
            box-shadow: var(--shadow-lg); 
            overflow: hidden;
            border: 1px solid var(--gray-200);
        }
        
        .header { 
            background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%); 
            color: white; 
            padding: 20px 24px; 
            text-align: center;
        }
        .header h3 {
            font-size: 16px;
            font-weight: 600;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }
        .header p {
            font-size: 11px;
            opacity: 0.9;
            margin-top: 4px;
        }
        .version-badge {
            display: inline-block;
            padding: 2px 8px;
            background: rgba(255,255,255,0.2);
            border-radius: 12px;
            font-size: 9px;
            font-weight: 600;
            margin-left: 8px;
        }
        
        form { padding: 24px; }
        
        .form-grid { 
            display: grid; 
            grid-template-columns: repeat(2, 1fr); 
            gap: 16px; 
        }
        .full-width { grid-column: span 2; }
        
        .form-group { margin-bottom: 4px; }
        
        .form-group label { 
            display: flex;
            align-items: center;
            gap: 6px;
            font-weight: 600; 
            margin-bottom: 6px; 
            font-size: 12px; 
            color: var(--gray-700); 
            text-transform: uppercase;
            letter-spacing: 0.3px;
        }
        .form-group label i { color: var(--accent); font-size: 10px; }
        .form-group label .required { color: var(--danger); margin-left: auto; }
        .form-group label .hint { color: var(--gray-500); font-weight: 400; margin-left: auto; font-size: 10px; }
        
        .form-control { 
            width: 100%; 
            padding: 11px 14px; 
            border: 1px solid var(--gray-300); 
            border-radius: var(--radius); 
            font-size: 14px; 
            transition: var(--transition); 
            background: var(--gray-50);
        }
        .form-control:focus { 
            outline: none; 
            border-color: var(--accent); 
            background: white;
            box-shadow: 0 0 0 3px rgba(37,99,235,0.1); 
        }
        .form-control:disabled {
            background: var(--gray-100);
            color: var(--gray-500);
            cursor: not-allowed;
        }
        .form-control::placeholder { color: var(--gray-400); }
        
        select.form-control {
            appearance: none;
            background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3c/svg%3e");
            background-position: right 12px center;
            background-repeat: no-repeat;
            background-size: 16px;
            padding-right: 36px;
        }
        
        .info-hari { 
            font-size: 11px; 
            color: var(--success); 
            font-weight: 600; 
            margin-top: 4px; 
            display: block;
        }
        .file-hint { 
            font-size: 10px; 
            color: var(--gray-500); 
            margin-top: 4px; 
            display: block;
        }
        
        /* File Upload Area */
        .upload-area {
            border: 2px dashed var(--gray-300);
            border-radius: var(--radius);
            padding: 16px;
            text-align: center;
            background: var(--gray-50);
            transition: var(--transition);
            cursor: pointer;
        }
        .upload-area:hover, .upload-area.dragover {
            border-color: var(--accent);
            background: rgba(37, 99, 235, 0.03);
        }
        .upload-area i {
            font-size: 24px;
            color: var(--gray-400);
            margin-bottom: 6px;
        }
        .upload-area p {
            font-size: 12px;
            color: var(--gray-600);
            margin-bottom: 2px;
        }
        .upload-area small {
            font-size: 9px;
            color: var(--gray-500);
        }
        .upload-area input[type="file"] {
            position: absolute;
            width: 1px;
            height: 1px;
            padding: 0;
            margin: -1px;
            overflow: hidden;
            clip: rect(0,0,0,0);
            white-space: nowrap;
            border: 0;
        }
        
        /* Existing Photos Grid */
        .existing-photos {
            margin-top: 16px;
            padding-top: 16px;
            border-top: 1px solid var(--gray-200);
        }
        .existing-photos-title {
            font-size: 11px;
            font-weight: 600;
            color: var(--gray-700);
            text-transform: uppercase;
            letter-spacing: 0.3px;
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            gap: 6px;
        }
        .photo-grid {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        .photo-item {
            position: relative;
            width: 70px;
            height: 70px;
            border-radius: var(--radius);
            overflow: hidden;
            border: 2px solid var(--gray-200);
            background: var(--gray-100);
        }
        .photo-item img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: var(--transition);
        }
        .photo-item:hover img {
            transform: scale(1.05);
        }
        .photo-item .remove-btn {
            position: absolute;
            top: -6px;
            right: -6px;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background: var(--danger);
            color: white;
            border: 2px solid white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 10px;
            cursor: pointer;
            transition: var(--transition);
        }
        .photo-item .remove-btn:hover {
            background: #b91c1c;
            transform: scale(1.1);
        }
        .photo-placeholder {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100%;
            color: var(--gray-400);
            font-size: 20px;
        }
        
        /* Preview New Uploads */
        .preview-grid {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            margin-top: 12px;
        }
        .preview-item {
            position: relative;
            width: 70px;
            height: 70px;
            border-radius: var(--radius);
            overflow: hidden;
            border: 2px solid var(--success);
            animation: fadeIn 0.3s ease;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: scale(0.9); }
            to { opacity: 1; transform: scale(1); }
        }
        .preview-item img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        .preview-item .preview-badge {
            position: absolute;
            top: 4px;
            right: 4px;
            background: var(--success);
            color: white;
            font-size: 9px;
            padding: 2px 6px;
            border-radius: 10px;
            font-weight: 600;
        }
        
        /* Alert Messages */
        .alert {
            padding: 12px 16px;
            border-radius: var(--radius);
            font-size: 13px;
            margin-bottom: 16px;
            display: flex;
            align-items: flex-start;
            gap: 10px;
            animation: slideDown 0.3s ease;
        }
        @keyframes slideDown {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .alert-error {
            background: #fef2f2;
            border: 1px solid #fecaca;
            color: #b91c1c;
        }
        .alert-success {
            background: #ecfdf5;
            border: 1px solid #6ee7b7;
            color: #065f46;
        }
        .alert-warning {
            background: #fef3c7;
            border: 1px solid #f59e0b;
            color: #92400e;
        }
        .alert i { margin-top: 2px; }
        
        /* Button Group */
        .btn-group { 
            display: flex; 
            gap: 12px; 
            margin-top: 24px; 
            padding-top: 20px;
            border-top: 1px solid var(--gray-200);
        }
        .btn { 
            flex: 1; 
            padding: 12px 16px; 
            border: none; 
            border-radius: var(--radius); 
            font-weight: 600; 
            font-size: 13px;
            cursor: pointer; 
            display: flex; 
            align-items: center; 
            justify-content: center; 
            gap: 8px; 
            transition: var(--transition);
            text-decoration: none;
        }
        .btn i { font-size: 12px; }
        
        .btn-primary { 
            background: var(--primary); 
            color: white; 
        }
        .btn-primary:hover { 
            background: var(--primary-dark); 
            transform: translateY(-1px);
            box-shadow: var(--shadow-md);
        }
        .btn-primary:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none !important;
        }
        
        .btn-secondary { 
            background: white; 
            color: var(--gray-700); 
            border: 1px solid var(--gray-300);
        }
        .btn-secondary:hover { 
            background: var(--gray-100);
        }
        
        .btn .spinner {
            display: none;
            width: 16px;
            height: 16px;
            border: 2px solid rgba(255,255,255,0.3);
            border-top-color: white;
            border-radius: 50%;
            animation: spin 0.8s linear infinite;
        }
        .btn.loading .btn-text { display: none; }
        .btn.loading .spinner { display: inline-block; }
        @keyframes spin { to { transform: rotate(360deg); } }
        
        .back-link {
            display: block;
            text-align: center;
            margin-top: 16px;
            font-size: 12px;
            color: var(--gray-500);
            text-decoration: none;
            transition: var(--transition);
        }
        .back-link:hover { color: var(--accent); }
        
        /* Responsive */
        @media (max-width: 640px) { 
            .form-grid { grid-template-columns: 1fr; } 
            .full-width { grid-column: span 1; }
            .btn-group { flex-direction: column; }
            .btn { width: 100%; }
        }
        
        /* Print Hide */
        @media print {
            .no-print { display: none !important; }
            body { background: white; padding: 0; }
        }
        
        /* Utilities */
        .sr-only {
            position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
            overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0;
        }
        .text-muted { color: var(--gray-500); font-size: 11px; }
    </style>
</head>
<body>

<div class="container">
    <div class="header">
        <h3><i class="fas fa-pen-to-square"></i> EDIT SAFETY TALK</h3>
        <p>PT Citra Lampia Mandiri • QHSEF Department 
            <span class="version-badge">v<?= $config->appVersion ?> Rev.<?= $config->revision ?></span>
        </p>
    </div>

    <!-- ✅ FIX: Form action path - simple relative path -->
    <form id="editForm" action="update_proses.php" method="POST" enctype="multipart/form-data" autocomplete="off">
        <!-- ✅ CSRF Token -->
        <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
        <input type="hidden" name="row_id" value="<?= (int)$id ?>">
        <!-- Foto lama: handle both old (index 8) and new (index 9) structure -->
        <input type="hidden" name="foto_lama" value="<?= htmlspecialchars($dataLama[$fotoIndex] ?? '') ?>">
        <input type="hidden" name="foto_dihapus" id="fotoDihapus" value="">
        
        <!-- Alert Messages Container (untuk error dari session) -->
        <div id="alertContainer">
            <?php if(isset($_SESSION['error_msg'])): ?>
            <div class="alert alert-error" role="alert">
                <i class="fas fa-circle-exclamation"></i>
                <span><?= htmlspecialchars($_SESSION['error_msg']) ?></span>
            </div>
            <?php unset($_SESSION['error_msg']); endif; ?>
        </div>

        <!-- Warning Alert -->
        <div class="alert alert-warning">
            <i class="fas fa-triangle-exclamation"></i>
            <div>
                <strong>Perhatian:</strong> Mengunggah foto baru akan <em>mengganti</em> foto lama. 
                Kosongkan upload jika hanya ingin mengedit teks.
            </div>
        </div>

        <div class="form-grid">
            <!-- Tanggal -->
            <div class="form-group">
                <label for="tanggal">
                    <i class="far fa-calendar"></i> Tanggal <span class="required">*</span>
                </label>
                <input type="date" id="tanggal" name="tanggal" class="form-control" 
                       value="<?= htmlspecialchars($dataLama[0] ?? '') ?>" 
                       max="<?= date('Y-m-d') ?>" required>
                <span id="displayHari" class="info-hari" role="status" aria-live="polite"></span>
                <input type="hidden" name="hari" id="hariHidden" value="<?= htmlspecialchars($dataLama[1] ?? '') ?>">
            </div>

            <!-- Divisi -->
            <div class="form-group">
                <label for="divisi">
                    <i class="fas fa-sitemap"></i> Divisi <span class="required">*</span>
                </label>
                <select id="divisi" name="divisi" class="form-control" required>
                    <option value="">-- Pilih Divisi --</option>
                    <option value="HS" <?= ($dataLama[3] ?? '') === 'HS' ? 'selected' : '' ?>>HS (Health & Safety)</option>
                    <option value="EF" <?= ($dataLama[3] ?? '') === 'EF' ? 'selected' : '' ?>>EF (Environment & Forestry)</option>
                    <option value="QMS" <?= ($dataLama[3] ?? '') === 'QMS' ? 'selected' : '' ?>>QMS (Quality Management)</option>
                </select>
            </div>

            <!-- Nama PIC -->
            <div class="form-group">
                <label for="nama">
                    <i class="fas fa-user"></i> Nama PIC <span class="required">*</span>
                </label>
                <input type="text" id="nama" name="nama" class="form-control" 
                       value="<?= htmlspecialchars($dataLama[4] ?? '') ?>" 
                       placeholder="Nama lengkap penanggung jawab" required
                       pattern="[A-Za-z\s\.\'\-]{3,50}">
            </div>

            <!-- Jabatan -->
            <div class="form-group">
                <label for="jabatan">
                    <i class="fas fa-id-badge"></i> Jabatan <span class="required">*</span>
                </label>
                <input type="text" id="jabatan" name="jabatan" class="form-control" 
                       value="<?= htmlspecialchars($dataLama[5] ?? '') ?>" 
                       placeholder="Jabatan / Posisi" required
                       pattern="[A-Za-z\s\.\,\-\/]{2,50}">
            </div>

            <!-- Jumlah Peserta Hadir -->
            <div class="form-group">
                <label for="peserta">
                    <i class="fas fa-users"></i> Peserta Hadir <span class="required">*</span>
                    <span class="hint">Orang</span>
                </label>
                <input type="number" id="peserta" name="peserta" class="form-control" 
                       value="<?= $peserta ?>" min="1" max="999" placeholder="1-999" required>
            </div>

            <!-- ✅ NEW: Peserta Seharusnya (untuk metrik kehadiran) -->
            <div class="form-group">
                <label for="peserta_seharusnya">
                    <i class="fas fa-user-check"></i> Peserta Seharusnya <span class="hint">Opsional</span>
                </label>
                <input type="number" id="peserta_seharusnya" name="peserta_seharusnya" class="form-control" 
                       value="<?= $peserta_seharusnya ?>" min="1" max="999" placeholder="Target undangan">
                <small class="file-hint">Kosongkan jika sama dengan peserta hadir</small>
            </div>

            <!-- Hari (Auto, readonly) -->
            <div class="form-group">
                <label for="hariDisplay">
                    <i class="far fa-clock"></i> Hari
                </label>
                <input type="text" id="hariDisplay" class="form-control" disabled
                       value="<?= !empty($dataLama[0]) ? date('l', strtotime($dataLama[0])) : '-' ?>">
                <small class="text-muted">Otomatis dari tanggal</small>
            </div>

            <!-- Topik Materi (Full Width) -->
            <div class="form-group full-width">
                <label for="topik">
                    <i class="fas fa-bullhorn"></i> Topik / Materi <span class="required">*</span>
                </label>
                <input type="text" id="topik" name="topik" class="form-control" 
                       value="<?= htmlspecialchars($dataLama[6] ?? '') ?>" 
                       placeholder="Contoh: Penggunaan APD Lengkap di Area Produksi" required
                       minlength="10" maxlength="200">
            </div>

            <!-- Foto Bukti (Edit Mode) -->
            <div class="form-group full-width">
                <label>
                    <i class="fas fa-camera"></i> Dokumentasi Foto
                </label>
                
                <!-- Custom Upload Area -->
                <label class="upload-area" for="bukti" id="uploadArea">
                    <input type="file" id="bukti" name="bukti[]" 
                           accept="image/jpeg,image/png,image/webp" 
                           multiple
                           aria-describedby="fileHint">
                    <i class="fas fa-cloud-upload-alt"></i>
                    <p><strong>Klik atau drag file</strong> untuk ganti foto</p>
                    <small id="fileHint">Maks. <?= $config->maxUploadFiles ?> foto, @<?= $config->maxFileSizeBytes / 1024 / 1024 ?>MB</small>
                </label>

                <!-- Preview New Uploads -->
                <div class="preview-grid" id="previewNew"></div>

                <!-- Existing Photos -->
                <?php if(!empty($fotoLama)): ?>
                <div class="existing-photos">
                    <div class="existing-photos-title">
                        <i class="fas fa-photo-film"></i> Foto Saat Ini (<?= count($fotoLama) ?>)
                    </div>
                    <div class="photo-grid">
                        <?php foreach($fotoLama as $foto): ?>
                        <div class="photo-item">
                            <img src="../uploads/<?= htmlspecialchars(basename($foto)) ?>" 
                                 alt="Foto Safety Talk" 
                                 loading="lazy"
                                 onerror="this.parentElement.innerHTML='<div class=\\'photo-placeholder\\'><i class=\\'fas fa-image-slash\\'></i></div>'">
                            <button type="button" class="remove-btn" 
                                    onclick="markForRemoval('<?= htmlspecialchars($foto) ?>')"
                                    title="Tandai untuk dihapus"
                                    aria-label="Hapus foto <?= htmlspecialchars($foto) ?>">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Button Group -->
        <div class="btn-group no-print">
            <!-- ✅ FIX: Back link path - naik satu level ke root -->
            <a href="../rekap.php" class="btn btn-secondary">
                <i class="fas fa-xmark"></i> <span class="btn-text">Batal</span>
            </a>
            <button type="submit" class="btn btn-primary" id="btnSubmit">
                <span class="btn-text"><i class="fas fa-check-circle"></i> Simpan Perubahan</span>
                <span class="spinner"></span>
            </button>
        </div>
        
        <!-- ✅ FIX: Back link path - naik satu level ke root -->
        <a href="../rekap.php" class="back-link">
            <i class="fas fa-list-alt"></i> Kembali ke Rekap Data
        </a>
    </form>
</div>

<!-- ✅ INCLUDE FOOTER -->
<?php include __DIR__ . '/../footer.php'; ?>

<script>
// ===== CONFIG FROM PHP =====
const CONFIG = {
    maxFiles: <?= $config->maxUploadFiles ?>,
    maxFileSize: <?= $config->maxFileSizeBytes ?>,
    allowedTypes: <?= json_encode($config->allowedMimeTypes) ?>
};

// ===== AUTO-UPDATE HARI BASED ON TANGGAL =====
document.getElementById('tanggal').addEventListener('change', function() {
    const dateValue = this.value;
    const displayHari = document.getElementById('displayHari');
    const hariHidden = document.getElementById('hariHidden');
    const hariDisplay = document.getElementById('hariDisplay');
    
    if(dateValue) {
        // ✅ Validate: no future dates
        const today = new Date();
        today.setHours(0,0,0,0);
        const selected = new Date(dateValue);
        
        if(selected > today) {
            showAlert('⚠️ Tanggal tidak boleh melebihi hari ini!', 'error');
            this.value = '';
            displayHari.innerText = '';
            hariHidden.value = '';
            hariDisplay.value = '-';
            return;
        }
        
        const days = ['Minggu','Senin','Selasa','Rabu','Kamis','Jumat','Sabtu'];
        const namaHari = days[selected.getDay()];
        displayHari.innerText = 'Hari: ' + namaHari;
        hariHidden.value = namaHari;
        hariDisplay.value = namaHari;
    } else {
        displayHari.innerText = '';
        hariHidden.value = '';
        hariDisplay.value = '-';
    }
});

// ===== SHOW ALERT MESSAGE =====
function showAlert(message, type = 'error') {
    const container = document.getElementById('alertContainer');
    const icons = { error: 'circle-exclamation', success: 'circle-check', info: 'circle-info', warning: 'triangle-exclamation' };
    
    container.innerHTML = `
        <div class="alert alert-${type}" role="alert">
            <i class="fas fa-${icons[type] || 'circle-info'}"></i>
            <span>${message}</span>
        </div>
    `;
    
    if(type === 'success') {
        setTimeout(() => { container.innerHTML = ''; }, 3000);
    }
    container.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}

// ===== FILE UPLOAD PREVIEW & VALIDATION =====
const fileInput = document.getElementById('bukti');
const previewNew = document.getElementById('previewNew');
const uploadArea = document.getElementById('uploadArea');

fileInput.addEventListener('change', handleFileSelect);
uploadArea.addEventListener('dragover', (e) => { e.preventDefault(); uploadArea.classList.add('dragover'); });
uploadArea.addEventListener('dragleave', () => uploadArea.classList.remove('dragover'));
uploadArea.addEventListener('drop', (e) => {
    e.preventDefault();
    uploadArea.classList.remove('dragover');
    if(e.dataTransfer.files.length) {
        fileInput.files = e.dataTransfer.files;
        handleFileSelect({ target: fileInput });
    }
});

function handleFileSelect(e) {
    const files = Array.from(e.target.files);
    previewNew.innerHTML = '';
    
    if(files.length > CONFIG.maxFiles) {
        showAlert(`❌ Maksimal ${CONFIG.maxFiles} foto!`, 'error');
        fileInput.value = '';
        return;
    }
    
    files.forEach((file, index) => {
        if(file.size > CONFIG.maxFileSize) {
            showAlert(`❌ File "${file.name}" melebihi ${CONFIG.maxFileSize / 1024 / 1024}MB!`, 'error');
            fileInput.value = '';
            previewNew.innerHTML = '';
            return;
        }
        
        if(!CONFIG.allowedTypes.includes(file.type)) {
            showAlert(`❌ Format "${file.name}" tidak didukung!`, 'error');
            fileInput.value = '';
            previewNew.innerHTML = '';
            return;
        }
        
        const reader = new FileReader();
        reader.onload = function(evt) {
            try {
                const item = document.createElement('div');
                item.className = 'preview-item';
                item.innerHTML = `
                    <img src="${evt.target.result}" alt="Preview ${index + 1}" onerror="this.parentElement.remove()">
                    <span class="preview-badge">Baru</span>
                `;
                previewNew.appendChild(item);
            } catch(err) {
                console.error('Preview error:', err);
                showAlert('⚠️ Gagal memuat preview foto', 'error');
            }
        };
        reader.onerror = function() {
            showAlert(`❌ Gagal membaca file: ${file.name}`, 'error');
        };
        reader.readAsDataURL(file);
    });
}

// ===== MARK PHOTO FOR REMOVAL =====
function markForRemoval(filename) {
    const input = document.getElementById('fotoDihapus');
    const current = input.value ? input.value.split(',') : [];
    if(!current.includes(filename)) {
        current.push(filename);
        input.value = current.join(',');
    }
    // Visual feedback
    const btn = event.target.closest('button');
    if(btn) {
        btn.closest('.photo-item').style.opacity = '0.5';
        btn.closest('.photo-item').style.pointerEvents = 'none';
        btn.title = 'Akan dihapus';
    }
}

// ===== FORM SUBMISSION WITH LOADING STATE =====
document.getElementById('editForm').addEventListener('submit', function(e) {
    const btnSubmit = document.getElementById('btnSubmit');
    const hariHidden = document.getElementById('hariHidden').value;
    
    document.getElementById('alertContainer').innerHTML = '';
    
    if(!hariHidden) {
        e.preventDefault();
        showAlert('⚠️ Hari gagal terdeteksi! Silakan pilih tanggal lagi.', 'error');
        return;
    }
    
    // Auto-fill peserta_seharusnya jika kosong (backward compatible)
    const pesertaSeharusnya = document.getElementById('peserta_seharusnya');
    if(pesertaSeharusnya && !pesertaSeharusnya.value) {
        const peserta = document.getElementById('peserta').value;
        if(peserta) pesertaSeharusnya.value = peserta;
    }
    
    // Show loading state
    btnSubmit.classList.add('loading');
    btnSubmit.disabled = true;
});

// ===== RESET VISUAL FEEDBACK =====
document.querySelector('.btn-secondary')?.addEventListener('click', function() {
    previewNew.innerHTML = '';
    document.getElementById('alertContainer').innerHTML = '';
});

// ===== KEYBOARD SHORTCUTS =====
document.addEventListener('keydown', function(e) {
    if((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
        e.preventDefault();
        document.getElementById('editForm').requestSubmit();
    }
    if(e.key === 'Escape' && document.activeElement.tagName !== 'INPUT') {
        window.location.href = '../rekap.php';
    }
});

// ===== INITIALIZATION =====
document.addEventListener('DOMContentLoaded', function() {
    // Initialize hari display from existing value
    const tanggalInput = document.getElementById('tanggal');
    if(tanggalInput.value) {
        const days = ['Minggu','Senin','Selasa','Rabu','Kamis','Jumat','Sabtu'];
        const d = new Date(tanggalInput.value);
        const namaHari = days[d.getDay()];
        document.getElementById('displayHari').innerText = 'Hari: ' + namaHari;
        document.getElementById('hariDisplay').value = namaHari;
    }
    
    // Initialize upload area click
    uploadArea.addEventListener('click', function(e) {
        if(e.target === this || e.target.closest('small') || e.target.closest('p')) {
            fileInput.click();
        }
    });
    
    // Auto-fill peserta_seharusnya = peserta on input change (UX enhancement)
    const pesertaInput = document.getElementById('peserta');
    const pesertaSeharusnyaInput = document.getElementById('peserta_seharusnya');
    if(pesertaInput && pesertaSeharusnyaInput) {
        pesertaInput.addEventListener('change', function() {
            if(pesertaSeharusnyaInput && !pesertaSeharusnyaInput.value) {
                pesertaSeharusnyaInput.value = this.value;
            }
        });
    }
});
</script>

</body>
</html>