<?php
declare(strict_types=1);
/* ====================================================
SAFETY TALK SYSTEM - PT CITRA LAMPIA MANDIRI
File        : formulir/input_safety_talk.php
Versi       : 2.5.0
Revisi      : 002 - Fix form action path + CSV 10 kolom
Tanggal     : 20-02-2026
Fitur       : - ✅ Multiple Photo Upload (max 3 files)
              - ✅ Field "Peserta Seharusnya" (index 8 CSV)
              - ✅ CSV Structure: 10 columns [0-9]
              - ✅ CSRF Protection + Strict Types
              - ✅ Server-side Validation Hints
              - ✅ File Sanitization Guidelines
              - ✅ 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 (simpan.php MUST):
  1. Validasi CSRF token: hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])
  2. Validasi semua input fields dengan pattern + length + range
  3. Validasi file upload: MIME type via finfo_file(), max size, sanitize filename
  4. Simpan 10 kolom ke CSV dengan fputcsv() yang aman
  5. Generate unique filename: 'ST_' . date('Ymd_His') . '_' . bin2hex(random_bytes(8)) . '.' . $ext
====================================================
*/

// ===== 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'],
    ) {}
}

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

// ===== AUTH & SECURITY CHECK =====
if(session_status() === PHP_SESSION_NONE && !@session_start()) {
    error_log('[INPUT_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'] > 1800)) {
    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);
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Input Safety Talk | QHSEF System - PT CLM 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;
        }
        
        /* Preview Grid */
        .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;
        }
        .preview-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;
        }
        
        /* 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-info {
            background: #f0f9ff;
            border: 1px solid #7dd3fc;
            color: #075985;
        }
        .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-hard-hat"></i> INPUT SAFETY TALK</h3>
        <p>QHSEF Department • PT Citra Lampia Mandiri 
            <span class="version-badge">v<?= $config->appVersion ?> Rev.<?= $config->revision ?></span>
        </p>
    </div>

    <!-- ✅ FIX: Form action path - simple relative path -->
    <form id="formSafety" action="simpan.php" method="POST" enctype="multipart/form-data" autocomplete="off">
        <!-- ✅ CSRF Token -->
        <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
        
        <!-- Alert Messages Container -->
        <div id="alertContainer"></div>

        <div class="form-grid">
            <!-- Tanggal -->
            <div class="form-group">
                <label for="tanggalInput">
                    <i class="far fa-calendar-alt"></i> Tanggal <span class="required">*</span>
                </label>
                <input type="date" id="tanggalInput" name="tanggal" class="form-control" 
                       max="<?= date('Y-m-d') ?>" required 
                       aria-describedby="displayHari">
                <span id="displayHari" class="info-hari" role="status" aria-live="polite"></span>
                <input type="hidden" name="hari" id="hariHidden">
            </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">HS (Health & Safety)</option>
                    <option value="EF">EF (Environment & Forestry)</option>
                    <option value="QMS">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" 
                       placeholder="Nama lengkap penanggung jawab" required
                       pattern="[A-Za-z\s\.\'\-]{3,50}" title="Minimal 3 karakter, huruf/spasi/titik/apostrof/tanda hubung">
            </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" 
                       placeholder="Jabatan / Posisi" required
                       pattern="[A-Za-z\s\.\,\-\/]{2,50}" title="Minimal 2 karakter">
            </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" 
                       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" 
                       min="1" max="999" placeholder="Target undangan"
                       title="Jumlah peserta yang diundang/dijadwalkan">
                <small class="file-hint">Kosongkan jika sama dengan peserta hadir</small>
            </div>

            <!-- Foto Bukti (Custom Upload) -->
            <div class="form-group full-width">
                <label>
                    <i class="fas fa-camera"></i> Foto Bukti <span class="required">*</span>
                </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 required
                           aria-describedby="fileHint">
                    <i class="fas fa-cloud-upload-alt"></i>
                    <p><strong>Klik atau drag file</strong> untuk upload</p>
                    <small id="fileHint">Maks. <?= $config->maxUploadFiles ?> foto, @<?= $config->maxFileSizeBytes / 1024 / 1024 ?>MB (JPG/PNG/WebP)</small>
                </label>

                <!-- Preview Grid -->
                <div class="preview-grid" id="previewGrid" role="list" aria-label="Preview foto"></div>
            </div>

            <!-- Topik Materi -->
            <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" 
                       placeholder="Contoh: Penggunaan APD Lengkap di Area Produksi" required
                       minlength="10" maxlength="200"
                       title="Minimal 10 karakter, maksimal 200 karakter">
            </div>

            <!-- Hidden Fields -->
            <input type="hidden" name="departemen" value="QHSEF">
            <input type="hidden" name="max_file_size" value="<?= $config->maxFileSizeBytes ?>">
            <input type="hidden" name="max_files" value="<?= $config->maxUploadFiles ?>">
        </div>

        <!-- Button Group -->
        <div class="btn-group no-print">
            <button type="reset" class="btn btn-secondary" id="btnReset">
                <i class="fas fa-undo"></i> <span class="btn-text">Reset</span>
            </button>
            <button type="submit" class="btn btn-primary" id="btnSubmit">
                <span class="btn-text"><i class="fas fa-save"></i> Simpan Data</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> Lihat 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('tanggalInput').addEventListener('change', function() {
    const dateValue = this.value;
    const displayHari = document.getElementById('displayHari');
    const hariHidden = document.getElementById('hariHidden');
    
    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 = '';
            return;
        }
        
        const days = ['Minggu','Senin','Selasa','Rabu','Kamis','Jumat','Sabtu'];
        const namaHari = days[selected.getDay()];
        displayHari.innerText = 'Hari: ' + namaHari;
        hariHidden.value = namaHari;
    } else {
        displayHari.innerText = '';
        hariHidden.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' };
    
    container.innerHTML = `
        <div class="alert alert-${type}" role="alert">
            <i class="fas fa-${icons[type] || 'circle-info'}"></i>
            <span>${message}</span>
        </div>
    `;
    
    // Auto-hide success messages after 3 seconds
    if(type === 'success') {
        setTimeout(() => {
            container.innerHTML = '';
        }, 3000);
    }
    
    // Scroll to alert
    container.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}

// ===== FILE UPLOAD PREVIEW & VALIDATION =====
const fileInput = document.getElementById('bukti');
const previewGrid = document.getElementById('previewGrid');
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);
    previewGrid.innerHTML = '';
    
    // Validate count
    if(files.length > CONFIG.maxFiles) {
        showAlert(`❌ Maksimal ${CONFIG.maxFiles} foto!`, 'error');
        fileInput.value = '';
        return;
    }
    
    files.forEach((file, index) => {
        // Validate size
        if(file.size > CONFIG.maxFileSize) {
            showAlert(`❌ File "${file.name}" melebihi ${CONFIG.maxFileSize / 1024 / 1024}MB!`, 'error');
            fileInput.value = '';
            previewGrid.innerHTML = '';
            return;
        }
        
        // Validate type
        if(!CONFIG.allowedTypes.includes(file.type)) {
            showAlert(`❌ Format "${file.name}" tidak didukung!`, 'error');
            fileInput.value = '';
            previewGrid.innerHTML = '';
            return;
        }
        
        // Preview dengan error handler
        const reader = new FileReader();
        reader.onload = function(evt) {
            try {
                const item = document.createElement('div');
                item.className = 'preview-item';
                item.setAttribute('role', 'listitem');
                item.innerHTML = `
                    <img src="${evt.target.result}" alt="Preview ${index + 1}" onerror="this.parentElement.remove()">
                    <span class="preview-badge">Baru</span>
                    <button type="button" class="remove-btn" onclick="removeFile(${index})" 
                            aria-label="Hapus foto ${index + 1}" title="Hapus">
                        <i class="fas fa-times"></i>
                    </button>
                `;
                previewGrid.appendChild(item);
            } catch(err) {
                console.error('Preview error:', err);
                showAlert('⚠️ Gagal memuat preview foto', 'error');
            }
        };
        // ✅ Tambah error handler untuk FileReader
        reader.onerror = function() {
            showAlert(`❌ Gagal membaca file: ${file.name}`, 'error');
        };
        reader.readAsDataURL(file);
    });
}

// ✅ Remove file dengan fallback untuk browser lama
function removeFile(index) {
    try {
        const files = Array.from(fileInput.files);
        if(index >= files.length) return;
        
        files.splice(index, 1);
        
        // Fallback untuk browser yang tidak support DataTransfer
        if(typeof DataTransfer === 'function') {
            const dataTransfer = new DataTransfer();
            files.forEach(file => dataTransfer.items.add(file));
            fileInput.files = dataTransfer.files;
        } else {
            // Fallback: reset input dan minta user pilih ulang
            showAlert('ℹ️ Browser tidak mendukung hapus file individual. Silakan pilih ulang file.', 'info');
            fileInput.value = '';
            previewGrid.innerHTML = '';
            return;
        }
        
        // Re-render preview
        handleFileSelect({ target: fileInput });
    } catch(err) {
        console.error('Remove file error:', err);
        showAlert('⚠️ Gagal menghapus file dari preview', 'error');
    }
}

// ===== FORM SUBMISSION WITH LOADING STATE =====
document.getElementById('formSafety').addEventListener('submit', function(e) {
    const btnSubmit = document.getElementById('btnSubmit');
    const hariHidden = document.getElementById('hariHidden').value;
    const files = fileInput.files;
    
    // Clear previous alerts
    document.getElementById('alertContainer').innerHTML = '';
    
    // Validate hari
    if(!hariHidden) {
        e.preventDefault();
        showAlert('⚠️ Hari gagal terdeteksi! Silakan pilih tanggal lagi.', 'error');
        return;
    }
    
    // Validate files (double-check)
    if(files.length === 0 || files.length > CONFIG.maxFiles) {
        e.preventDefault();
        showAlert(`⚠️ Silakan upload 1-${CONFIG.maxFiles} foto bukti.`, '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 HANDLER =====
document.getElementById('btnReset').addEventListener('click', function() {
    previewGrid.innerHTML = '';
    document.getElementById('alertContainer').innerHTML = '';
    document.getElementById('displayHari').innerText = '';
    document.getElementById('hariHidden').value = '';
    
    // Focus first field after reset
    setTimeout(() => document.getElementById('tanggalInput')?.focus(), 100);
});

// ===== KEYBOARD SHORTCUTS =====
document.addEventListener('keydown', function(e) {
    // Ctrl+Enter to submit
    if((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
        e.preventDefault();
        document.getElementById('formSafety').requestSubmit();
    }
    // Escape to reset
    if(e.key === 'Escape' && document.activeElement.tagName !== 'INPUT') {
        document.getElementById('btnReset')?.click();
    }
});

// ===== INITIALIZATION =====
document.addEventListener('DOMContentLoaded', function() {
    // Focus first field on load
    document.getElementById('tanggalInput')?.focus();
    
    // 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>