<?php
session_start();
require_once __DIR__ . '/../../DataBase/koneksi.php';

/* =========================
   VALIDASI ADMIN
========================= */
if (!isset($_SESSION['login']) || $_SESSION['role'] !== 'A') {
    header("Location: ../../index.html");
    exit;
}

/* =========================
   AJAX HANDLER
========================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json');

    try {
        $action = $_POST['action'];

        if ($action === 'create') {
            $sql = "INSERT INTO kantor 
                    (kode_kantor, nama_kantor, alamat, telepon, status, created_at)
                    VALUES (?, ?, ?, ?, 'active', NOW())";

            $stmt = $conn->prepare($sql);
            $stmt->bind_param("ssss", 
                $_POST['kode_kantor'],
                $_POST['nama_kantor'],
                $_POST['alamat'],
                $_POST['telepon']
            );
            $stmt->execute();
            $stmt->close();

            echo json_encode(['success' => true, 'message' => 'Kantor berhasil ditambahkan']);
        }

        elseif ($action === 'update') {
            $sql = "UPDATE kantor SET 
                        kode_kantor = ?, 
                        nama_kantor = ?, 
                        alamat = ?, 
                        telepon = ?, 
                        status = ?
                    WHERE id = ?";

            $stmt = $conn->prepare($sql);
            $stmt->bind_param("sssssi", 
                $_POST['kode_kantor'],
                $_POST['nama_kantor'],
                $_POST['alamat'],
                $_POST['telepon'],
                $_POST['status'],
                $_POST['id']
            );
            $stmt->execute();
            $stmt->close();

            echo json_encode(['success' => true, 'message' => 'Data kantor berhasil diupdate']);
        }

        elseif ($action === 'delete') {
            $stmt = $conn->prepare("DELETE FROM kantor WHERE id = ?");
            $stmt->bind_param("i", $_POST['id']);
            $stmt->execute();
            $stmt->close();

            echo json_encode(['success' => true, 'message' => 'Kantor berhasil dihapus']);
        }

        elseif ($action === 'toggle_status') {
            $stmt = $conn->prepare("
                UPDATE kantor 
                SET status = IF(status='active','inactive','active') 
                WHERE id = ?
            ");
            $stmt->bind_param("i", $_POST['id']);
            $stmt->execute();
            $stmt->close();

            echo json_encode(['success' => true, 'message' => 'Status kantor diperbarui']);
        }

    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Terjadi kesalahan: ' . $e->getMessage()]);
    }
    exit;
}

/* =========================
   AMBIL DATA KANTOR
========================= */
$result = $conn->query("SELECT * FROM kantor ORDER BY created_at DESC");
$kantors = [];
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $kantors[] = $row;
    }
    $result->free();
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kelola Kantor - 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">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: #f8fafc;
            padding: 25px;
            color: #1e293b;
        }

        /* HEADER */
        .header {
            background: linear-gradient(135deg, #7AB2B2 0%, #4D869C 100%);
            color: white;
            padding: 40px;
            border-radius: 20px;
            margin-bottom: 30px;
            box-shadow: 0 8px 25px rgba(122, 178, 178, 0.25);
        }

        .header h1 {
            font-size: 32px;
            font-weight: 800;
            margin-bottom: 8px;
        }

        .header p {
            font-size: 16px;
            opacity: 0.95;
        }

        /* CARD */
        .card {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            margin-bottom: 30px;
        }

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
            padding-bottom: 20px;
            border-bottom: 2px solid #f1f5f9;
        }

        .card-title {
            font-size: 20px;
            font-weight: 700;
            color: #1e293b;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .card-title i {
            color: #7AB2B2;
            font-size: 24px;
        }

        /* BUTTON */
        .btn {
            padding: 12px 24px;
            border-radius: 10px;
            border: none;
            cursor: pointer;
            font-weight: 600;
            font-size: 14px;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            font-family: 'Inter', sans-serif;
        }

        .btn-add {
            background: linear-gradient(135deg, #7AB2B2 0%, #4D869C 100%);
            color: white;
            box-shadow: 0 4px 15px rgba(122, 178, 178, 0.3);
        }

        .btn-add:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(122, 178, 178, 0.4);
        }

        /* TABLE */
        .table-container {
            overflow-x: auto;
            border-radius: 10px;
        }

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

        table thead {
            background: linear-gradient(135deg, #7AB2B2 0%, #4D869C 100%);
        }

        table th {
            color: white;
            padding: 16px;
            text-align: left;
            font-weight: 600;
            font-size: 14px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        table th:first-child {
            border-radius: 10px 0 0 0;
        }

        table th:last-child {
            border-radius: 0 10px 0 0;
        }

        table td {
            padding: 16px;
            border-bottom: 1px solid #f1f5f9;
            font-size: 14px;
            color: #334155;
        }

        table tbody tr {
            transition: all 0.3s ease;
        }

        table tbody tr:hover {
            background: #f8fafc;
        }

        table tbody tr:last-child td {
            border-bottom: none;
        }

        .status-badge {
            padding: 6px 14px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            display: inline-block;
        }

        .status-active {
            background: rgba(16, 185, 129, 0.1);
            color: #10b981;
        }

        .status-inactive {
            background: rgba(239, 68, 68, 0.1);
            color: #ef4444;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #94a3b8;
        }

        .empty-state i {
            font-size: 64px;
            margin-bottom: 20px;
            opacity: 0.3;
        }

        .empty-state p {
            font-size: 16px;
            font-weight: 500;
        }

        /* DROPDOWN */
        .dropdown {
            position: relative;
            display: inline-block;
        }

        .dropdown-toggle {
            background: #7AB2B2;
            color: white;
            width: 36px;
            height: 36px;
            border-radius: 8px;
            border: none;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
        }

        .dropdown-toggle:hover {
            background: #4D869C;
            transform: scale(1.05);
        }

        .dropdown-menu {
            position: absolute;
            right: 0;
            top: 100%;
            margin-top: 8px;
            background: white;
            border-radius: 10px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.15);
            min-width: 180px;
            opacity: 0;
            visibility: hidden;
            transform: translateY(-10px);
            transition: all 0.3s ease;
            z-index: 1000;
        }

        .dropdown.active .dropdown-menu {
            opacity: 1;
            visibility: visible;
            transform: translateY(0);
        }

        .dropdown-item {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 12px 16px;
            color: #334155;
            text-decoration: none;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.2s ease;
            cursor: pointer;
            border: none;
            background: none;
            width: 100%;
            text-align: left;
        }

        .dropdown-item:first-child {
            border-radius: 10px 10px 0 0;
        }

        .dropdown-item:last-child {
            border-radius: 0 0 10px 10px;
        }

        .dropdown-item i {
            width: 18px;
            font-size: 14px;
        }

        .dropdown-item:hover {
            background: #f8fafc;
        }

        .dropdown-item.detail:hover {
            background: rgba(122, 178, 178, 0.1);
            color: #7AB2B2;
        }

        .dropdown-item.edit:hover {
            background: rgba(59, 130, 246, 0.1);
            color: #3b82f6;
        }

        .dropdown-item.toggle:hover {
            background: rgba(245, 158, 11, 0.1);
            color: #f59e0b;
        }

        .dropdown-item.delete:hover {
            background: rgba(239, 68, 68, 0.1);
            color: #ef4444;
        }

        .dropdown-divider {
            height: 1px;
            background: #f1f5f9;
            margin: 4px 0;
        }

        /* MODAL */
        .modal {
            display: none;
            position: fixed;
            z-index: 10000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
            animation: fadeIn 0.3s ease;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        .modal-wrapper {
            width: 100%;
            height: 100%;
            overflow-y: auto;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .modal-content {
            background-color: #fff;
            margin: auto;
            padding: 0;
            border-radius: 20px;
            width: 90%;
            max-width: 600px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            animation: slideDown 0.3s ease;
            display: flex;
            flex-direction: column;
        }

        .modal-content.large {
            max-width: 900px;
        }

        @keyframes slideDown {
            from {
                transform: translateY(-50px);
                opacity: 0;
            }
            to {
                transform: translateY(0);
                opacity: 1;
            }
        }

        .modal-header {
            background: linear-gradient(135deg, #7AB2B2 0%, #4D869C 100%);
            color: white;
            padding: 25px 30px;
            border-radius: 20px 20px 0 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-shrink: 0;
        }

        .modal-header h2 {
            font-size: 22px;
            font-weight: 700;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .close {
            color: white;
            font-size: 32px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            width: 35px;
            height: 35px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            flex-shrink: 0;
        }

        .close:hover {
            background: rgba(255,255,255,0.2);
            transform: rotate(90deg);
        }

        .modal-body {
            padding: 30px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #1e293b;
            font-weight: 600;
            font-size: 14px;
        }

        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e2e8f0;
            border-radius: 10px;
            font-size: 14px;
            font-family: 'Inter', sans-serif;
            transition: all 0.3s ease;
        }

        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #7AB2B2;
            box-shadow: 0 0 0 3px rgba(122, 178, 178, 0.1);
        }

        .form-group textarea {
            resize: vertical;
            min-height: 60px;
        }

        .form-actions {
            margin-top: 30px;
            display: flex;
            gap: 12px;
            justify-content: flex-end;
        }

        .btn-submit {
            background: linear-gradient(135deg, #7AB2B2 0%, #4D869C 100%);
            color: white;
            padding: 12px 32px;
        }

        .btn-submit:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(122, 178, 178, 0.4);
        }

        .btn-cancel {
            background: #64748b;
            color: white;
            padding: 12px 32px;
        }

        .btn-cancel:hover {
            background: #475569;
        }

        /* DETAIL MODAL */
        .detail-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20px;
            margin-bottom: 25px;
        }

        .detail-item {
            background: #f8fafc;
            padding: 15px;
            border-radius: 10px;
            border-left: 4px solid #7AB2B2;
        }

        .detail-label {
            font-size: 12px;
            color: #64748b;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            margin-bottom: 6px;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .detail-label i {
            font-size: 14px;
            color: #7AB2B2;
        }

        .detail-value {
            font-size: 15px;
            color: #1e293b;
            font-weight: 600;
        }

        .detail-full {
            grid-column: 1 / -1;
        }

        .map-container {
            width: 100%;
            height: 350px;
            border-radius: 10px;
            overflow: hidden;
            border: 2px solid #e2e8f0;
            margin-bottom: 15px;
        }

        .map-container iframe {
            width: 100%;
            height: 100%;
            border: none;
        }

        .map-info {
            background: #f8fafc;
            padding: 12px 16px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 13px;
            color: #64748b;
        }

        .map-info i {
            color: #7AB2B2;
            font-size: 16px;
        }

        /* RESPONSIVE */
        @media (max-width: 768px) {
            body {
                padding: 15px;
            }

            .header {
                padding: 25px;
            }

            .header h1 {
                font-size: 24px;
            }

            .card {
                padding: 20px;
            }

            .card-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 15px;
            }

            table th,
            table td {
                padding: 12px 8px;
                font-size: 13px;
            }

            .modal-wrapper {
                padding: 10px;
            }

            .modal-content {
                width: 95%;
            }

            .modal-content.large {
                max-width: 95%;
            }

            .modal-body {
                padding: 20px;
            }

            .form-actions {
                flex-direction: column;
            }

            .form-actions .btn {
                width: 100%;
            }

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

            .map-container {
                height: 250px;
            }
        }
    </style>
</head>
<body>

    <!-- HEADER -->
    <div class="header">
        <h1><i class="fas fa-building"></i> Kelola Kantor</h1>
        <p>Manajemen Data Kantor dan Lokasi ACF EDU HUB</p>
    </div>

    <!-- CARD CONTENT -->
    <div class="card">
        <div class="card-header">
            <div class="card-title">
                <i class="fas fa-list"></i>
                Daftar Kantor
            </div>
            <button class="btn btn-add" onclick="openModal('add')">
                <i class="fas fa-plus"></i>
                Tambah Kantor
            </button>
        </div>

        <div class="table-container">
            <table>
                <thead>
                    <tr>
                        <th style="width: 60px;">No</th>
                        <th>Kode</th>
                        <th>Nama Kantor</th>
                        <th>Alamat</th>
                        <th>Telepon</th>
                        <th style="width: 100px;">Status</th>
                        <th style="width: 80px; text-align: center;">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($kantors)): ?>
                        <tr>
                            <td colspan="7">
                                <div class="empty-state">
                                    <i class="fas fa-inbox"></i>
                                    <p>Belum ada data kantor</p>
                                </div>
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($kantors as $index => $kantor): ?>
                        <tr>
                            <td><strong><?= $index + 1 ?></strong></td>
                            <td><strong><?= htmlspecialchars($kantor['kode_kantor'] ?? '') ?></strong></td>
                            <td><?= htmlspecialchars($kantor['nama_kantor'] ?? '') ?></td>
                            <td><?= htmlspecialchars($kantor['alamat'] ?? '-') ?></td>
                            <td><?= htmlspecialchars($kantor['telepon'] ?? '-') ?></td>
                            <td>
                                <span class="status-badge status-<?= $kantor['status'] ?>">
                                    <i class="fas fa-circle" style="font-size: 8px;"></i>
                                    <?= $kantor['status'] === 'active' ? 'Aktif' : 'Nonaktif' ?>
                                </span>
                            </td>
                            <td style="text-align: center;">
                                <div class="dropdown" id="dropdown-<?= $kantor['id'] ?>">
                                    <button class="dropdown-toggle" onclick="toggleDropdown(<?= $kantor['id'] ?>)" aria-label="Actions">
                                        <i class="fas fa-ellipsis-vertical"></i>
                                    </button>
                                    <div class="dropdown-menu">
                                        <button class="dropdown-item detail" onclick="viewDetail(<?= htmlspecialchars(json_encode($kantor)) ?>)">
                                            <i class="fas fa-eye"></i>
                                            Lihat Detail
                                        </button>
                                        <button class="dropdown-item edit" onclick="editKantor(<?= htmlspecialchars(json_encode($kantor)) ?>)">
                                            <i class="fas fa-edit"></i>
                                            Edit
                                        </button>
                                        <button class="dropdown-item toggle" onclick="toggleStatus(<?= $kantor['id'] ?>)">
                                            <i class="fas fa-toggle-on"></i>
                                            Toggle Status
                                        </button>
                                        <div class="dropdown-divider"></div>
                                        <button class="dropdown-item delete" onclick="deleteKantor(<?= $kantor['id'] ?>)">
                                            <i class="fas fa-trash"></i>
                                            Hapus
                                        </button>
                                    </div>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- MODAL FORM -->
    <div id="formModal" class="modal">
        <div class="modal-wrapper">
            <div class="modal-content">
                <div class="modal-header">
                    <h2 id="modalTitle">
                        <i class="fas fa-plus-circle"></i>
                        Tambah Kantor
                    </h2>
                    <span class="close" onclick="closeModal()">&times;</span>
                </div>
                <div class="modal-body">
                    <form id="kantorForm">
                        <input type="hidden" id="formAction" name="action" value="create">
                        <input type="hidden" id="kantorId" name="id">

                        <div class="form-group">
                            <label for="kode_kantor">
                                <i class="fas fa-barcode"></i> Kode Kantor *
                            </label>
                            <input type="text" id="kode_kantor" name="kode_kantor" placeholder="Contoh: PUSAT, SDJ-MDN" required>
                        </div>

                        <div class="form-group">
                            <label for="nama_kantor">
                                <i class="fas fa-building"></i> Nama Kantor *
                            </label>
                            <input type="text" id="nama_kantor" name="nama_kantor" placeholder="Contoh: Kantor Pusat Jakarta" required>
                        </div>

                        <div class="form-group">
                            <label for="alamat">
                                <i class="fas fa-map-marker-alt"></i> Alamat
                            </label>
                            <textarea id="alamat" name="alamat" placeholder="Masukkan alamat lengkap kantor" rows="2"></textarea>
                        </div>

                        <div class="form-group">
                            <label for="telepon">
                                <i class="fas fa-phone"></i> No. Telepon
                            </label>
                            <input type="text" id="telepon" name="telepon" placeholder="Contoh: 021-12345678">
                        </div>

                        <div class="form-group" id="statusGroup" style="display: none;">
                            <label for="status">
                                <i class="fas fa-toggle-on"></i> Status *
                            </label>
                            <select id="status" name="status">
                                <option value="active">Aktif</option>
                                <option value="inactive">Nonaktif</option>
                            </select>
                        </div>

                        <div class="form-actions">
                            <button type="button" class="btn btn-cancel" onclick="closeModal()">
                                <i class="fas fa-times"></i>
                                Batal
                            </button>
                            <button type="submit" class="btn btn-submit">
                                <i class="fas fa-save"></i>
                                Simpan
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- MODAL DETAIL -->
    <div id="detailModal" class="modal">
        <div class="modal-wrapper">
            <div class="modal-content large">
                <div class="modal-header">
                    <h2>
                        <i class="fas fa-info-circle"></i>
                        Detail Kantor
                    </h2>
                    <span class="close" onclick="closeDetailModal()">&times;</span>
                </div>
                <div class="modal-body">
                    <div class="detail-grid">
                        <div class="detail-item">
                            <div class="detail-label">
                                <i class="fas fa-barcode"></i>
                                Kode Kantor
                            </div>
                            <div class="detail-value" id="detail-kode"></div>
                        </div>

                        <div class="detail-item">
                            <div class="detail-label">
                                <i class="fas fa-toggle-on"></i>
                                Status
                            </div>
                            <div class="detail-value" id="detail-status"></div>
                        </div>

                        <div class="detail-item detail-full">
                            <div class="detail-label">
                                <i class="fas fa-building"></i>
                                Nama Kantor
                            </div>
                            <div class="detail-value" id="detail-nama"></div>
                        </div>

                        <div class="detail-item detail-full">
                            <div class="detail-label">
                                <i class="fas fa-map-marker-alt"></i>
                                Alamat
                            </div>
                            <div class="detail-value" id="detail-alamat"></div>
                        </div>

                        <div class="detail-item">
                            <div class="detail-label">
                                <i class="fas fa-phone"></i>
                                Telepon
                            </div>
                            <div class="detail-value" id="detail-telepon"></div>
                        </div>

                        <div class="detail-item">
                            <div class="detail-label">
                                <i class="fas fa-calendar"></i>
                                Dibuat Pada
                            </div>
                            <div class="detail-value" id="detail-created"></div>
                        </div>
                    </div>

                    <div class="map-container" id="mapContainer">
                        <iframe id="mapFrame" frameborder="0" allowfullscreen="" aria-hidden="false" tabindex="0"></iframe>
                    </div>

                    <div class="map-info">
                        <i class="fas fa-info-circle"></i>
                        <span>Lokasi ditampilkan berdasarkan alamat kantor. Geser peta untuk melihat area sekitar.</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Toggle Dropdown
        function toggleDropdown(id) {
            const dropdown = document.getElementById('dropdown-' + id);
            const allDropdowns = document.querySelectorAll('.dropdown');
            
            allDropdowns.forEach(d => {
                if (d.id !== 'dropdown-' + id) {
                    d.classList.remove('active');
                }
            });
            
            dropdown.classList.toggle('active');
        }

        // Close dropdown when clicking outside
        document.addEventListener('click', function(event) {
            if (!event.target.closest('.dropdown')) {
                document.querySelectorAll('.dropdown').forEach(d => {
                    d.classList.remove('active');
                });
            }
        });

        // Open Modal
        function openModal(mode) {
            document.querySelectorAll('.dropdown').forEach(d => {
                d.classList.remove('active');
            });
            
            document.getElementById('formModal').style.display = 'block';
            document.body.style.overflow = 'hidden';
            
            if (mode === 'add') {
                document.getElementById('modalTitle').innerHTML = '<i class="fas fa-plus-circle"></i> Tambah Kantor';
                document.getElementById('formAction').value = 'create';
                document.getElementById('kantorForm').reset();
                document.getElementById('statusGroup').style.display = 'none';
            }
        }

        // Close Modal
        function closeModal() {
            document.getElementById('formModal').style.display = 'none';
            document.getElementById('kantorForm').reset();
            document.body.style.overflow = '';
        }

        // Edit Kantor
        function editKantor(kantor) {
            document.querySelectorAll('.dropdown').forEach(d => {
                d.classList.remove('active');
            });
            
            document.getElementById('formModal').style.display = 'block';
            document.body.style.overflow = 'hidden';
            
            document.getElementById('modalTitle').innerHTML = '<i class="fas fa-edit"></i> Edit Kantor';
            document.getElementById('formAction').value = 'update';
            document.getElementById('kantorId').value = kantor.id;
            document.getElementById('kode_kantor').value = kantor.kode_kantor;
            document.getElementById('nama_kantor').value = kantor.nama_kantor;
            document.getElementById('alamat').value = kantor.alamat || '';
            document.getElementById('telepon').value = kantor.telepon || '';
            document.getElementById('status').value = kantor.status;
            document.getElementById('statusGroup').style.display = 'block';
        }

        // View Detail
        function viewDetail(kantor) {
            document.querySelectorAll('.dropdown').forEach(d => {
                d.classList.remove('active');
            });

            document.getElementById('detail-kode').textContent = kantor.kode_kantor;
            document.getElementById('detail-nama').textContent = kantor.nama_kantor;
            document.getElementById('detail-alamat').textContent = kantor.alamat || '-';
            document.getElementById('detail-telepon').textContent = kantor.telepon || '-';
            
            // Format status
            const statusBadge = kantor.status === 'active' 
                ? '<span class="status-badge status-active"><i class="fas fa-circle" style="font-size: 8px;"></i> Aktif</span>'
                : '<span class="status-badge status-inactive"><i class="fas fa-circle" style="font-size: 8px;"></i> Nonaktif</span>';
            document.getElementById('detail-status').innerHTML = statusBadge;

            // Format tanggal
            if (kantor.created_at) {
                const date = new Date(kantor.created_at);
                const options = { year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit' };
                document.getElementById('detail-created').textContent = date.toLocaleDateString('id-ID', options);
            } else {
                document.getElementById('detail-created').textContent = '-';
            }

            // Load Google Maps
            const alamat = kantor.alamat || kantor.nama_kantor || 'Indonesia';
            const mapUrl = `https://www.google.com/maps?q=${encodeURIComponent(alamat)}&output=embed`;
            document.getElementById('mapFrame').src = mapUrl;

            document.getElementById('detailModal').style.display = 'block';
            document.body.style.overflow = 'hidden';
        }

        // Close Detail Modal
        function closeDetailModal() {
            document.getElementById('detailModal').style.display = 'none';
            document.getElementById('mapFrame').src = '';
            document.body.style.overflow = '';
        }

        // Submit Form
        document.getElementById('kantorForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            
            fetch('', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    location.reload();
                } else {
                    alert(data.message);
                }
            })
            .catch(error => {
                alert('Terjadi kesalahan: ' + error);
            });
        });

        // Toggle Status
        function toggleStatus(id) {
            document.getElementById('dropdown-' + id).classList.remove('active');
            
            if (confirm('Yakin ingin mengubah status kantor?')) {
                const formData = new FormData();
                formData.append('action', 'toggle_status');
                formData.append('id', id);

                fetch('', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert(data.message);
                        location.reload();
                    } else {
                        alert(data.message);
                    }
                });
            }
        }

        // Delete Kantor
        function deleteKantor(id) {
            document.getElementById('dropdown-' + id).classList.remove('active');
            
            if (confirm('Yakin ingin menghapus kantor ini? Data yang terhapus tidak dapat dikembalikan!')) {
                const formData = new FormData();
                formData.append('action', 'delete');
                formData.append('id', id);

                fetch('', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert(data.message);
                        location.reload();
                    } else {
                        alert(data.message);
                    }
                });
            }
        }

        // Close modal when clicking outside
        document.getElementById('formModal').addEventListener('click', function(event) {
            if (event.target === this) {
                closeModal();
            }
        });

        document.getElementById('detailModal').addEventListener('click', function(event) {
            if (event.target === this) {
                closeDetailModal();
            }
        });
    </script>

</body>
</html>