<?php
session_start();

// Validasi session
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
    header("Location: ../../index.html?error=session");
    exit;
}

$userRole = strtoupper(trim($_SESSION['role'] ?? ''));
if ($userRole !== 'M' && $userRole !== 'A') {
    header("Location: ../../index.html?error=forbidden");
    exit;
}

require_once __DIR__ . '/../../DataBase/koneksi.php';

// Handle success messages
$successMessage = '';
if (isset($_GET['success'])) {
    switch ($_GET['success']) {
        case 'added':
            $successMessage = 'Data SDM berhasil ditambahkan!';
            break;
        case 'updated':
            $successMessage = 'Data SDM berhasil diupdate!';
            break;
        case 'deleted':
            $successMessage = 'Data SDM berhasil dihapus!';
            break;
        case 'imported':
            $count = isset($_GET['count']) ? (int)$_GET['count'] : 0;
            $successMessage = "Berhasil mengimport $count data SDM!";
            break;
    }
}

// Handle pencarian dan filter
$search = isset($_GET['search']) ? mysqli_real_escape_string($conn, $_GET['search']) : '';
$filter_kantor = isset($_GET['kantor']) ? mysqli_real_escape_string($conn, $_GET['kantor']) : '';
$filter_jabatan = isset($_GET['jabatan']) ? mysqli_real_escape_string($conn, $_GET['jabatan']) : '';
$filter_status = isset($_GET['status']) ? mysqli_real_escape_string($conn, $_GET['status']) : '';

// Build WHERE clause
$whereClause = "1=1";
if (!empty($search)) {
    $whereClause .= " AND (nama LIKE '%$search%' OR nip LIKE '%$search%' OR email LIKE '%$search%')";
}
if (!empty($filter_kantor)) {
    $whereClause .= " AND kantor = '$filter_kantor'";
}
if (!empty($filter_jabatan)) {
    $whereClause .= " AND jabatan = '$filter_jabatan'";
}
if (!empty($filter_status)) {
    $whereClause .= " AND status = '$filter_status'";
}

// Get data untuk filter options
$kantorList = [];
$qKantor = mysqli_query($conn, "SELECT DISTINCT kantor FROM sdm WHERE kantor IS NOT NULL ORDER BY kantor");
while($r = mysqli_fetch_assoc($qKantor)) { $kantorList[] = $r['kantor']; }

$jabatanList = [];
$qJabatan = mysqli_query($conn, "SELECT DISTINCT jabatan FROM sdm WHERE jabatan IS NOT NULL ORDER BY jabatan");
while($r = mysqli_fetch_assoc($qJabatan)) { $jabatanList[] = $r['jabatan']; }

// Pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 15;
$offset = ($page - 1) * $perPage;

// Get total records
$queryCount = "SELECT COUNT(*) as total FROM sdm WHERE $whereClause";
$resultCount = mysqli_query($conn, $queryCount);
$totalRecords = mysqli_fetch_assoc($resultCount)['total'];
$totalPages = ceil($totalRecords / $perPage);

// Get SDM data
$querySdm = "SELECT * FROM sdm WHERE $whereClause ORDER BY nama ASC LIMIT $offset, $perPage";
$resultSdm = mysqli_query($conn, $querySdm);

// Get statistics
$queryStats = "SELECT 
    COUNT(*) as total_sdm,
    SUM(CASE WHEN status = 'Aktif' THEN 1 ELSE 0 END) as aktif,
    SUM(CASE WHEN status = 'Non-Aktif' THEN 1 ELSE 0 END) as non_aktif,
    SUM(CASE WHEN jenis_kelamin = 'Laki-laki' THEN 1 ELSE 0 END) as laki_laki,
    SUM(CASE WHEN jenis_kelamin = 'Perempuan' THEN 1 ELSE 0 END) as perempuan
    FROM sdm WHERE $whereClause";
$resultStats = mysqli_query($conn, $queryStats);
$statsRaw = mysqli_fetch_assoc($resultStats);

$stats = [
    'total_sdm' => $statsRaw['total_sdm'] ?? 0,
    'aktif' => $statsRaw['aktif'] ?? 0,
    'non_aktif' => $statsRaw['non_aktif'] ?? 0,
    'laki_laki' => $statsRaw['laki_laki'] ?? 0,
    'perempuan' => $statsRaw['perempuan'] ?? 0
];

// Get data by department/kantor untuk chart
$queryByKantor = "SELECT kantor, COUNT(*) as jumlah FROM sdm WHERE kantor IS NOT NULL GROUP BY kantor ORDER BY jumlah DESC LIMIT 6";
$resultKantor = mysqli_query($conn, $queryByKantor);
$dataKantor = [];
while($row = mysqli_fetch_assoc($resultKantor)) {
    $dataKantor[] = $row;
}

// Get data by position/jabatan untuk chart
$queryByJabatan = "SELECT jabatan, COUNT(*) as jumlah FROM sdm WHERE jabatan IS NOT NULL GROUP BY jabatan ORDER BY jumlah DESC LIMIT 6";
$resultJabatan = mysqli_query($conn, $queryByJabatan);
$dataJabatan = [];
while($row = mysqli_fetch_assoc($resultJabatan)) {
    $dataJabatan[] = $row;
}

function getInitials($name) {
    $words = explode(' ', $name);
    if (count($words) >= 2) {
        return strtoupper(substr($words[0], 0, 1) . substr($words[1], 0, 1));
    }
    return strtoupper(substr($name, 0, 2));
}

function getRandomColor() {
    $colors = ['#7AB2B2', '#4D869C', '#16a34a', '#1e40af', '#ea580c', '#7c3aed', '#dc2626'];
    return $colors[array_rand($colors)];
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Data SDM - ACF EDU HUB</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
    <style>
        :root {
            --primary-teal: #7AB2B2;
            --secondary-teal: #4D869C;
            --light-mint: #CDE8E5;
            --lightest-mint: #EEF7FF;
            --bg-light: #f8fafc;
            --text-dark: #1e293b;
            --text-medium: #475569;
            --text-light: #64748b;
            --border-color: #e2e8f0;
            --purple: #6366f1;
        }

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

        body {
            font-family: 'Inter', sans-serif;
            background: var(--bg-light);
            color: var(--text-dark);
            padding: 24px;
            line-height: 1.6;
        }

        .container { max-width: 1600px; margin: 0 auto; }

        /* Success Alert */
        .alert-container {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 9999;
            animation: slideInRight 0.3s ease;
        }

        @keyframes slideInRight {
            from { transform: translateX(400px); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }

        @keyframes slideOutRight {
            from { transform: translateX(0); opacity: 1; }
            to { transform: translateX(400px); opacity: 0; }
        }

        .alert-container.closing {
            animation: slideOutRight 0.3s ease;
        }

        .alert {
            background: white;
            border-radius: 12px;
            padding: 16px 20px;
            box-shadow: 0 8px 24px rgba(0,0,0,0.15);
            display: flex;
            align-items: center;
            gap: 12px;
            min-width: 350px;
            border-left: 4px solid #16a34a;
        }

        .alert i.fa-check-circle {
            font-size: 24px;
            color: #16a34a;
        }

        .alert-content {
            flex: 1;
        }

        .alert-content strong {
            color: #065f46;
            display: block;
            font-size: 14px;
            margin-bottom: 2px;
        }

        .alert-close {
            background: none;
            border: none;
            color: #64748b;
            cursor: pointer;
            padding: 4px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 6px;
            transition: all 0.2s ease;
        }

        .alert-close:hover {
            background: #f1f5f9;
            color: #1e293b;
        }

        /* Header */
        .page-header {
            margin-bottom: 24px;
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            flex-wrap: wrap;
            gap: 16px;
        }

        .header-title h1 {
            font-size: 28px;
            font-weight: 800;
            color: var(--text-dark);
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .header-subtitle {
            display: flex;
            align-items: center;
            gap: 6px;
            color: var(--text-light);
            font-size: 14px;
            font-weight: 500;
        }

        .header-actions {
            display: flex;
            gap: 12px;
            align-items: center;
        }

        /* Buttons */
        .btn {
            padding: 11px 20px;
            border-radius: 10px;
            font-weight: 700;
            font-size: 14px;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            cursor: pointer;
            border: none;
            transition: all 0.3s ease;
            text-decoration: none;
            white-space: nowrap;
        }

        .btn-primary {
            background: var(--purple);
            color: white;
        }

        .btn-primary:hover {
            background: #4f46e5;
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(99, 102, 241, 0.4);
        }

        .btn-success {
            background: #16a34a;
            color: white;
        }

        .btn-success:hover {
            background: #15803d;
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(22, 163, 74, 0.4);
        }

        .btn-outline {
            background: white;
            color: var(--text-dark);
            border: 2px solid var(--border-color);
        }

        .btn-outline:hover {
            background: var(--bg-light);
            border-color: var(--primary-teal);
        }

        /* Export Dropdown Menu */
        .dropdown {
            position: relative;
        }

        .dropdown .dropdown-menu {
            position: absolute;
            right: 0;
            top: calc(100% + 8px);
            background: white;
            border: 1px solid var(--border-color);
            border-radius: 12px;
            box-shadow: 0 8px 24px rgba(0,0,0,0.12);
            min-width: 200px;
            z-index: 1000;
            display: none;
            overflow: hidden;
        }

        .dropdown .dropdown-menu.show {
            display: block;
        }

        .dropdown .dropdown-menu .dropdown-item {
            padding: 12px 16px;
            font-size: 14px;
            color: var(--text-dark);
            cursor: pointer;
            transition: background 0.2s ease;
            display: flex;
            align-items: center;
            gap: 10px;
            border: none;
            background: none;
            width: 100%;
            text-align: left;
            font-weight: 600;
        }

        .dropdown .dropdown-menu .dropdown-item:hover {
            background: var(--bg-light);
        }

        .dropdown .dropdown-menu .dropdown-item i {
            width: 20px;
            text-align: center;
            color: var(--primary-teal);
        }

        /* Stats Cards */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
            gap: 20px;
            margin-bottom: 24px;
        }

        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 16px;
            border: 1px solid var(--border-color);
            display: flex;
            align-items: center;
            gap: 16px;
            transition: all 0.3s ease;
        }

        .stat-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 8px 24px rgba(0,0,0,0.08);
        }

        .stat-icon {
            width: 56px;
            height: 56px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            flex-shrink: 0;
        }

        .stat-content {
            flex: 1;
        }

        .stat-label {
            font-size: 12px;
            color: var(--text-light);
            font-weight: 600;
            text-transform: uppercase;
            margin-bottom: 4px;
            letter-spacing: 0.5px;
        }

        .stat-value {
            font-size: 24px;
            font-weight: 800;
            color: var(--text-dark);
        }

        /* Chart Section */
        .charts-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20px;
            margin-bottom: 24px;
        }

        .chart-card {
            background: white;
            border-radius: 16px;
            border: 1px solid var(--border-color);
            padding: 24px;
        }

        .chart-title {
            font-size: 14px;
            font-weight: 700;
            color: var(--text-light);
            margin-bottom: 16px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .chart-container {
            position: relative;
            height: 250px;
        }

        /* Main Card */
        .main-card {
            background: white;
            border-radius: 16px;
            border: 1px solid var(--border-color);
            overflow: hidden;
        }

        .card-header {
            padding: 20px 24px;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 16px;
        }

        .search-filter-bar {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
            flex: 1;
        }

        .search-box {
            position: relative;
            flex: 1;
            min-width: 280px;
            max-width: 400px;
        }

        .search-box input {
            width: 100%;
            padding: 10px 16px 10px 42px;
            border: 2px solid var(--border-color);
            border-radius: 10px;
            font-size: 14px;
            outline: none;
            transition: all 0.3s ease;
        }

        .search-box input:focus {
            border-color: var(--purple);
            box-shadow: 0 0 0 4px rgba(99, 102, 241, 0.1);
        }

        .search-box i {
            position: absolute;
            left: 14px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--text-light);
        }

        .filter-group {
            display: flex;
            gap: 8px;
        }

        .filter-select {
            padding: 10px 14px;
            border: 2px solid var(--border-color);
            border-radius: 10px;
            font-size: 14px;
            outline: none;
            transition: all 0.3s ease;
            background: white;
            cursor: pointer;
            min-width: 140px;
        }

        .filter-select:focus {
            border-color: var(--purple);
            box-shadow: 0 0 0 4px rgba(99, 102, 241, 0.1);
        }

        .icon-btn {
            width: 42px;
            height: 42px;
            border-radius: 10px;
            border: 2px solid var(--border-color);
            background: white;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s ease;
            color: var(--text-medium);
        }

        .icon-btn:hover {
            background: var(--bg-light);
            border-color: var(--primary-teal);
            color: var(--primary-teal);
        }

        /* Table */
        .table-container {
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        thead th {
            background: var(--bg-light);
            padding: 14px 16px;
            text-align: left;
            font-size: 11px;
            font-weight: 700;
            color: var(--text-light);
            text-transform: uppercase;
            letter-spacing: 0.5px;
            border-bottom: 2px solid var(--border-color);
            white-space: nowrap;
        }

        tbody td {
            padding: 16px;
            border-bottom: 1px solid var(--border-color);
            font-size: 14px;
        }

        tbody tr {
            transition: background 0.2s ease;
        }

        tbody tr:hover {
            background: var(--bg-light);
        }

        .checkbox-cell {
            width: 40px;
        }

        .checkbox {
            width: 18px;
            height: 18px;
            border: 2px solid var(--border-color);
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .checkbox:checked {
            background: var(--purple);
            border-color: var(--purple);
        }

        .id-badge {
            background: var(--lightest-mint);
            color: var(--primary-teal);
            padding: 4px 10px;
            border-radius: 6px;
            font-size: 12px;
            font-weight: 700;
            display: inline-block;
        }

        .user-cell {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .avatar {
            width: 36px;
            height: 36px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 13px;
            font-weight: 700;
            color: white;
            flex-shrink: 0;
        }

        .user-info {
            flex: 1;
            min-width: 0;
        }

        .user-name {
            font-weight: 600;
            color: var(--text-dark);
            margin-bottom: 2px;
        }

        .user-email {
            font-size: 12px;
            color: var(--text-light);
        }

        .badge {
            padding: 6px 12px;
            border-radius: 8px;
            font-size: 12px;
            font-weight: 700;
            display: inline-block;
            text-transform: capitalize;
        }

        .badge-success {
            background: #d1fae5;
            color: #065f46;
        }

        .badge-danger {
            background: #fee2e2;
            color: #991b1b;
        }

        .badge-blue {
            background: #dbeafe;
            color: #1e40af;
        }

        .badge-purple {
            background: #e9d5ff;
            color: #6b21a8;
        }

        .actions-cell {
            display: flex;
            gap: 8px;
            align-items: center;
        }

        .action-btn {
            width: 32px;
            height: 32px;
            border-radius: 8px;
            border: none;
            background: var(--bg-light);
            color: var(--text-medium);
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .action-btn:hover:not(:disabled) {
            background: var(--primary-teal);
            color: white;
        }

        .action-btn:disabled {
            opacity: 0.3;
            cursor: not-allowed;
        }

        /* Pagination */
        .card-footer {
            padding: 16px 24px;
            border-top: 1px solid var(--border-color);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .pagination-info {
            font-size: 13px;
            color: var(--text-light);
        }

        .pagination {
            display: flex;
            gap: 6px;
            align-items: center;
        }

        .pagination a,
        .pagination span {
            min-width: 36px;
            height: 36px;
            padding: 0 12px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 13px;
            font-weight: 600;
            text-decoration: none;
            transition: all 0.2s ease;
        }

        .pagination a {
            background: white;
            color: var(--text-dark);
            border: 2px solid var(--border-color);
        }

        .pagination a:hover {
            background: var(--purple);
            color: white;
            border-color: var(--purple);
        }

        .pagination .active {
            background: var(--purple);
            color: white;
            border: 2px solid var(--purple);
        }

        .pagination .disabled {
            opacity: 0.5;
            pointer-events: none;
        }

        /* Table Action Dropdown Menu */
        .dropdown.active .dropdown-menu {
            display: block;
        }

        /* Responsive */
        @media (max-width: 768px) {
            .alert-container {
                top: 10px;
                right: 10px;
                left: 10px;
            }
            
            .alert {
                min-width: auto;
            }

            .charts-grid {
                grid-template-columns: 1fr;
            }

            body { padding: 12px; }
            
            .page-header {
                flex-direction: column;
                align-items: stretch;
            }

            .header-actions {
                width: 100%;
                justify-content: stretch;
                flex-wrap: wrap;
            }

            .header-actions .btn,
            .header-actions .dropdown {
                flex: 1;
                min-width: 140px;
            }

            .stats-grid {
                grid-template-columns: 1fr;
            }

            .search-filter-bar {
                flex-direction: column;
            }

            .search-box {
                max-width: 100%;
            }

            .filter-group {
                width: 100%;
            }

            .filter-select {
                flex: 1;
            }
        }
    </style>
</head>
<body>
    <!-- Success Alert -->
    <?php if ($successMessage): ?>
    <div class="alert-container" id="successAlert">
        <div class="alert">
            <i class="fas fa-check-circle"></i>
            <div class="alert-content">
                <strong>Berhasil!</strong> <?= htmlspecialchars($successMessage) ?>
            </div>
            <button class="alert-close" onclick="closeAlert()">
                <i class="fas fa-times"></i>
            </button>
        </div>
    </div>
    <?php endif; ?>

    <div class="container">
        <!-- Page Header -->
        <div class="page-header">
            <div class="header-title">
                <h1>
                    <i class="fas fa-users" style="color: var(--purple);"></i>
                    Data SDM
                </h1>
                <div class="header-subtitle">
                    <i class="fas fa-database"></i>
                    <span>Total: <?= number_format($stats['total_sdm']) ?> SDM</span>
                </div>
            </div>
            <div class="header-actions">
                <div class="dropdown">
                    <button class="btn btn-outline" onclick="toggleExportMenu(event)">
                        <i class="fas fa-download"></i>
                        Export
                        <i class="fas fa-chevron-down" style="font-size: 10px;"></i>
                    </button>
                    <div class="dropdown-menu" id="exportMenu">
                        <div class="dropdown-item" onclick="exportToExcelComplete()">
                            <i class="fas fa-file-excel"></i>
                            Export to Excel
                        </div>
                        <div class="dropdown-item" onclick="window.print()">
                            <i class="fas fa-print"></i>
                            Print / PDF
                        </div>
                    </div>
                </div>
                <a href="import_sdm.php" class="btn btn-success">
                    <i class="fas fa-file-import"></i>
                    Import Excel
                </a>
                <a href="add_sdm.php" class="btn btn-primary">
                    <i class="fas fa-plus"></i>
                    Tambah SDM
                </a>
            </div>
        </div>

        <!-- Statistics Cards -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon" style="background: #dbeafe; color: #1e40af;">
                    <i class="fas fa-users"></i>
                </div>
                <div class="stat-content">
                    <div class="stat-label">Total SDM</div>
                    <div class="stat-value"><?= number_format($stats['total_sdm']) ?></div>
                </div>
            </div>

            <div class="stat-card">
                <div class="stat-icon" style="background: #d1fae5; color: #065f46;">
                    <i class="fas fa-user-check"></i>
                </div>
                <div class="stat-content">
                    <div class="stat-label">SDM Aktif</div>
                    <div class="stat-value"><?= number_format($stats['aktif']) ?></div>
                </div>
            </div>

            <div class="stat-card">
                <div class="stat-icon" style="background: #dbeafe; color: #0284c7;">
                    <i class="fas fa-male"></i>
                </div>
                <div class="stat-content">
                    <div class="stat-label">Laki-laki</div>
                    <div class="stat-value"><?= number_format($stats['laki_laki']) ?></div>
                </div>
            </div>

            <div class="stat-card">
                <div class="stat-icon" style="background: #fce7f3; color: #be185d;">
                    <i class="fas fa-female"></i>
                </div>
                <div class="stat-content">
                    <div class="stat-label">Perempuan</div>
                    <div class="stat-value"><?= number_format($stats['perempuan']) ?></div>
                </div>
            </div>
        </div>

        <!-- Charts Section -->
        <div class="charts-grid">
            <!-- Distribution by Office -->
            <div class="chart-card">
                <div class="chart-title">Distribusi SDM per Kantor</div>
                <div class="chart-container">
                    <canvas id="kantorChart"></canvas>
                </div>
            </div>

            <!-- Distribution by Position -->
            <div class="chart-card">
                <div class="chart-title">Distribusi SDM per Jabatan</div>
                <div class="chart-container">
                    <canvas id="jabatanChart"></canvas>
                </div>
            </div>
        </div>

        <!-- Main Table Card -->
        <div class="main-card">
            <!-- Card Header with Search & Filters -->
            <div class="card-header">
                <div class="search-filter-bar">
                    <div class="search-box">
                        <i class="fas fa-search"></i>
                        <input type="text" 
                               id="searchInput" 
                               placeholder="Cari nama, NIP, atau email..." 
                               value="<?= htmlspecialchars($search) ?>"
                               onkeypress="if(event.key==='Enter') doSearch()">
                    </div>

                    <div class="filter-group">
                        <select class="filter-select" id="filterKantor" onchange="applyFilter()">
                            <option value="">Semua Kantor</option>
                            <?php foreach($kantorList as $k): ?>
                            <option value="<?= htmlspecialchars($k) ?>" <?= $filter_kantor === $k ? 'selected' : '' ?>>
                                <?= htmlspecialchars($k) ?>
                            </option>
                            <?php endforeach; ?>
                        </select>

                        <select class="filter-select" id="filterJabatan" onchange="applyFilter()">
                            <option value="">Semua Jabatan</option>
                            <?php foreach($jabatanList as $j): ?>
                            <option value="<?= htmlspecialchars($j) ?>" <?= $filter_jabatan === $j ? 'selected' : '' ?>>
                                <?= htmlspecialchars($j) ?>
                            </option>
                            <?php endforeach; ?>
                        </select>

                        <select class="filter-select" id="filterStatus" onchange="applyFilter()">
                            <option value="">Semua Status</option>
                            <option value="Aktif" <?= $filter_status === 'Aktif' ? 'selected' : '' ?>>Aktif</option>
                            <option value="Non-Aktif" <?= $filter_status === 'Non-Aktif' ? 'selected' : '' ?>>Non-Aktif</option>
                        </select>
                    </div>
                </div>

                <div class="filter-group">
                    <button class="icon-btn" title="Refresh" onclick="location.reload()">
                        <i class="fas fa-sync-alt"></i>
                    </button>
                </div>
            </div>

            <!-- Table -->
            <div class="table-container">
                <table>
                    <thead>
                        <tr>
                            <th class="checkbox-cell">
                                <input type="checkbox" class="checkbox" id="selectAll">
                            </th>
                            <th>ID</th>
                            <th>NAMA SDM</th>
                            <th>JENIS KELAMIN</th>
                            <th>JABATAN</th>
                            <th>KANTOR</th>
                            <th>NO. HP</th>
                            <th>STATUS</th>
                            <th style="text-align: center;">ACTIONS</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        if (mysqli_num_rows($resultSdm) > 0):
                            while($row = mysqli_fetch_assoc($resultSdm)): 
                                $color = getRandomColor();
                        ?>
                        <tr>
                            <td class="checkbox-cell">
                                <input type="checkbox" class="checkbox">
                            </td>
                            <td>
                                <span class="id-badge"><?= htmlspecialchars($row['nip'] ?? $row['id']) ?></span>
                            </td>
                            <td>
                                <div class="user-cell">
                                    <div class="avatar" style="background: <?= $color ?>;">
                                        <?= getInitials($row['nama']) ?>
                                    </div>
                                    <div class="user-info">
                                        <div class="user-name"><?= htmlspecialchars($row['nama']) ?></div>
                                        <div class="user-email"><?= htmlspecialchars($row['email'] ?? '-') ?></div>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <?php
                                $gender = $row['jenis_kelamin'] ?? '-';
                                $genderBadge = $gender === 'Laki-laki' ? 'badge-blue' : 'badge-purple';
                                ?>
                                <span class="badge <?= $genderBadge ?>">
                                    <?= htmlspecialchars($gender) ?>
                                </span>
                            </td>
                            <td><?= htmlspecialchars($row['jabatan'] ?? '-') ?></td>
                            <td>
                                <i class="fas fa-map-marker-alt" style="color: var(--primary-teal); margin-right: 4px;"></i>
                                <?= htmlspecialchars($row['kantor'] ?? '-') ?>
                            </td>
                            <td><?= htmlspecialchars($row['no_hp'] ?? '-') ?></td>
                            <td>
                                <?php
                                $status = $row['status'] ?? 'Aktif';
                                $statusBadge = $status === 'Aktif' ? 'badge-success' : 'badge-danger';
                                ?>
                                <span class="badge <?= $statusBadge ?>">
                                    <?= htmlspecialchars($status) ?>
                                </span>
                            </td>
                            <td>
                                <div class="actions-cell">
                                    <?php if (!empty($row['no_hp'])): ?>
                                    <button class="action-btn" title="Telepon <?= htmlspecialchars($row['no_hp']) ?>" onclick="window.open('tel:<?= htmlspecialchars($row['no_hp']) ?>', '_self')">
                                        <i class="fas fa-phone"></i>
                                    </button>
                                    <?php else: ?>
                                    <button class="action-btn" title="No telepon tidak tersedia" style="opacity: 0.3; cursor: not-allowed;" disabled>
                                        <i class="fas fa-phone"></i>
                                    </button>
                                    <?php endif; ?>
                                    
                                    <?php if (!empty($row['email'])): ?>
                                    <button class="action-btn" title="Email ke <?= htmlspecialchars($row['email']) ?>" onclick="window.open('mailto:<?= htmlspecialchars($row['email']) ?>', '_self')">
                                        <i class="fas fa-envelope"></i>
                                    </button>
                                    <?php else: ?>
                                    <button class="action-btn" title="Email tidak tersedia" style="opacity: 0.3; cursor: not-allowed;" disabled>
                                        <i class="fas fa-envelope"></i>
                                    </button>
                                    <?php endif; ?>
                                    
                                    <div class="dropdown">
                                        <button class="action-btn action-menu-btn" onclick="toggleDropdown(this)">
                                            <i class="fas fa-ellipsis-h"></i>
                                        </button>
                                        <div class="dropdown-menu">
                                            <a href="edit_sdm.php?id=<?= $row['id'] ?>" class="dropdown-item">
                                                <i class="fas fa-edit"></i>
                                                Edit
                                            </a>
                                            <a href="detail_sdm.php?id=<?= $row['id'] ?>" class="dropdown-item">
                                                <i class="fas fa-eye"></i>
                                                Detail
                                            </a>
                                            <div class="dropdown-item" style="color: #dc2626;" onclick="if(confirm('Hapus SDM ini?')) location.href='delete_sdm.php?id=<?= $row['id'] ?>'">
                                                <i class="fas fa-trash"></i>
                                                Delete
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </td>
                        </tr>
                        <?php 
                            endwhile;
                        else:
                        ?>
                        <tr>
                            <td colspan="9" style="text-align: center; padding: 40px; color: var(--text-light);">
                                <i class="fas fa-inbox" style="font-size: 48px; margin-bottom: 16px; opacity: 0.3;"></i>
                                <br>
                                <strong>Tidak ada data SDM</strong>
                                <br>
                                <small>Silakan tambahkan data SDM baru</small>
                            </td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <!-- Card Footer with Pagination -->
            <div class="card-footer">
                <div class="pagination-info">
                    Menampilkan <?= $offset + 1 ?> - <?= min($offset + $perPage, $totalRecords) ?> dari <?= number_format($totalRecords) ?> data
                </div>

                <?php if ($totalPages > 1): ?>
                <div class="pagination">
                    <a href="?page=<?= max(1, $page - 1) ?>&search=<?= urlencode($search) ?>&kantor=<?= urlencode($filter_kantor) ?>&jabatan=<?= urlencode($filter_jabatan) ?>&status=<?= urlencode($filter_status) ?>" class="<?= $page <= 1 ? 'disabled' : '' ?>">
                        <i class="fas fa-chevron-left"></i>
                    </a>

                    <?php
                    $start = max(1, $page - 2);
                    $end = min($totalPages, $page + 2);
                    
                    for ($i = $start; $i <= $end; $i++):
                    ?>
                        <?php if ($i == $page): ?>
                            <span class="active"><?= $i ?></span>
                        <?php else: ?>
                            <a href="?page=<?= $i ?>&search=<?= urlencode($search) ?>&kantor=<?= urlencode($filter_kantor) ?>&jabatan=<?= urlencode($filter_jabatan) ?>&status=<?= urlencode($filter_status) ?>">
                                <?= $i ?>
                            </a>
                        <?php endif; ?>
                    <?php endfor; ?>

                    <a href="?page=<?= min($totalPages, $page + 1) ?>&search=<?= urlencode($search) ?>&kantor=<?= urlencode($filter_kantor) ?>&jabatan=<?= urlencode($filter_jabatan) ?>&status=<?= urlencode($filter_status) ?>" class="<?= $page >= $totalPages ? 'disabled' : '' ?>">
                        <i class="fas fa-chevron-right"></i>
                    </a>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script>
        // Success Alert Functions
        function closeAlert() {
            const alert = document.getElementById('successAlert');
            if (alert) {
                alert.classList.add('closing');
                setTimeout(() => {
                    alert.remove();
                }, 300);
            }
        }

        // Auto close after 5 seconds
        setTimeout(() => {
            closeAlert();
        }, 5000);

        // Chart.js Global Config
        Chart.defaults.font.family = 'Inter';
        Chart.defaults.font.size = 12;
        Chart.defaults.color = '#64748b';

        // Distribution by Office Chart
        const kantorCtx = document.getElementById('kantorChart');
        new Chart(kantorCtx, {
            type: 'bar',
            data: {
                labels: [<?php echo implode(',', array_map(function($d) { return '"'.addslashes($d['kantor']).'"'; }, $dataKantor)); ?>],
                datasets: [{
                    label: 'Jumlah SDM',
                    data: [<?php echo implode(',', array_column($dataKantor, 'jumlah')); ?>],
                    backgroundColor: '#8b5cf6',
                    borderRadius: 8,
                    barThickness: 40,
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { display: false }
                },
                scales: {
                    y: { 
                        beginAtZero: true,
                        grid: { display: true, color: '#f1f5f9' }
                    },
                    x: { 
                        grid: { display: false },
                        ticks: { maxRotation: 45, minRotation: 0 }
                    }
                }
            }
        });

        // Distribution by Position Chart
        const jabatanCtx = document.getElementById('jabatanChart');
        new Chart(jabatanCtx, {
            type: 'bar',
            data: {
                labels: [<?php echo implode(',', array_map(function($d) { return '"'.addslashes($d['jabatan']).'"'; }, $dataJabatan)); ?>],
                datasets: [{
                    label: 'Jumlah SDM',
                    data: [<?php echo implode(',', array_column($dataJabatan, 'jumlah')); ?>],
                    backgroundColor: '#7AB2B2',
                    borderRadius: 8,
                    barThickness: 40,
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { display: false }
                },
                scales: {
                    y: { 
                        beginAtZero: true,
                        grid: { display: true, color: '#f1f5f9' }
                    },
                    x: { 
                        grid: { display: false },
                        ticks: { maxRotation: 45, minRotation: 0 }
                    }
                }
            }
        });

        // Search Function
        function doSearch() {
            const searchValue = document.getElementById('searchInput').value;
            const currentUrl = new URL(window.location.href);
            currentUrl.searchParams.set('search', searchValue);
            currentUrl.searchParams.set('page', '1');
            window.location.href = currentUrl.toString();
        }

        // Filter Function
        function applyFilter() {
            const kantor = document.getElementById('filterKantor').value;
            const jabatan = document.getElementById('filterJabatan').value;
            const status = document.getElementById('filterStatus').value;
            const search = document.getElementById('searchInput').value;
            
            const params = new URLSearchParams();
            if (search) params.append('search', search);
            if (kantor) params.append('kantor', kantor);
            if (jabatan) params.append('jabatan', jabatan);
            if (status) params.append('status', status);
            params.append('page', '1');
            
            window.location.href = '?' + params.toString();
        }

        // Select All Checkbox
        document.getElementById('selectAll')?.addEventListener('change', function() {
            const checkboxes = document.querySelectorAll('tbody .checkbox');
            checkboxes.forEach(cb => cb.checked = this.checked);
        });

        // Table Action Dropdown Toggle
        function toggleDropdown(btn) {
            const dropdown = btn.closest('.dropdown');
            const allDropdowns = document.querySelectorAll('.actions-cell .dropdown');
            
            allDropdowns.forEach(d => {
                if (d !== dropdown) d.classList.remove('active');
            });
            
            dropdown.classList.toggle('active');
        }

        // Export Menu Toggle
        function toggleExportMenu(event) {
            event.stopPropagation();
            const menu = document.getElementById('exportMenu');
            menu.classList.toggle('show');
        }

        // Close dropdowns when clicking outside
        document.addEventListener('click', function(e) {
            // Close export menu
            const exportMenu = document.getElementById('exportMenu');
            if (exportMenu && !e.target.closest('.header-actions .dropdown')) {
                exportMenu.classList.remove('show');
            }
            
            // Close table action dropdowns
            if (!e.target.closest('.actions-cell .dropdown')) {
                document.querySelectorAll('.actions-cell .dropdown').forEach(d => d.classList.remove('active'));
            }
        });

        // Real-time search with debounce
        let searchTimeout;
        document.getElementById('searchInput')?.addEventListener('input', function() {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
                doSearch();
            }, 800);
        });

        // Export to Excel - Complete Data via AJAX (IMPROVED VERSION)
        function exportToExcelComplete() {
            // Show loading state
            const exportMenu = document.getElementById('exportMenu');
            const btn = event.target;
            const originalHTML = btn.innerHTML;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Exporting...';
            btn.style.pointerEvents = 'none';
            
            // Fetch complete data from server
            fetch('export_sdm_data.php')
                .then(response => {
                    console.log('Response status:', response.status);
                    console.log('Response ok:', response.ok);
                    
                    // Check if response is ok
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    
                    // Get response as text first to debug
                    return response.text();
                })
                .then(text => {
                    console.log('Raw response:', text);
                    
                    // Try to parse JSON
                    let data;
                    try {
                        data = JSON.parse(text);
                    } catch (e) {
                        console.error('JSON parse error:', e);
                        throw new Error('Response bukan JSON yang valid. Response: ' + text.substring(0, 200));
                    }
                    
                    console.log('Parsed data:', data);
                    
                    // Check if request was successful
                    if (data.success && data.data) {
                        const wb = XLSX.utils.book_new();
                        
                        // Prepare data array
                        const exportData = [
                            ['NIP', 'Nama', 'Jenis Kelamin', 'Tempat Lahir', 'Tanggal Lahir', 
                             'Alamat', 'No HP', 'Email', 'Jabatan', 'Kantor', 
                             'Tanggal Masuk', 'Status', 'Pendidikan', 'Jurusan']
                        ];
                        
                        data.data.forEach(row => {
                            exportData.push([
                                row.nip || '',
                                row.nama || '',
                                row.jenis_kelamin || '',
                                row.tempat_lahir || '',
                                row.tanggal_lahir || '',
                                row.alamat || '',
                                row.no_hp || '',
                                row.email || '',
                                row.jabatan || '',
                                row.kantor || '',
                                row.tanggal_masuk || '',
                                row.status || '',
                                row.pendidikan || '',
                                row.jurusan || ''
                            ]);
                        });
                        
                        const ws = XLSX.utils.aoa_to_sheet(exportData);
                        ws['!cols'] = [
                            { wch: 15 }, { wch: 25 }, { wch: 15 }, { wch: 20 }, { wch: 15 },
                            { wch: 30 }, { wch: 15 }, { wch: 25 }, { wch: 20 }, { wch: 20 },
                            { wch: 15 }, { wch: 12 }, { wch: 15 }, { wch: 20 }
                        ];
                        
                        XLSX.utils.book_append_sheet(wb, ws, 'Data SDM');
                        
                        const date = new Date();
                        const filename = `Data_SDM_${date.getFullYear()}${String(date.getMonth()+1).padStart(2,'0')}${String(date.getDate()).padStart(2,'0')}.xlsx`;
                        
                        XLSX.writeFile(wb, filename);
                        
                        alert(`Export berhasil! ${data.total} data telah di-export.`);
                    } else {
                        throw new Error(data.message || 'Gagal mengambil data dari server');
                    }
                })
                .catch(error => {
                    console.error('Export error:', error);
                    alert('Terjadi kesalahan saat export data:\n' + error.message);
                })
                .finally(() => {
                    btn.innerHTML = originalHTML;
                    btn.style.pointerEvents = '';
                    if (exportMenu) {
                        exportMenu.classList.remove('show');
                    }
                });
        }
    </script>
</body>
</html>
<?php
mysqli_close($conn);
?>