<?php
declare(strict_types=1);
/* ====================================================
SAFETY TALK SYSTEM - PT CITRA LAMPIA MANDIRI
File        : admin_panel.php
Versi       : 2.1 (Fixed CSV Reading + PHP 8.2+)
Fitur       : - ✅ Auto-detect CSV dengan/tanpa header
              - ✅ Strict Types & Modern PHP Syntax
              - ✅ Match Expressions for Clean Logic
              - ✅ Arrow Functions & Nullsafe Operator
              - ✅ Union Types & Readonly Config
              - ✅ Modern Randomizer for Security
              - ✅ Role-Based Access + Activity Logging
====================================================
*/

// ===== KONFIGURASI GLOBAL (Readonly Class) =====
final readonly class AppConfig
{
    public function __construct(
        public string $appVersion = '2.4.2',
        public string $timezone = 'Asia/Jakarta',
        public int $sessionTimeout = 1800,      // 30 menit
        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 string $uploadsDir = 'uploads',
        public string $dataDir = 'data',
        public string $usersDir = 'users',
        public string $backupsDir = 'backups',
    ) {}
    
    public function getPath(string $subdir): string
    {
        return __DIR__ . '/' . $subdir . '/';
    }
}

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

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

// Redirect if not logged in or not admin
if (!isset($_SESSION['user_logged_in']) || $_SESSION['user_logged_in'] !== true || ($_SESSION['user_role'] ?? '') !== 'admin') {
    header('Location: login.php?access_denied=1');
    exit;
}

// Session timeout check
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);
}

// ===== HELPER FUNCTIONS (PHP 8.2+ Syntax) =====

/**
 * Read CSV file with auto-detect header
 * @return list<array<string, string>>
 */
function readCSV(string $filepath, array $defaultHeader = []): array
{
    if (!file_exists($filepath) || !is_readable($filepath)) {
        error_log("[ADMIN_PANEL] File not found or not readable: $filepath");
        return [];
    }
    
    $file = @fopen($filepath, 'r');
    if ($file === false) {
        error_log("[ADMIN_PANEL] Failed to open CSV: $filepath");
        return [];
    }
    
    // Read first line
    $firstLine = @fgetcsv($file);
    if ($firstLine === false || empty($firstLine)) {
        fclose($file);
        error_log("[ADMIN_PANEL] Empty CSV file: $filepath");
        return [];
    }
    
    // Detect if first line is header or data
    // For safety_talk.csv: if first column looks like date (YYYY-MM-DD), it's data
    $isDataAsFirstLine = false;
    if (!empty($defaultHeader) && isset($firstLine[0])) {
        // Check if it matches date pattern
        if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $firstLine[0])) {
            $isDataAsFirstLine = true;
        }
        // Or check if it matches known header values
        elseif (in_array(strtolower($firstLine[0]), array_map('strtolower', $defaultHeader))) {
            $isDataAsFirstLine = false;
        }
    }
    
    $header = $isDataAsFirstLine ? $defaultHeader : $firstLine;
    
    // If first line was data, we need to process it
    $data = [];
    if ($isDataAsFirstLine && !empty($defaultHeader)) {
        if (count($firstLine) === count($header)) {
            $combined = array_combine($header, $firstLine);
            if ($combined !== false) {
                $data[] = $combined;
            }
        }
    }
    
    // Read remaining lines
    while (($row = @fgetcsv($file)) !== false) {
        if (!is_array($row) || empty($row) || (count($row) === 1 && empty($row[0]))) {
            continue;
        }
        
        // Handle rows with different column count
        if (count($row) !== count($header)) {
            error_log("[ADMIN_PANEL] Row has " . count($row) . " columns, expected " . count($header));
            if (count($row) < count($header)) {
                $row = array_pad($row, count($header), '');
            } else {
                $row = array_slice($row, 0, count($header));
            }
        }
        
        $combined = array_combine($header, $row);
        if ($combined !== false) {
            $data[] = $combined;
        }
    }
    
    fclose($file);
    return $data;
}

/**
 * Write CSV file with file locking
 */
function writeCSV(string $filepath, array $header, array $rows): bool
{
    $file = @fopen($filepath, 'w');
    if ($file === false) {
        error_log("[ADMIN_PANEL] Failed to write CSV: $filepath");
        return false;
    }
    
    $success = false;
    if (@flock($file, LOCK_EX)) {
        @fputcsv($file, $header);
        foreach ($rows as $row) {
            @fputcsv($file, $row);
        }
        @flock($file, LOCK_UN);
        $success = true;
    }
    fclose($file);
    return $success;
}

/**
 * Calculate folder size recursively
 */
function getFolderSize(string $path): int
{
    if (!is_dir($path) || !is_readable($path)) {
        return 0;
    }
    
    try {
        $iterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS)
        );
        return array_sum(
            array_map(
                fn(SplFileInfo $file): int => $file->isFile() ? $file->getSize() : 0,
                iterator_to_array($iterator)
            )
        );
    } catch (Exception $e) {
        error_log("[ADMIN_PANEL] Error calculating folder size: " . $e->getMessage());
        return 0;
    }
}

/**
 * Format bytes to human readable
 */
function formatBytes(int $bytes, int $precision = 2): string
{
    if ($bytes === 0) return '0 B';
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];
    $pow = min((int) floor(log($bytes, 1024)), count($units) - 1);
    return sprintf('%.2f %s', $bytes / (1 << (10 * $pow)), $units[$pow]);
}

/**
 * Log activity to CSV
 */
function logActivity(string $action, string $details, string $logPath): void
{
    $header = ['timestamp', 'admin', 'action', 'details'];
    $logDir = dirname($logPath);
    
    if (!is_dir($logDir) && !@mkdir($logDir, 0755, true)) {
        return;
    }
    
    $file = @fopen($logPath, 'a');
    if ($file === false) return;
    
    $exists = filesize($logPath) > 0;
    if (!$exists) @fputcsv($file, $header);
    
    @fputcsv($file, [
        date('Y-m-d H:i:s'),
        $_SESSION['user_name'] ?? 'unknown',
        $action,
        $details
    ]);
    fclose($file);
}

/**
 * Redirect with error message (never returns)
 */
function redirectWithError(string $location, string $message): never
{
    $_SESSION['error_msg'] = $message;
    header("Location: $location");
    exit;
}

// ===== PATHS SETUP =====
$paths = [
    'users' => $config->getPath($config->usersDir) . 'users.csv',
    'data' => $config->getPath($config->dataDir) . 'safety_talk.csv',
    'uploads' => $config->getPath($config->uploadsDir),
    'backups' => $config->getPath($config->backupsDir),
    'log' => $config->getPath($config->dataDir) . 'activity_log.csv',
];

// Default header for safety_talk.csv (when file has no header)
$safetyTalkHeader = ['tanggal', 'hari', 'departemen', 'divisi', 'nama', 'jabatan', 'topik', 'peserta', 'foto'];

// Ensure directories exist
foreach ([$config->dataDir, $config->uploadsDir, $config->backupsDir] as $dir) {
    $dirPath = $config->getPath($dir);
    if (!is_dir($dirPath) && !@mkdir($dirPath, 0755, true)) {
        error_log("[ADMIN_PANEL] Failed to create directory: $dirPath");
    }
}

// Check ZipArchive availability
$zipAvailable = class_exists('ZipArchive');

// ===== HANDLE FORM ACTIONS =====
$message = '';
$msgType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    
    // Validate CSRF token
    if (!hash_equals($_SESSION['csrf_token'] ?? '', $_POST['csrf_token'] ?? '')) {
        redirectWithError('admin_panel.php', '❌ Token keamanan tidak valid!');
    }
    
    // Handle actions using match expression (PHP 8.0+)
    $result = match ($action) {
        'add_user', 'edit_user' => handleUserAction($_POST, $action, $paths['users'], $paths['log']),
        'delete_user' => handleDeleteUser($_POST, $paths['users'], $paths['log']),
        'delete_record' => handleDeleteRecord($_POST, $paths['data'], $paths['log'], $safetyTalkHeader),
        'backup_system' => handleBackup($paths, $zipAvailable, $config),
        'clear_uploads' => handleClearUploads($paths['uploads'], $paths['log']),
        default => ['error' => '❌ Aksi tidak valid!', 'type' => 'error']
    };
    
    $message = $result['message'] ?? '';
    $msgType = $result['type'] ?? 'error';
}

// ===== ACTION HANDLERS (PHP 8.2+ Functions) =====

/**
 * Handle add/edit user action
 * @return array{message: string, type: string}
 */
function handleUserAction(array $post, string $action, string $usersPath, string $logPath): array
{
    $nama = trim($post['nama'] ?? '');
    $nik = trim($post['nik'] ?? '');
    $roles = $post['roles'] ?? 'petugas';
    $password = $post['password'] ?? '';
    $oldNama = $post['old_nama'] ?? '';
    
    if (empty($nama) || empty($nik) || ($action === 'add_user' && empty($password))) {
        return ['message' => '⚠️ Semua field wajib diisi!', 'type' => 'error'];
    }
    
    $users = readCSV($usersPath);
    $header = ['nama', 'nik', 'roles', 'password'];
    
    if ($action === 'add_user') {
        // Check duplicate using arrow function + nullsafe
        $duplicate = array_filter(
            $users,
            fn(array $u): bool =>
                (strtolower($u['nama'] ?? '') === strtolower($nama)) ||
                ($u['nik'] ?? '') === $nik
        );
        
        if (!empty($duplicate)) {
            return ['message' => '❌ Nama atau NIK sudah terdaftar!', 'type' => 'error'];
        }
        
        $users[] = ['nama' => $nama, 'nik' => $nik, 'roles' => $roles, 'password' => $password];
        
        if (writeCSV($usersPath, $header, $users)) {
            logActivity('ADD_USER', "Nama: $nama, NIK: $nik, Role: $roles", $logPath);
            return ['message' => '✅ User berhasil ditambahkan!', 'type' => 'success'];
        }
        return ['message' => '❌ Gagal menyimpan data user!', 'type' => 'error'];
        
    } else {
        // Edit existing using array_walk
        $updated = false;
        array_walk($users, function (&$u) use ($oldNama, $nik, $roles, $password, &$updated): void {
            if (($u['nama'] ?? '') === $oldNama) {
                $u['nik'] = $nik;
                $u['roles'] = $roles;
                if (!empty($password)) $u['password'] = $password;
                $updated = true;
            }
        });
        
        if ($updated && writeCSV($usersPath, $header, $users)) {
            logActivity('EDIT_USER', "Nama: $nama, NIK: $nik, Role: $roles", $logPath);
            return ['message' => '✅ Data user berhasil diperbarui!', 'type' => 'success'];
        }
        return ['message' => '❌ Gagal memperbarui data user!', 'type' => 'error'];
    }
}

/**
 * Handle delete user action
 */
function handleDeleteUser(array $post, string $usersPath, string $logPath): array
{
    $namaToDelete = $post['nama'] ?? '';
    
    if (empty($namaToDelete) || $namaToDelete === ($_SESSION['user_name'] ?? '')) {
        return ['message' => '❌ Tidak dapat menghapus user sendiri!', 'type' => 'error'];
    }
    
    $users = readCSV($usersPath);
    $header = ['nama', 'nik', 'roles', 'password'];
    
    // Filter using arrow function (clean & readable)
    $filtered = array_filter(
        $users,
        fn(array $u): bool => ($u['nama'] ?? '') !== $namaToDelete
    );
    
    if (writeCSV($usersPath, $header, array_values($filtered))) {
        logActivity('DELETE_USER', "Nama: $namaToDelete", $logPath);
        return ['message' => '✅ User berhasil dihapus!', 'type' => 'success'];
    }
    return ['message' => '❌ Gagal menghapus user!', 'type' => 'error'];
}

/**
 * Handle delete safety talk record
 */
function handleDeleteRecord(array $post, string $dataPath, string $logPath, array $header): array
{
    $rowId = filter_var($post['row_id'] ?? -1, FILTER_VALIDATE_INT);
    
    if ($rowId === false || $rowId < 0 || !file_exists($dataPath)) {
        return ['message' => '❌ Data tidak valid!', 'type' => 'error'];
    }
    
    // Read all data including first line
    $allData = readCSV($dataPath, $header);
    
    if (!isset($allData[$rowId])) {
        return ['message' => '❌ Data tidak ditemukan!', 'type' => 'error'];
    }
    
    // Remove the row
    unset($allData[$rowId]);
    $allData = array_values($allData); // Re-index
    
    // Write back without header (data-only CSV)
    $file = @fopen($dataPath, 'w');
    if ($file === false) {
        return ['message' => '❌ Gagal menulis data!', 'type' => 'error'];
    }
    
    foreach ($allData as $row) {
        @fputcsv($file, array_values($row));
    }
    fclose($file);
    
    logActivity('DELETE_RECORD', "Row ID: $rowId", $logPath);
    return ['message' => '✅ Data safety talk berhasil dihapus!', 'type' => 'success'];
}

/**
 * Handle system backup
 */
function handleBackup(array $paths, bool $zipAvailable, AppConfig $config): array
{
    if (!$zipAvailable) {
        return ['message' => '❌ Fitur backup tidak tersedia: extension ZipArchive tidak aktif.', 'type' => 'error'];
    }
    
    if (!is_dir($paths['backups']) && !@mkdir($paths['backups'], 0755, true)) {
        return ['message' => '❌ Gagal membuat folder backups/', 'type' => 'error'];
    }
    
    $backupName = 'backup_' . date('Ymd_His') . '.zip';
    $backupPath = $paths['backups'] . $backupName;
    
    $zip = new ZipArchive();
    if ($zip->open($backupPath, ZipArchive::CREATE) !== true) {
        return ['message' => '❌ Gagal membuat file backup.', 'type' => 'error'];
    }
    
    // Add files using match for cleaner logic
    foreach (['users' => 'users/users.csv', 'data' => 'data/safety_talk.csv'] as $key => $zipPath) {
        if (file_exists($paths[$key])) {
            $zip->addFile($paths[$key], $zipPath);
        }
    }
    
    // Add uploads folder
    if (is_dir($paths['uploads'])) {
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($paths['uploads'], RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::LEAVES_ONLY
        );
        foreach ($files as $file) {
            if ($file->isFile()) {
                $filePath = $file->getRealPath();
                $relativePath = 'uploads/' . substr($filePath, strlen($paths['uploads']));
                $zip->addFile($filePath, $relativePath);
            }
        }
    }
    
    if ($zip->close()) {
        logActivity('BACKUP', "File: $backupName", $paths['log']);
        return [
            'message' => "✅ Backup berhasil! <a href='backups/$backupName' download class='link-download'>Download</a>",
            'type' => 'success'
        ];
    }
    return ['message' => '❌ Gagal menutup file backup.', 'type' => 'error'];
}

/**
 * Handle clear uploads folder
 */
function handleClearUploads(string $uploadsPath, string $logPath): array
{
    if (!is_dir($uploadsPath) || !is_writable($uploadsPath)) {
        return ['message' => '❌ Folder uploads/ tidak dapat diakses.', 'type' => 'error'];
    }
    
    $count = 0;
    foreach (glob($uploadsPath . '*') as $file) {
        if (is_file($file) && @unlink($file)) $count++;
    }
    
    logActivity('CLEAR_UPLOADS', "Dihapus: $count file", $logPath);
    return ['message' => "✅ $count file foto berhasil dihapus dari uploads/", 'type' => 'info'];
}

// ===== LOAD DATA FOR DISPLAY =====
$users = readCSV($paths['users']);
$safetyData = readCSV($paths['data'], $safetyTalkHeader); // Use default header
$activityLog = readCSV($paths['log']);

// Stats using modern array functions
$totalUsers = count($users);
$totalRecords = count($safetyData);
$storageUsed = is_dir($paths['uploads']) ? getFolderSize($paths['uploads']) : 0;
$adminCount = count(array_filter($users, fn($u): bool => ($u['roles'] ?? '') === 'admin'));

// Get unique divisi using arrow function + nullsafe
$divisiOptions = array_unique(
    array_filter(
        array_column($safetyData, 'divisi'),
        fn($v): bool => !empty($v)
    )
);
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Panel | Safety Talk System</title>
    <!-- ✅ CDN URLs FIXED -->
    <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">
    <link rel="icon" type="image/x-icon" href="assets/img/clm_logo3.png">
    <style>
        :root {
            --primary: #0f172a; --primary-dark: #1e3a8a; --accent: #2563eb;
            --success: #059669; --warning: #f59e0b; --danger: #dc2626; --info: #0ea5e9;
            --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, sans-serif; background: var(--gray-50); color: var(--gray-900); line-height: 1.5; padding: 24px; min-height: 100vh; }
        .container { max-width: 1200px; margin: auto; }
        .page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; padding-bottom: 16px; border-bottom: 2px solid var(--primary); flex-wrap: wrap; gap: 12px; }
        .page-title { display: flex; align-items: center; gap: 12px; }
        .page-title i { font-size: 24px; color: var(--primary); }
        .page-title h1 { font-size: 20px; font-weight: 700; color: var(--gray-900); }
        .page-title small { display: block; font-size: 12px; color: var(--gray-500); font-weight: 400; margin-top: 2px; }
        .admin-badge { background: var(--warning); color: white; padding: 4px 12px; border-radius: 20px; font-size: 11px; font-weight: 600; display: inline-flex; align-items: center; gap: 4px; }
        .stats-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 16px; margin-bottom: 24px; }
        .stat-card { background: white; padding: 16px; border-radius: var(--radius-lg); border: 1px solid var(--gray-200); box-shadow: var(--shadow-sm); display: flex; align-items: center; gap: 12px; }
        .stat-icon { width: 44px; height: 44px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 18px; color: white; }
        .stat-icon.blue { background: var(--accent); }
        .stat-icon.green { background: var(--success); }
        .stat-icon.orange { background: var(--warning); }
        .stat-icon.purple { background: #7c3aed; }
        .stat-info .stat-val { font-size: 1.4rem; font-weight: 700; color: var(--gray-900); }
        .stat-info .stat-label { font-size: 11px; color: var(--gray-500); text-transform: uppercase; letter-spacing: 0.3px; }
        .tabs { display: flex; gap: 4px; background: white; padding: 6px; border-radius: var(--radius-lg); border: 1px solid var(--gray-200); margin-bottom: 20px; overflow-x: auto; }
        .tab-btn { flex: 1; min-width: 120px; padding: 10px 16px; border: none; background: none; border-radius: var(--radius); font-size: 13px; font-weight: 600; color: var(--gray-600); cursor: pointer; transition: var(--transition); display: flex; align-items: center; justify-content: center; gap: 6px; white-space: nowrap; }
        .tab-btn:hover { background: var(--gray-100); }
        .tab-btn.active { background: var(--primary); color: white; }
        .tab-btn i { font-size: 12px; }
        .tab-content { display: none; animation: fadeIn 0.3s ease; }
        .tab-content.active { display: block; }
        @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
        .card { background: white; border-radius: var(--radius-lg); border: 1px solid var(--gray-200); box-shadow: var(--shadow-md); margin-bottom: 20px; overflow: hidden; }
        .card-header { background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%); color: white; padding: 16px 20px; display: flex; justify-content: space-between; align-items: center; }
        .card-header h3 { font-size: 14px; font-weight: 600; display: flex; align-items: center; gap: 8px; }
        .card-body { padding: 20px; }
        .table-responsive { overflow-x: auto; }
        table { width: 100%; border-collapse: collapse; font-size: 13px; }
        th { background: var(--gray-100); padding: 12px 14px; text-align: left; font-weight: 600; color: var(--gray-700); text-transform: uppercase; font-size: 11px; letter-spacing: 0.3px; border-bottom: 2px solid var(--gray-200); }
        td { padding: 12px 14px; border-bottom: 1px solid var(--gray-100); vertical-align: middle; }
        tbody tr:hover { background: var(--gray-50); }
        .badge { display: inline-block; padding: 3px 10px; border-radius: 20px; font-size: 10px; font-weight: 600; }
        .badge-admin { background: #fef3c7; color: #92400e; }
        .badge-petugas { background: #dbeafe; color: #1e40af; }
        .badge-success { background: #dcfce7; color: #166534; }
        .badge-danger { background: #fee2e2; color: #b91c1c; }
        .btn { display: inline-flex; align-items: center; gap: 6px; padding: 8px 14px; border-radius: var(--radius); font-weight: 600; font-size: 12px; text-decoration: none; border: none; cursor: pointer; transition: var(--transition); white-space: nowrap; }
        .btn-primary { background: var(--primary); color: white; }
        .btn-primary:hover { background: var(--primary-dark); }
        .btn-success { background: var(--success); color: white; }
        .btn-success:hover { background: #047857; }
        .btn-danger { background: var(--danger); color: white; }
        .btn-danger:hover { background: #b91c1c; }
        .btn-outline { background: white; color: var(--gray-700); border: 1px solid var(--gray-300); }
        .btn-outline:hover { background: var(--gray-100); }
        .btn-sm { padding: 5px 10px; font-size: 11px; }
        .btn i { font-size: 11px; }
        .form-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 16px; }
        .form-group { display: flex; flex-direction: column; gap: 6px; }
        .form-group label { font-size: 12px; font-weight: 600; color: var(--gray-700); text-transform: uppercase; letter-spacing: 0.3px; }
        .form-control { padding: 10px 12px; border: 1px solid var(--gray-300); border-radius: var(--radius); font-size: 14px; background: var(--gray-50); transition: var(--transition); }
        .form-control:focus { outline: none; border-color: var(--accent); background: white; box-shadow: 0 0 0 3px rgba(37,99,235,0.1); }
        select.form-control { appearance: none; background-image: url("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; }
        .modal { display: none; position: fixed; z-index: 9999; top: 0; left: 0; width: 100%; height: 100%; background: rgba(15,23,42,0.7); justify-content: center; align-items: center; padding: 20px; animation: fadeIn 0.2s ease; }
        .modal.active { display: flex; }
        .modal-content { background: white; border-radius: var(--radius-lg); width: 100%; max-width: 500px; max-height: 90vh; overflow-y: auto; box-shadow: var(--shadow-lg); animation: slideUp 0.3s ease; }
        @keyframes slideUp { from { opacity: 0; transform: translateY(30px); } to { opacity: 1; transform: translateY(0); } }
        .modal-header { padding: 16px 20px; border-bottom: 1px solid var(--gray-200); display: flex; justify-content: space-between; align-items: center; }
        .modal-header h3 { font-size: 14px; font-weight: 600; }
        .modal-close { background: none; border: none; font-size: 20px; color: var(--gray-500); cursor: pointer; }
        .modal-close:hover { color: var(--danger); }
        .modal-body { padding: 20px; }
        .modal-footer { padding: 16px 20px; border-top: 1px solid var(--gray-200); display: flex; justify-content: flex-end; gap: 10px; }
        .alert { padding: 12px 16px; border-radius: var(--radius); margin-bottom: 20px; font-size: 13px; display: flex; align-items: flex-start; gap: 10px; animation: fadeIn 0.3s ease; }
        .alert-success { background: #ecfdf5; border: 1px solid #6ee7b7; color: #065f46; }
        .alert-error { background: #fef2f2; border: 1px solid #fecaca; color: #b91c1c; }
        .alert-info { background: #f0f9ff; border: 1px solid #7dd3fc; color: #075985; }
        .alert i { margin-top: 2px; }
        .alert .link-download { color: var(--accent); font-weight: 600; text-decoration: none; }
        .alert .link-download:hover { text-decoration: underline; }
        .filter-bar { display: flex; gap: 12px; margin-bottom: 16px; flex-wrap: wrap; }
        .filter-bar input, .filter-bar select { padding: 10px 12px; border: 1px solid var(--gray-300); border-radius: var(--radius); font-size: 13px; background: white; }
        .filter-bar input { flex: 1; min-width: 200px; }
        .log-entry { padding: 10px 0; border-bottom: 1px solid var(--gray-100); font-size: 12px; display: flex; gap: 12px; }
        .log-entry:last-child { border-bottom: none; }
        .log-time { color: var(--gray-500); font-family: monospace; min-width: 140px; }
        .log-admin { font-weight: 600; color: var(--primary); min-width: 120px; }
        .log-action { color: var(--gray-700); }
        .log-details { color: var(--gray-500); font-style: italic; }
        @media (max-width: 1024px) { .stats-grid { grid-template-columns: repeat(2, 1fr); } }
        @media (max-width: 768px) { 
            .page-header { flex-direction: column; align-items: flex-start; }
            .stats-grid { grid-template-columns: 1fr; }
            .form-grid { grid-template-columns: 1fr; }
            .tabs { flex-wrap: wrap; }
            .tab-btn { min-width: auto; flex: none; }
        }
        @media print { .no-print { display: none !important; } body { background: white; padding: 0; } }
        .text-right { text-align: right; }
        .text-center { text-align: center; }
        .text-muted { color: var(--gray-500); font-size: 12px; }
        .mt-16 { margin-top: 16px; }
        .mb-16 { margin-bottom: 16px; }
        .divider { height: 1px; background: var(--gray-200); margin: 20px 0; }
    </style>
</head>
<body>

<div class="container">
    <!-- Page Header -->
    <div class="page-header no-print">
        <div class="page-title">
            <i class="fas fa-user-shield"></i>
            <div>
                <h1>ADMIN PANEL</h1>
                <small>Manajemen Sistem • Safety Talk v<?= $config->appVersion ?></small>
            </div>
        </div>
        <div style="display:flex; align-items:center; gap:12px; flex-wrap:wrap;">
            <span class="admin-badge"><i class="fas fa-crown"></i> <?= htmlspecialchars($_SESSION['user_name'] ?? 'Admin') ?> (Admin)</span>
            <a href="index.php" class="btn btn-outline btn-sm"><i class="fas fa-home"></i> Dashboard</a>
            <a href="logout.php" class="btn btn-danger btn-sm"><i class="fas fa-sign-out-alt"></i> Logout</a>
        </div>
    </div>

    <!-- Alert Message -->
    <?php if ($message): ?>
    <div class="alert alert-<?= htmlspecialchars($msgType) ?>">
        <i class="fas fa-<?= match ($msgType) {
            'success' => 'circle-check',
            'error' => 'circle-exclamation',
            default => 'circle-info'
        } ?>"></i>
        <span><?= $message ?></span>
    </div>
    <?php endif; ?>

    <!-- Stats Cards -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-icon blue"><i class="fas fa-users"></i></div>
            <div class="stat-info"><span class="stat-val"><?= $totalUsers ?></span><span class="stat-label">Total User</span></div>
        </div>
        <div class="stat-card">
            <div class="stat-icon green"><i class="fas fa-file-alt"></i></div>
            <div class="stat-info"><span class="stat-val"><?= $totalRecords ?></span><span class="stat-label">Data Safety Talk</span></div>
        </div>
        <div class="stat-card">
            <div class="stat-icon orange"><i class="fas fa-hard-drive"></i></div>
            <div class="stat-info"><span class="stat-val"><?= formatBytes($storageUsed) ?></span><span class="stat-label">Storage Uploads</span></div>
        </div>
        <div class="stat-card">
            <div class="stat-icon purple"><i class="fas fa-shield-alt"></i></div>
            <div class="stat-info"><span class="stat-val"><?= $adminCount ?></span><span class="stat-label">Admin Aktif</span></div>
        </div>
    </div>

    <!-- Tabs Navigation -->
    <div class="tabs no-print">
        <button class="tab-btn active" onclick="switchTab('users')"><i class="fas fa-users"></i> Manajemen User</button>
        <button class="tab-btn" onclick="switchTab('data')"><i class="fas fa-database"></i> Data Safety Talk</button>
        <button class="tab-btn" onclick="switchTab('system')"><i class="fas fa-cog"></i> Pengaturan Sistem</button>
        <button class="tab-btn" onclick="switchTab('logs')"><i class="fas fa-clipboard-list"></i> Activity Log</button>
    </div>

    <!-- TAB: User Management -->
    <div id="tab-users" class="tab-content active">
        <div class="card">
            <div class="card-header">
                <h3><i class="fas fa-list"></i> Daftar Pengguna</h3>
                <button class="btn btn-success btn-sm" onclick="openModal('modalAddUser')"><i class="fas fa-plus"></i> Tambah User</button>
            </div>
            <div class="card-body">
                <?php if (empty($users)): ?>
                <p class="text-muted text-center">Belum ada user terdaftar.</p>
                <?php else: ?>
                <div class="table-responsive">
                    <table>
                        <thead><tr><th>Nama</th><th>NIK</th><th>Roles</th><th>Aksi</th></tr></thead>
                        <tbody>
                            <?php foreach ($users as $u):
                                if (!isset($u['nama'], $u['nik'], $u['roles'])) continue;
                            ?>
                            <tr>
                                <td><strong><?= htmlspecialchars($u['nama']) ?></strong></td>
                                <td><?= htmlspecialchars($u['nik']) ?></td>
                                <td>
                                    <span class="badge badge-<?= $u['roles'] === 'admin' ? 'admin' : 'petugas' ?>">
                                        <?= ucfirst(htmlspecialchars($u['roles'])) ?>
                                    </span>
                                </td>
                                <td style="display:flex; gap:6px;">
                                    <button class="btn btn-outline btn-sm" onclick="editUser('<?= htmlspecialchars($u['nama']) ?>','<?= htmlspecialchars($u['nik']) ?>','<?= htmlspecialchars($u['roles']) ?>')">
                                        <i class="fas fa-pen"></i>
                                    </button>
                                    <?php if ($u['nama'] !== ($_SESSION['user_name'] ?? '')): ?>
                                    <form method="POST" style="display:inline" onsubmit="return confirm('Hapus user <?= htmlspecialchars($u['nama']) ?>?')">
                                        <input type="hidden" name="action" value="delete_user">
                                        <input type="hidden" name="nama" value="<?= htmlspecialchars($u['nama']) ?>">
                                        <button type="submit" class="btn btn-danger btn-sm"><i class="fas fa-trash"></i></button>
                                    </form>
                                    <?php else: ?>
                                    <span class="text-muted" title="Tidak dapat menghapus diri sendiri"><i class="fas fa-lock"></i></span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- TAB: Data Management -->
    <div id="tab-data" class="tab-content">
        <div class="card">
            <div class="card-header">
                <h3><i class="fas fa-table"></i> Data Safety Talk</h3>
                <a href="rekap.php" class="btn btn-outline btn-sm" target="_blank"><i class="fas fa-external-link-alt"></i> Buka Rekap</a>
            </div>
            <div class="card-body">
                <div class="filter-bar">
                    <input type="text" id="dataSearch" placeholder="Cari nama/topik..." onkeyup="filterTable('safetyTable', this.value)">
                    <select id="dataDivisi" onchange="filterTableByDivisi()">
                        <option value="">Semua Divisi</option>
                        <?php foreach ($divisiOptions as $div): if ($div): ?>
                        <option value="<?= htmlspecialchars($div) ?>"><?= htmlspecialchars($div) ?></option>
                        <?php endif; endforeach; ?>
                    </select>
                </div>
                <?php if (empty($safetyData)): ?>
                <p class="text-muted text-center">Belum ada data safety talk.</p>
                <?php else: ?>
                <div class="table-responsive">
                    <table id="safetyTable">
                        <thead><tr><th>Tanggal</th><th>Nama</th><th>Topik</th><th>Divisi</th><th>Peserta</th><th>Aksi</th></tr></thead>
                        <tbody>
                            <?php foreach ($safetyData as $idx => $r):
                                if (!is_array($r) || count($r) < 8) continue;
                            ?>
                            <tr data-divisi="<?= htmlspecialchars($r['divisi'] ?? '') ?>">
                                <td><?= htmlspecialchars($r['tanggal'] ?? '-') ?></td>
                                <td><?= htmlspecialchars($r['nama'] ?? '-') ?></td>
                                <td><?= htmlspecialchars($r['topik'] ?? '-') ?></td>
                                <td><span class="badge badge-petugas"><?= htmlspecialchars($r['divisi'] ?? '-') ?></span></td>
                                <td class="text-center"><?= isset($r['peserta']) ? (int)$r['peserta'] : '-' ?></td>
                                <td>
                                    <form method="POST" onsubmit="return confirm('Hapus data ini?')" style="display:inline">
                                        <input type="hidden" name="action" value="delete_record">
                                        <input type="hidden" name="row_id" value="<?= (int)$idx ?>">
                                        <button type="submit" class="btn btn-danger btn-sm"><i class="fas fa-trash"></i></button>
                                    </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <p class="text-muted mt-16">* Menampilkan <?= count($safetyData) ?> record.</p>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- TAB: System Settings -->
    <div id="tab-system" class="tab-content">
        <div class="card">
            <div class="card-header"><h3><i class="fas fa-cog"></i> Pengaturan Sistem</h3></div>
            <div class="card-body">
                <div class="form-grid">
                    <div class="form-group">
                        <label>Versi Aplikasi</label>
                        <input type="text" class="form-control" value="v<?= $config->appVersion ?>" disabled>
                    </div>
                    <div class="form-group">
                        <label>PHP Version</label>
                        <input type="text" class="form-control" value="<?= htmlspecialchars(phpversion()) ?>" disabled>
                    </div>
                    <div class="form-group">
                        <label>Storage Uploads</label>
                        <input type="text" class="form-control" value="<?= formatBytes($storageUsed) ?>" disabled>
                    </div>
                    <div class="form-group">
                        <label>Timezone</label>
                        <input type="text" class="form-control" value="<?= $config->timezone ?>" disabled>
                    </div>
                </div>
                
                <div class="divider"></div>
                
                <h4 style="font-size:14px;font-weight:600;margin-bottom:16px">Maintenance</h4>
                <div style="display:flex; gap:12px; flex-wrap:wrap;">
                    <?php if ($zipAvailable): ?>
                    <form method="POST" onsubmit="return confirm('Buat backup sistem sekarang?')">
                        <input type="hidden" name="action" value="backup_system">
                        <button type="submit" class="btn btn-primary"><i class="fas fa-download"></i> Backup Sistem</button>
                    </form>
                    <?php else: ?>
                    <button class="btn btn-primary" disabled title="ZipArchive extension tidak aktif"><i class="fas fa-download"></i> Backup (Non-aktif)</button>
                    <?php endif; ?>
                    
                    <form method="POST" onsubmit="return confirm('Hapus SEMUA file di folder uploads/?')">
                        <input type="hidden" name="action" value="clear_uploads">
                        <button type="submit" class="btn btn-danger"><i class="fas fa-eraser"></i> Clear Uploads</button>
                    </form>
                    
                    <a href="users/users.csv" download class="btn btn-outline"><i class="fas fa-file-csv"></i> Export Users</a>
                    <a href="data/safety_talk.csv" download class="btn btn-outline"><i class="fas fa-file-csv"></i> Export Data</a>
                </div>
                
                <?php if (!$zipAvailable): ?>
                <div class="alert alert-warning mt-16">
                    <i class="fas fa-exclamation-triangle"></i>
                    <div><strong>Perhatian:</strong> Fitur backup memerlukan extension <code>ZipArchive</code>. Hubungi administrator untuk mengaktifkannya.</div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- TAB: Activity Log -->
    <div id="tab-logs" class="tab-content">
        <div class="card">
            <div class="card-header"><h3><i class="fas fa-history"></i> Activity Log</h3></div>
            <div class="card-body">
                <?php if (!empty($activityLog)): ?>
                <div style="max-height:400px; overflow-y:auto; border:1px solid var(--gray-200); border-radius:var(--radius);">
                    <?php foreach (array_reverse($activityLog) as $log):
                        if (!isset($log['timestamp'], $log['admin'], $log['action'])) continue;
                    ?>
                    <div class="log-entry">
                        <span class="log-time"><?= htmlspecialchars($log['timestamp']) ?></span>
                        <span class="log-admin"><?= htmlspecialchars($log['admin']) ?></span>
                        <span class="log-action"><strong><?= htmlspecialchars($log['action']) ?></strong></span>
                        <span class="log-details"><?= htmlspecialchars($log['details'] ?? '') ?></span>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php else: ?>
                <p class="text-center text-muted" style="padding:40px">
                    <i class="fas fa-inbox" style="font-size:40px;margin-bottom:12px;display:block"></i>
                    Belum ada aktivitas tercatat.
                </p>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- ===== MODAL: Add/Edit User ===== -->
<div id="modalAddUser" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="modalTitle"><i class="fas fa-user-plus"></i> Tambah User Baru</h3>
            <button class="modal-close" onclick="closeModal('modalAddUser')">&times;</button>
        </div>
        <form method="POST" id="userForm">
            <!-- CSRF Token -->
            <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
            <input type="hidden" name="action" id="formAction" value="add_user">
            <input type="hidden" name="old_nama" id="oldNama">
            
            <div class="modal-body">
                <div class="form-group">
                    <label>Nama Pengguna *</label>
                    <input type="text" name="nama" id="inputNama" class="form-control" required placeholder="Contoh: admin">
                </div>
                <div class="form-group">
                    <label>NIK *</label>
                    <input type="text" name="nik" id="inputNik" class="form-control" required placeholder="Contoh: 10001">
                </div>
                <div class="form-group">
                    <label>Roles *</label>
                    <select name="roles" id="inputRoles" class="form-control" required>
                        <option value="petugas">Petugas</option>
                        <option value="admin">Admin</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Password <span id="pwdHint">*</span></label>
                    <input type="password" name="password" id="inputPassword" class="form-control" required placeholder="••••••••">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline" onclick="closeModal('modalAddUser')">Batal</button>
                <button type="submit" class="btn btn-primary"><i class="fas fa-check"></i> Simpan</button>
            </div>
        </form>
    </div>
</div>

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

<!-- ===== SCRIPTS ===== -->
<script>
const switchTab = (tabId) => {
    document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active'));
    document.querySelectorAll('.tab-btn').forEach(el => el.classList.remove('active'));
    const target = document.getElementById(`tab-${tabId}`);
    if (target) {
        target.classList.add('active');
        event?.currentTarget?.classList.add('active');
    }
};

const openModal = (modalId) => {
    const modal = document.getElementById(modalId);
    if (modal) {
        modal.classList.add('active');
        document.body.style.overflow = 'hidden';
    }
};

const closeModal = (modalId) => {
    const modal = document.getElementById(modalId);
    if (modal) {
        modal.classList.remove('active');
        document.body.style.overflow = '';
        resetUserForm();
    }
};

const editUser = (nama, nik, roles) => {
    document.getElementById('formAction').value = 'edit_user';
    document.getElementById('modalTitle').innerHTML = '<i class="fas fa-user-edit"></i> Edit User';
    document.getElementById('oldNama').value = nama ?? '';
    document.getElementById('inputNama').value = nama ?? '';
    document.getElementById('inputNik').value = nik ?? '';
    document.getElementById('inputRoles').value = roles ?? 'petugas';
    document.getElementById('inputPassword').required = false;
    document.getElementById('inputPassword').placeholder = 'Kosongkan jika tidak diubah';
    document.getElementById('pwdHint').textContent = '(Kosongkan jika tidak diubah)';
    openModal('modalAddUser');
};

const resetUserForm = () => {
    document.getElementById('formAction').value = 'add_user';
    document.getElementById('modalTitle').innerHTML = '<i class="fas fa-user-plus"></i> Tambah User Baru';
    document.getElementById('userForm')?.reset();
    const pwdInput = document.getElementById('inputPassword');
    if (pwdInput) {
        pwdInput.required = true;
        pwdInput.placeholder = '••••••••';
    }
    document.getElementById('pwdHint').textContent = '*';
};

const filterTable = (tableId, query) => {
    const table = document.getElementById(tableId);
    if (!table) return;
    const rows = table.getElementsByTagName('tr');
    const q = (query ?? '').toLowerCase();
    
    for (let i = 1; i < rows.length; i++) {
        const cells = rows[i].getElementsByTagName('td');
        const match = Array.from(cells).slice(0, -1).some(cell =>
            cell?.textContent.toLowerCase().includes(q)
        );
        rows[i].style.display = match ? '' : 'none';
    }
};

const filterTableByDivisi = () => {
    const divisi = document.getElementById('dataDivisi').value;
    document.querySelectorAll('#safetyTable tbody tr').forEach(row => {
        const rowDivisi = row.dataset.divisi ?? '';
        row.style.display = (!divisi || rowDivisi === divisi) ? '' : 'none';
    });
};

// Event listeners
document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') {
        document.querySelectorAll('.modal.active').forEach(m => closeModal(m.id));
    }
});

document.querySelectorAll('.modal').forEach(modal => {
    modal.addEventListener('click', (e) => {
        if (e.target === modal) closeModal(modal.id);
    });
});

// Initialize tab from URL
const urlParams = new URLSearchParams(window.location.search);
const tabParam = urlParams.get('tab');
if (tabParam) {
    const tabBtn = document.querySelector(`.tab-btn[onclick*="${tabParam}"]`);
    tabBtn?.click();
}
</script>

</body>
</html>