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

if (!$conn) {
    die("Koneksi database gagal!");
}

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

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

        if ($action === 'add') {
            $nama_kategori = trim($_POST['nama_kategori']);
            $deskripsi = trim($_POST['deskripsi']);

            if (empty($nama_kategori)) {
                echo json_encode(['success' => false, 'message' => 'Nama kategori harus diisi!']);
                exit;
            }
            
            $stmt = $conn->prepare("INSERT INTO kategori (nama_kategori, deskripsi) VALUES (?, ?)");
            $stmt->bind_param("ss", $nama_kategori, $deskripsi);
            $stmt->execute();
            $stmt->close();
            
            echo json_encode(['success' => true, 'message' => 'Kategori berhasil ditambahkan!']);
        }
        
        elseif ($action === 'edit') {
            $id = intval($_POST['id']);
            $nama_kategori = trim($_POST['nama_kategori']);
            $deskripsi = trim($_POST['deskripsi']);
            
            if (empty($nama_kategori) || $id <= 0) {
                echo json_encode(['success' => false, 'message' => 'Data tidak valid!']);
                exit;
            }
            
            $stmt = $conn->prepare("UPDATE kategori SET nama_kategori = ?, deskripsi = ? WHERE id = ?");
            $stmt->bind_param("ssi", $nama_kategori, $deskripsi, $id);
            $stmt->execute();
            $stmt->close();
            
            echo json_encode(['success' => true, 'message' => 'Kategori berhasil diupdate!']);
        }
        
        elseif ($action === 'delete') {
            $id = intval($_POST['id']);
            
            if ($id <= 0) {
                echo json_encode(['success' => false, 'message' => 'ID tidak valid!']);
                exit;
            }
            
            $stmt = $conn->prepare("DELETE FROM kategori WHERE id = ?");
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $stmt->close();
            
            echo json_encode(['success' => true, 'message' => 'Kategori berhasil dihapus!']);
        }
        
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Terjadi kesalahan: ' . $e->getMessage()]);
    }
    exit;
}

$result = $conn->query("SELECT * FROM kategori ORDER BY nama_kategori ASC");
$kategoris = [];
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $kategoris[] = $row;
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kelola Kategori - 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;
        }

        /* 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: 160px;
            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.edit:hover {
            background: rgba(59, 130, 246, 0.1);
            color: #3b82f6;
        }

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

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

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

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

        /* 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;
        }

        @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;
        }

        .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%;
        }

        .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 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 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: 80px;
        }

        .form-actions {
            margin-top: 30px;
            display: flex;
            gap: 12px;
            justify-content: flex-end;
            padding-top: 20px;
            border-top: 1px solid #f1f5f9;
        }

        .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;
        }

        /* 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-body {
                padding: 20px;
            }

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

            .form-actions .btn {
                width: 100%;
            }
        }
    </style>
</head>
<body>

    <!-- HEADER -->
    <div class="header">
        <h1><i class="fas fa-tags"></i> Kelola Kategori</h1>
        <p>Daftar Kategori Barang Inventory 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 Kategori
            </div>
            <button class="btn btn-add" onclick="openModal('add')">
                <i class="fas fa-plus"></i>
                Tambah Kategori
            </button>
        </div>

        <div class="table-container">
            <table>
                <thead>
                    <tr>
                        <th style="width: 60px;">No</th>
                        <th>Nama Kategori</th>
                        <th>Deskripsi</th>
                        <th style="width: 80px; text-align: center;">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($kategoris)): ?>
                        <tr>
                            <td colspan="4">
                                <div class="empty-state">
                                    <i class="fas fa-inbox"></i>
                                    <p>Belum ada data kategori</p>
                                </div>
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($kategoris as $index => $kategori): ?>
                        <tr>
                            <td><strong><?= $index + 1 ?></strong></td>
                            <td><strong><?= htmlspecialchars($kategori['nama_kategori']) ?></strong></td>
                            <td style="color: #64748b;"><?= htmlspecialchars($kategori['deskripsi'] ?: '-') ?></td>
                            <td style="text-align: center;">
                                <div class="dropdown" id="dropdown-<?= $kategori['id'] ?>">
                                    <button class="dropdown-toggle" onclick="toggleDropdown(<?= $kategori['id'] ?>)">
                                        <i class="fas fa-ellipsis-vertical"></i>
                                    </button>
                                    <div class="dropdown-menu">
                                        <button class="dropdown-item edit" onclick='editKategori(<?= json_encode($kategori) ?>)'>
                                            <i class="fas fa-edit"></i>
                                            Edit
                                        </button>
                                        <div class="dropdown-divider"></div>
                                        <button class="dropdown-item delete" onclick="deleteKategori(<?= $kategori['id'] ?>, '<?= htmlspecialchars($kategori['nama_kategori']) ?>')">
                                            <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 Kategori
                    </h2>
                    <span class="close" onclick="closeModal()">&times;</span>
                </div>
                <div class="modal-body">
                    <form id="kategoriForm">
                        <input type="hidden" id="formAction" name="action" value="add">
                        <input type="hidden" id="idKategori" name="id">

                        <div class="form-group">
                            <label for="namaKategori">
                                <i class="fas fa-tag"></i> Nama Kategori *
                            </label>
                            <input type="text" id="namaKategori" name="nama_kategori" placeholder="Contoh: Elektronik" required>
                        </div>

                        <div class="form-group">
                            <label for="deskripsi">
                                <i class="fas fa-file-alt"></i> Deskripsi
                            </label>
                            <textarea id="deskripsi" name="deskripsi" placeholder="Deskripsi opsional..." rows="3"></textarea>
                        </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>

    <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 Kategori';
                document.getElementById('formAction').value = 'add';
                document.getElementById('kategoriForm').reset();
                document.getElementById('idKategori').value = '';
            }
        }

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

        // Edit Kategori
        function editKategori(kategori) {
            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 Kategori';
            document.getElementById('formAction').value = 'edit';
            document.getElementById('idKategori').value = kategori.id;
            document.getElementById('namaKategori').value = kategori.nama_kategori;
            document.getElementById('deskripsi').value = kategori.deskripsi || '';
        }

        // Delete Kategori
        function deleteKategori(id, nama) {
            document.getElementById('dropdown-' + id).classList.remove('active');

            if (confirm('Yakin ingin menghapus kategori "' + nama + '"?\n\nData 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);
                    }
                });
            }
        }

        // Submit Form
        document.getElementById('kategoriForm').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);
            });
        });

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

</body>
</html>