<?php
declare(strict_types=1);
/* ====================================================
SAFETY TALK SYSTEM - PT CITRA LAMPIA MANDIRI
File        : index.php
Versi       : 2.5.0
Revisi      : 002 - Chart Styling Update (Solid Bars + System Font)
Fitur       : - ✅ Dashboard Stats: Total Laporan, Peserta, Target, Attendance Rate
              - ✅ Dual Dataset Chart: Hadir vs Seharusnya (SOLID BARS)
              - ✅ Attendance Rate Percentage dengan Color Coding
              - ✅ Dynamic Timeline (7 Hari Terakhir)
              - ✅ Chart Toggle (Bar ↔ Line View)
              - ✅ Donut Chart dengan Label Angka (SYSTEM FONT)
              - ✅ Quick Actions: Input, Rekap, Help, About
              - ✅ Footer Component Integration
              - ✅ PHP 8.2+ Strict Types + Backward Compatibility
              
📋 CSV Structure Support (9 or 10 columns):
  [0]tanggal, [1]hari, [2]departemen, [3]divisi, 
  [4]nama, [5]jabatan, [6]topik, [7]peserta, 
  [8]peserta_seharusnya (optional), [9]foto
====================================================
*/

// ===== 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 string $companyName = 'PT Citra Lampia Mandiri',
        public string $appName = 'Safety Talk System',
    ) {}
}

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

// ===== AUTH & SECURITY CHECK =====
if(session_status() === PHP_SESSION_NONE && !@session_start()) {
    error_log('[DASHBOARD] Failed to start session');
    header('Location: login.php');
    exit;
}

// 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();

// ===== INISIALISASI DATA =====
$totalTalk = 0;
$totalPeserta = 0;
$totalPesertaSeharusnya = 0;
$divisiCount = ["HS" => 0, "EF" => 0, "QMS" => 0];

// Penyiapan Tren 7 Hari Terakhir
$trenData = [];
for ($i = 6; $i >= 0; $i--) {
    $tgl = date('Y-m-d', strtotime("-$i days"));
    $tglDisplay = date('d/m', strtotime($tgl)); 
    $trenData[$tgl] = [
        'label' => $tglDisplay, 
        'hadir' => 0, 
        'seharusnya' => 0
    ];
}

// Load & Process CSV Data dengan error handling + backward compatibility
$csvPath = __DIR__ . '/data/safety_talk.csv';

if(file_exists($csvPath) && is_readable($csvPath)) {
    $file = @fopen($csvPath, 'r');
    if($file !== FALSE) {
        while(($row = @fgetcsv($file, 1000, ",")) !== FALSE) {
            // ✅ Validasi minimal 9 kolom (data lama) atau 10 kolom (data baru)
            if(!is_array($row) || count($row) < 9) continue;
            
            $tanggal = trim($row[0] ?? '');
            if(empty($tanggal)) continue;
            
            $totalTalk++;
            
            // Peserta Hadir (index 7)
            $peserta = isset($row[7]) ? (int) filter_var($row[7], FILTER_VALIDATE_INT) : 0;
            $totalPeserta += max(0, $peserta);
            
            // ✅ Peserta Seharusnya (index 8) - backward compatible
            $pesertaSeharusnya = isset($row[8]) ? (int) filter_var($row[8], FILTER_VALIDATE_INT) : $peserta;
            $totalPesertaSeharusnya += max(0, $pesertaSeharusnya);
            
            // Hitung Distribusi Divisi (validasi key array)
            $div = trim($row[3] ?? '');
            if(array_key_exists($div, $divisiCount)) {
                $divisiCount[$div]++;
            }

            // Hitung Tren Aktivitas (both hadir & seharusnya)
            if(isset($trenData[$tanggal])) {
                $trenData[$tanggal]['hadir'] += $peserta;
                $trenData[$tanggal]['seharusnya'] += $pesertaSeharusnya;
            }
        }
        @fclose($file);
    }
}

// ✅ Hitung Attendance Rate
$attendanceRate = $totalPesertaSeharusnya > 0 
    ? min(100, round(($totalPeserta / $totalPesertaSeharusnya) * 100, 1)) 
    : 0;

// Persiapan Data untuk JavaScript dengan error handling
$labelsTimeline = [];
$valuesHadir = [];
$valuesSeharusnya = [];

foreach($trenData as $data) {
    $labelsTimeline[] = $data['label'];
    $valuesHadir[] = $data['hadir'];
    $valuesSeharusnya[] = $data['seharusnya'];
}

// Encode JSON dengan error checking
$jsonOptions = JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT;
$labelsTimelineJSON = json_encode($labelsTimeline, $jsonOptions) ?: '[]';
$valuesHadirJSON = json_encode($valuesHadir, $jsonOptions) ?: '[]';
$valuesSeharusnyaJSON = json_encode($valuesSeharusnya, $jsonOptions) ?: '[]';
$dataDivisiJSON = json_encode(array_values($divisiCount), $jsonOptions) ?: '[0,0,0]';

// Session User Info (untuk footer)
$userName = $_SESSION['user_name'] ?? 'Guest';
$userRole = $_SESSION['user_role'] ?? 'Pengguna';
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard QHSEF | <?= htmlspecialchars($config->companyName) ?></title>
    
    <!-- ✅ Fonts & Icons (URLs cleaned) -->
    <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">
    
    <!-- ✅ Chart Libraries (URLs cleaned) -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.0.0"></script>
    
    <style>
        :root {
            /* Color System */
            --primary: #0f172a;
            --primary-dark: #1e3a8a;
            --primary-light: #3b82f6;
            --accent: #2563eb;
            --success: #059669;
            --success-light: #10b981;
            --warning: #f59e0b;
            --danger: #dc2626;
            
            /* Grays */
            --gray-50: #f8fafc;
            --gray-100: #f1f5f9;
            --gray-200: #e2e8f0;
            --gray-300: #cbd5e1;
            --gray-400: #94a3b8;
            --gray-500: #64748b;
            --gray-600: #475569;
            --gray-700: #334155;
            --gray-900: #0f172a;
            
            /* UI Variables */
            --bg: var(--gray-50);
            --border: var(--gray-200);
            --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(--bg); 
            padding: 24px; 
            color: var(--gray-900);
            line-height: 1.5;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }

        .container { max-width: 1100px; margin: auto; width: 100%; flex: 1; }
        
        /* ===== HEADER SECTION ===== */
        .header-area { 
            margin-bottom: 25px; 
            display: flex; 
            justify-content: space-between; 
            align-items: flex-end;
            flex-wrap: wrap;
            gap: 12px;
            padding-bottom: 16px;
            border-bottom: 2px solid var(--primary);
        }
        .header-area h2 { 
            margin: 0; 
            color: var(--primary); 
            font-size: 1.5rem; 
            font-weight: 700;
        }
        .header-area p { 
            margin: 5px 0 0 0; 
            color: var(--gray-500); 
            font-size: 0.9rem; 
        }
        .header-meta {
            text-align: right; 
            color: var(--gray-500); 
            font-size: 0.8rem; 
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 6px;
        }
        .header-meta i { color: var(--accent); }
        .version-badge {
            background: rgba(37, 99, 235, 0.1);
            color: var(--accent);
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 10px;
            font-weight: 600;
            margin-left: 8px;
        }

        /* ===== STATS CARDS ===== */
        .stats-grid { 
            display: grid; 
            grid-template-columns: repeat(4, 1fr); 
            gap: 20px; 
            margin-bottom: 25px;
        }
        .stat-card { 
            background: white; 
            padding: 20px; 
            border-radius: var(--radius-lg); 
            display: flex; 
            align-items: center; 
            gap: 15px; 
            border: 1px solid var(--border); 
            border-bottom: 4px solid var(--accent); 
            box-shadow: var(--shadow-sm);
            transition: var(--transition);
            position: relative;
            overflow: hidden;
        }
        .stat-card::before {
            content: '';
            position: absolute;
            top: 0; left: 0; right: 0;
            height: 3px;
            background: linear-gradient(90deg, var(--accent), var(--primary-light));
            opacity: 0;
            transition: opacity 0.2s ease;
        }
        .stat-card:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow-md);
        }
        .stat-card:hover::before { opacity: 1; }
        
        .stat-card i { 
            font-size: 2rem; 
            color: var(--accent); 
            opacity: 0.9; 
            width: 45px;
            text-align: center;
        }
        .stat-card:nth-child(2) i { color: var(--success-light); }
        .stat-card:nth-child(2) { border-bottom-color: var(--success-light); }
        .stat-card:nth-child(2)::before { background: linear-gradient(90deg, var(--success-light), var(--success)); }
        .stat-card:nth-child(3) i { color: var(--warning); }
        .stat-card:nth-child(3) { border-bottom-color: var(--warning); }
        .stat-card:nth-child(3)::before { background: linear-gradient(90deg, var(--warning), #f97316); }
        .stat-card:nth-child(4) i { 
            color: <?= $attendanceRate >= 80 ? 'var(--success)' : ($attendanceRate >= 50 ? 'var(--warning)' : 'var(--danger)') ?>; 
        }
        .stat-card:nth-child(4) { 
            border-bottom-color: <?= $attendanceRate >= 80 ? 'var(--success)' : ($attendanceRate >= 50 ? 'var(--warning)' : 'var(--danger)') ?>; 
        }
        
        .stat-val { 
            font-size: 1.5rem; 
            font-weight: 700; 
            display: block; 
            color: var(--primary);
            line-height: 1.2;
        }
        .stat-label { 
            font-size: 0.7rem; 
            color: var(--gray-500); 
            text-transform: uppercase; 
            letter-spacing: 0.5px; 
            font-weight: 600;
            display: block;
        }
        .stat-sub {
            font-size: 0.65rem;
            color: var(--gray-400);
            margin-top: 2px;
            display: block;
        }
        .rate-badge {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 10px;
            font-size: 0.65rem;
            font-weight: 700;
            background: <?= $attendanceRate >= 80 ? '#dcfce7' : ($attendanceRate >= 50 ? '#fef3c7' : '#fee2e2') ?>;
            color: <?= $attendanceRate >= 80 ? '#166534' : ($attendanceRate >= 50 ? '#92400e' : '#b91c1c') ?>;
            margin-top: 4px;
        }

        /* ===== CHARTS SECTION ===== */
        .grid-charts { 
            display: grid; 
            grid-template-columns: 2fr 1fr; 
            gap: 20px; 
            margin-bottom: 25px; 
        }
        .card { 
            background: white; 
            padding: 20px; 
            border-radius: var(--radius-lg); 
            border: 1px solid var(--border); 
            box-shadow: var(--shadow-md); 
            position: relative;
        }
        .card h4 { 
            margin: 0 0 20px 0; 
            color: var(--primary); 
            font-size: 0.95rem; 
            font-weight: 600;
            display: flex; 
            align-items: center; 
            gap: 10px; 
        }
        .card h4 i { color: var(--accent); }
        
        /* Toggle Button */
        .btn-toggle { 
            position: absolute; 
            top: 15px; 
            right: 15px; 
            padding: 6px 12px; 
            background: #fff; 
            border: 1px solid var(--gray-300); 
            border-radius: 6px; 
            cursor: pointer; 
            font-size: 11px; 
            font-weight: 700; 
            color: var(--gray-600); 
            transition: var(--transition); 
            display: flex; 
            align-items: center; 
            gap: 5px;
            z-index: 5;
        }
        .btn-toggle:hover { 
            background: var(--primary); 
            color: white; 
            border-color: var(--primary);
            transform: translateY(-1px);
        }

        /* Chart Legend */
        .chart-legend {
            display: flex;
            gap: 16px;
            margin-top: 12px;
            justify-content: center;
            font-size: 11px;
        }
        .legend-item {
            display: flex;
            align-items: center;
            gap: 6px;
            color: var(--gray-600);
        }
        .legend-color {
            width: 12px;
            height: 12px;
            border-radius: 3px;
        }
        .legend-color.hadir { background: rgba(37, 99, 235, 0.7); }
        /* ✅ UPDATED: Solid color for seharusnya (no dashed border) */
        .legend-color.seharusnya { background: rgba(245, 158, 11, 0.7); }

        /* ===== ACTION BUTTONS ===== */
        .btn-group { 
            display: flex; 
            gap: 15px; 
            margin-top: 25px;
            flex-wrap: wrap;
        }
        .btn { 
            flex: 1; 
            min-width: 180px;
            padding: 14px 20px; 
            border-radius: var(--radius-lg); 
            text-decoration: none; 
            font-weight: 600; 
            text-align: center; 
            transition: var(--transition); 
            display: flex; 
            align-items: center; 
            justify-content: center; 
            gap: 10px; 
            font-size: 0.9rem;
            border: none;
            cursor: pointer;
        }
        .btn i { font-size: 1rem; }
        
        .btn-primary { 
            background: var(--primary); 
            color: white; 
        }
        .btn-primary:hover { 
            background: var(--primary-dark); 
            transform: translateY(-2px); 
            box-shadow: var(--shadow-md);
        }
        
        .btn-outline { 
            background: white; 
            color: var(--primary); 
            border: 1px solid var(--gray-300);
        }
        .btn-outline:hover { 
            background: var(--gray-100); 
            transform: translateY(-2px);
            box-shadow: var(--shadow-sm);
        }
        
        /* Button Variants */
        .btn-outline.help-btn { 
            border-color: var(--success); 
            color: var(--success); 
        }
        .btn-outline.help-btn:hover { 
            background: #ecfdf5; 
            border-color: var(--success-light);
            color: var(--success-light);
        }

        .btn-outline.about-btn { 
            border-color: #7c3aed; 
            color: #7c3aed; 
        }
        .btn-outline.about-btn:hover { 
            background: #f5f3ff; 
            border-color: #6d28d9;
            color: #6d28d9;
        }

        /* ===== RESPONSIVE ===== */
        @media (max-width: 1024px) { 
            .stats-grid { grid-template-columns: repeat(2, 1fr); }
        }
        @media (max-width: 850px) { 
            .grid-charts { grid-template-columns: 1fr; }
            .header-area { flex-direction: column; align-items: flex-start; }
            .header-meta { text-align: left; }
        }
        @media (max-width: 640px) {
            body { padding: 16px; }
            .btn-group { flex-direction: column; }
            .btn { min-width: 100%; }
            .stat-card { padding: 16px; }
            .stat-val { font-size: 1.3rem; }
            .stats-grid { grid-template-columns: 1fr; }
        }

        /* ===== PRINT ===== */
        @media print {
            .no-print { display: none !important; }
            body { background: white; padding: 0; }
            .card { box-shadow: none; border: 1px solid #000; }
        }

        /* ===== 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-center { text-align: center; }
        .mt-20 { margin-top: 20px; }
    </style>
</head>
<body>

<div class="container">
    <!-- ===== HEADER ===== -->
    <div class="header-area">
        <div>
            <h2><i class="fas fa-chart-line"></i> Executive Dashboard 
                <span class="version-badge">v<?= $config->appVersion ?> Rev.<?= $config->revision ?></span>
            </h2>
            <p>Safety Talk Analytics • QHSEF Department</p>
        </div>
        <div class="header-meta">
            <i class="fas fa-clock"></i> 
            Update: <span id="headerTime"><?= date('H:i') ?></span>
        </div>
    </div>

    <!-- ===== STATS CARDS ===== -->
    <div class="stats-grid">
        <div class="stat-card">
            <i class="fas fa-file-signature"></i>
            <div>
                <span class="stat-val"><?= number_format($totalTalk) ?></span>
                <span class="stat-label">Total Laporan</span>
            </div>
        </div>
        <div class="stat-card">
            <i class="fas fa-users"></i>
            <div>
                <span class="stat-val"><?= number_format($totalPeserta, 0, ',', '.') ?></span>
                <span class="stat-label">Peserta Hadir</span>
                <span class="stat-sub">dari <?= number_format($totalPesertaSeharusnya, 0, ',', '.') ?> target</span>
            </div>
        </div>
        <div class="stat-card">
            <i class="fas fa-calendar-week"></i>
            <div>
                <span class="stat-val"><?= date('d M Y') ?></span>
                <span class="stat-label">Minggu Ke-<?= date('W') ?></span>
            </div>
        </div>
        <div class="stat-card">
            <i class="fas fa-percentage"></i>
            <div>
                <span class="stat-val"><?= $attendanceRate ?>%</span>
                <span class="stat-label">Attendance Rate</span>
                <span class="rate-badge">
                    <?= $attendanceRate >= 80 ? '✅ Baik' : ($attendanceRate >= 50 ? '⚠️ Cukup' : '❌ Perlu Perbaikan') ?>
                </span>
            </div>
        </div>
    </div>

    <!-- ===== CHARTS ===== -->
    <div class="grid-charts">
        <!-- Timeline Chart -->
        <div class="card">
            <h4><i class="fas fa-chart-area"></i> Tren Kehadiran (7 Hari Terakhir)</h4>
            <button class="btn-toggle no-print" onclick="toggleChart()" title="Ganti tipe grafik">
                <i class="fas fa-sliders-h"></i> <span id="toggleLabel">Bar</span>
            </button>
            <div style="height: 300px; position: relative;">
                <canvas id="mainChart"></canvas>
            </div>
            <div class="chart-legend no-print">
                <div class="legend-item">
                    <div class="legend-color hadir"></div>
                    <span>Peserta Hadir</span>
                </div>
                <div class="legend-item">
                    <div class="legend-color seharusnya"></div>
                    <span>Peserta Seharusnya</span>
                </div>
            </div>
        </div>

        <!-- Donut Chart -->
        <div class="card">
            <h4><i class="fas fa-chart-pie"></i> Distribusi Divisi</h4>
            <div style="height: 300px; position: relative;">
                <canvas id="pieChart"></canvas>
            </div>
        </div>
    </div>

    <!-- ===== ACTION BUTTONS ===== -->
    <div class="btn-group no-print">
        <a href="formulir/input_safety_talk.php" class="btn btn-primary">
            <i class="fas fa-plus-circle"></i> Input Safety Talk
        </a>
        <a href="rekap.php" class="btn btn-outline">
            <i class="fas fa-table"></i> Rekap Data
        </a>
        <a href="help.php" class="btn btn-outline help-btn">
            <i class="fas fa-circle-question"></i> Bantuan
        </a>
        <a href="about.php" class="btn btn-outline about-btn">
            <i class="fas fa-info-circle"></i> Tentang
        </a>
    </div>

    <!-- ===== QUICK INFO ===== -->
    <div class="text-center mt-20" style="color: var(--gray-500); font-size: 0.75rem;">
        <i class="fas fa-info-circle"></i> 
        Data terakhir: <?= $totalTalk > 0 ? 'Aktif' : 'Belum ada data' ?> • 
        Versi: v<?= $config->appVersion ?> Rev.<?= $config->revision ?> • 
        <a href="#" onclick="window.scrollTo({top:0,behavior:'smooth'});return false;" style="color:var(--accent);text-decoration:none">
            ↑ Atas
        </a>
    </div>
</div>

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

<!-- ===== CHART SCRIPTS ===== -->
<script>
// ===== DATA FROM PHP (with fallback) =====
const labelTimeline = <?= $labelsTimelineJSON ?>;
const dataHadir = <?= $valuesHadirJSON ?>;
const dataSeharusnya = <?= $valuesSeharusnyaJSON ?>;
const dataDivisi = <?= $dataDivisiJSON ?>;
const labelDivisi = ["Health & Safety", "Environment", "Quality Mgmt"];
const colorDivisi = ['#ef4444', '#10b981', '#f59e0b'];

// ===== VALIDASI DATA =====
if(!Array.isArray(labelTimeline)) console.error('Timeline labels invalid');
if(!Array.isArray(dataHadir)) console.error('Timeline hadir data invalid');
if(!Array.isArray(dataSeharusnya)) console.error('Timeline seharusnya data invalid');
if(!Array.isArray(dataDivisi)) console.error('Divisi data invalid');

// ===== REGISTER PLUGINS =====
if(typeof Chart !== 'undefined' && typeof ChartDataLabels !== 'undefined') {
    Chart.register(ChartDataLabels);
} else {
    console.error('Chart.js or plugin not loaded');
}

// ===== MAIN CHART (Timeline - Dual Dataset with SOLID BARS) =====
let chartType = 'bar';
let mainChart;

function renderMainChart(type) {
    const canvas = document.getElementById('mainChart');
    if(!canvas) return;
    
    const ctx = canvas.getContext('2d');
    if(mainChart) mainChart.destroy();

    mainChart = new Chart(ctx, {
        type: type,
        data: {
            labels: labelTimeline,
            datasets: [
                {
                    label: 'Peserta Hadir',
                    data: dataHadir,
                    backgroundColor: type === 'bar' ? 'rgba(37, 99, 235, 0.7)' : 'rgba(37, 99, 235, 0.1)',
                    borderColor: '#2563eb',
                    borderWidth: 2,
                    fill: true,
                    tension: 0.4,
                    borderRadius: type === 'bar' ? 5 : 0,
                    pointRadius: 4,
                    pointHoverRadius: 6,
                    order: 2
                },
                {
                    label: 'Peserta Seharusnya',
                    data: dataSeharusnya,
                    // ✅ UPDATED: Solid bar fill (no transparent, no dashed)
                    backgroundColor: type === 'bar' ? 'rgba(245, 158, 11, 0.5)' : 'rgba(245, 158, 11, 0.1)',
                    borderColor: '#f59e0b',
                    borderWidth: 2,
                    // ✅ REMOVED: borderDash: [5, 5] untuk solid line
                    fill: true,
                    tension: 0.4,
                    borderRadius: type === 'bar' ? 5 : 0,
                    pointRadius: 3,
                    pointHoverRadius: 5,
                    pointBackgroundColor: '#f59e0b',
                    order: 1
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            animation: { duration: 500, easing: 'easeOutQuart' },
            plugins: {
                legend: { display: false },
                tooltip: {
                    padding: 12,
                    cornerRadius: 8,
                    backgroundColor: 'rgba(15, 23, 42, 0.95)',
                    titleColor: '#fff',
                    bodyColor: '#fff',
                    displayColors: true,
                    callbacks: {
                        label: function(context) {
                            const hadir = context.dataset.data[context.dataIndex];
                            const seharusnya = dataSeharusnya[context.dataIndex];
                            const rate = seharusnya > 0 ? ((hadir / seharusnya) * 100).toFixed(1) : 0;
                            return `${context.dataset.label}: ${hadir} (${rate}% dari target)`;
                        }
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: { 
                        stepSize: 1, 
                        font: { size: 10, weight: '600' },
                        color: '#64748b'
                    },
                    grid: { color: 'rgba(0, 0, 0, 0.05)', drawBorder: false }
                },
                x: {
                    grid: { color: 'rgba(0, 0, 0, 0.03)', drawBorder: false },
                    ticks: { font: { size: 10, weight: '600' }, color: '#64748b' }
                }
            }
        }
    });
    
    // Update toggle label
    const toggleLabel = document.getElementById('toggleLabel');
    if(toggleLabel) {
        toggleLabel.textContent = type === 'bar' ? 'Bar' : 'Line';
    }
}

function toggleChart() {
    chartType = (chartType === 'bar') ? 'line' : 'bar';
    renderMainChart(chartType);
}

// ===== PIE CHART (Donut with Numbers - SYSTEM FONT) =====
const pieCanvas = document.getElementById('pieChart');
if(pieCanvas) {
    const ctxPie = pieCanvas.getContext('2d');
    new Chart(ctxPie, {
        type: 'doughnut',
        data: {
            labels: labelDivisi,
            datasets: [{
                data: dataDivisi,
                backgroundColor: colorDivisi,
                hoverOffset: 12,
                borderWidth: 3,
                borderColor: '#ffffff',
                hoverBorderColor: '#ffffff'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            animation: { animateRotate: true, animateScale: true },
            plugins: {
                legend: { 
                    position: 'bottom', 
                    labels: { 
                        boxWidth: 14,
                        padding: 12,
                        // ✅ UPDATED: System font stack (Arial/Helvetica/sans-serif)
                        font: { 
                            size: 11, 
                            weight: '600', 
                            family: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'
                        },
                        color: '#334155',
                        usePointStyle: true
                    }
                },
                tooltip: {
                    backgroundColor: 'rgba(15, 23, 42, 0.95)',
                    titleColor: '#fff',
                    bodyColor: '#fff',
                    padding: 12,
                    cornerRadius: 8,
                    callbacks: {
                        label: function(context) {
                            const total = context.dataset.data.reduce((a,b) => a+b, 0);
                            const pct = total > 0 ? ((context.parsed / total) * 100).toFixed(1) : 0;
                            return `${context.label}: ${context.parsed} (${pct}%)`;
                        }
                    }
                },
                datalabels: {
                    color: '#ffffff',
                    // ✅ UPDATED: System font for datalabels too
                    font: { 
                        weight: 'bold', 
                        size: 13, 
                        family: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'
                    },
                    formatter: (value) => value > 0 ? value : '',
                    anchor: 'center',
                    align: 'center',
                    offset: 0,
                    textShadow: true
                }
            },
            cutout: '70%'
        }
    });
}

// ===== REAL-TIME CLOCK UPDATE =====
function updateHeaderTime() {
    const timeEl = document.getElementById('headerTime');
    if(!timeEl) return;
    
    const now = new Date();
    const timeStr = now.toLocaleTimeString('id-ID', {
        hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false
    });
    timeEl.textContent = timeStr;
}
setInterval(updateHeaderTime, 1000);

// ===== INITIALIZATION =====
document.addEventListener('DOMContentLoaded', function() {
    renderMainChart(chartType);
    
    // Subtle entrance animation for cards
    document.querySelectorAll('.stat-card, .card').forEach((el, i) => {
        el.style.opacity = '0';
        el.style.transform = 'translateY(10px)';
        el.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
        setTimeout(() => {
            el.style.opacity = '1';
            el.style.transform = 'translateY(0)';
        }, 100 + (i * 50));
    });
});

// ===== KEYBOARD SHORTCUTS =====
document.addEventListener('keydown', function(e) {
    if(e.ctrlKey || e.metaKey) {
        if(e.key === '1') { e.preventDefault(); window.location.href = 'formulir/input_safety_talk.php'; }
        if(e.key === '2') { e.preventDefault(); window.location.href = 'rekap.php'; }
        if(e.key === 'h' || e.key === 'H') { e.preventDefault(); window.location.href = 'help.php'; }
        if(e.key === 'a' || e.key === 'A') { e.preventDefault(); window.location.href = 'about.php'; }
    }
});
</script>

</body>
</html>