<?php
session_start();
include '../db_config.php';
include '../functions.php';

check_login();
check_role('admin');

// Handle Form Submissions
$message = '';
$error = '';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Add District
    if (isset($_POST['add_district'])) {
        $name = sanitize_input($_POST['name']);
        if (!empty($name)) {
            $stmt = $conn->prepare("INSERT INTO districts (name) VALUES (?)");
            $stmt->bind_param("s", $name);
            if ($stmt->execute()) {
                $message = "District added successfully.";
            } else {
                $error = "Error adding district: " . $conn->error;
            }
            $stmt->close();
        }
    }

    // Add Division
    if (isset($_POST['add_division'])) {
        $district_id = (int)$_POST['district_id'];
        $name = sanitize_input($_POST['division_name']);
        if (!empty($name) && $district_id > 0) {
            $stmt = $conn->prepare("INSERT INTO divisional_secretariats (district_id, name) VALUES (?, ?)");
            $stmt->bind_param("is", $district_id, $name);
            if ($stmt->execute()) {
                $message = "Division added successfully.";
            } else {
                $error = "Error adding division: " . $conn->error;
            }
            $stmt->close();
        }
    }

    // Delete District
    if (isset($_POST['delete_district'])) {
        $id = (int)$_POST['id'];
        // Use CASCADE delete in DB, or manual delete
        $stmt = $conn->prepare("DELETE FROM districts WHERE id = ?");
        $stmt->bind_param("i", $id);
        if ($stmt->execute()) {
            $message = "District deleted successfully.";
        } else {
            $error = "Error deleting district: " . $conn->error;
        }
        $stmt->close();
    }

    // Delete Division
    if (isset($_POST['delete_division'])) {
        $id = (int)$_POST['id'];
        $stmt = $conn->prepare("DELETE FROM divisional_secretariats WHERE id = ?");
        $stmt->bind_param("i", $id);
        if ($stmt->execute()) {
            $message = "Division deleted successfully.";
        } else {
            $error = "Error deleting division: " . $conn->error;
        }
        $stmt->close();
    }
}

// Fetch Data in Nested Structure
$locations = [];
$result = $conn->query("SELECT * FROM districts ORDER BY name");
if ($result && $result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $locations[$row['id']] = [
            'name' => $row['name'],
            'divisions' => []
        ];
    }
}

$sql_div = "SELECT * FROM divisional_secretariats ORDER BY name";
$result_div = $conn->query($sql_div);
if ($result_div && $result_div->num_rows > 0) {
    while($row = $result_div->fetch_assoc()) {
        if (isset($locations[$row['district_id']])) {
            $locations[$row['district_id']]['divisions'][] = $row;
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Locations | Admin Panel</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://unpkg.com/lucide@latest"></script>
    <style>
        body { font-family: 'Outfit', sans-serif; }
        .glass-panel {
            background: rgba(30, 41, 59, 0.4);
            backdrop-filter: blur(12px);
            border: 1px solid rgba(255, 255, 255, 0.05);
        }
        .accordion-content { transition: max-height 0.3s ease-in-out, opacity 0.3s ease-in-out; max-height: 0; opacity: 0; overflow: hidden; }
        .accordion-content.active { max-height: 2000px; opacity: 1; }
        .rotate-icon { transition: transform 0.3s; }
        .active .rotate-icon { transform: rotate(180deg); }
    </style>
</head>
<body class="bg-slate-950 min-h-screen text-slate-200 selection:bg-indigo-500 selection:text-white">

    <!-- Navbar -->
    <nav class="bg-slate-900 border-b border-slate-800 sticky top-0 z-50">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between h-20 items-center">
                <a href="<?= BASE_URL ?>/index.php" class="text-2xl font-bold italic tracking-tighter text-white">
                    Work For <span class="text-indigo-400">Sri Lanka</span>
                    <span class="text-xs font-normal text-white bg-indigo-600 px-2 py-0.5 rounded ml-2 align-middle border border-indigo-500/50">Admin Panel</span>
                </a>
                <div class="flex items-center gap-6">
                    <span class="text-sm font-medium text-slate-400 hidden md:inline">Logged in as: <span class="text-indigo-400 font-mono"><?php echo $_SESSION['username']; ?></span></span>
                    <a href="../logout.php" class="text-slate-400 hover:text-red-400 font-medium transition text-sm flex items-center">
                        <i data-lucide="log-out" class="w-4 h-4 mr-2"></i> Logout
                    </a>
                </div>
            </div>
        </div>
    </nav>

    <!-- Header Section -->
    <div class="relative bg-slate-900 py-10 px-4 border-b border-slate-800">
        <div class="absolute top-0 right-0 w-[500px] h-[500px] bg-indigo-600/10 rounded-full blur-[100px] -mt-20 -mr-20 pointer-events-none"></div>
        
        <div class="max-w-7xl mx-auto flex flex-col md:flex-row justify-between items-center gap-4 relative z-10">
            <div>
                <h1 class="text-3xl font-bold mb-2 text-white">Manage Locations</h1>
                <p class="text-slate-400">Manage districts and divisional secretariats.</p>
            </div>
             <a href="dashboard.php" class="bg-slate-800 hover:bg-slate-700 text-white px-5 py-2.5 rounded-xl font-bold transition flex items-center border border-slate-700 hover:border-indigo-500 hover:text-indigo-400 shadow-sm text-sm group">
                <i data-lucide="arrow-left" class="w-4 h-4 mr-2 group-hover:-translate-x-1 transition-transform"></i> Back to Dashboard
            </a>
        </div>
    </div>

    <!-- Main Content -->
    <div class="max-w-7xl mx-auto px-4 pb-20 pt-8">
        
        <?php if ($message): ?>
            <div class="bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 px-6 py-4 rounded-xl mb-6 flex items-center shadow-sm animate-fade-in-down">
                <i data-lucide="check-circle" class="w-5 h-5 mr-3 flex-shrink-0"></i>
                <span class="font-bold mr-2">Success!</span> <?php echo $message; ?>
            </div>
        <?php endif; ?>

        <?php if ($error): ?>
            <div class="bg-red-500/10 border border-red-500/20 text-red-400 px-6 py-4 rounded-xl mb-6 flex items-center shadow-sm animate-pulse">
                <i data-lucide="alert-circle" class="w-5 h-5 mr-3 flex-shrink-0"></i>
                <div><?php echo $error; ?></div>
            </div>
        <?php endif; ?>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            
            <!-- Add New District Form -->
            <div class="lg:col-span-1">
                <div class="glass-panel rounded-3xl shadow-xl overflow-hidden sticky top-24">
                    <div class="p-6 border-b border-slate-700/50 bg-slate-800/30">
                        <h2 class="text-lg font-bold text-white flex items-center">
                            <i data-lucide="map" class="w-5 h-5 mr-2 text-indigo-400"></i> Add New District
                        </h2>
                    </div>
                    <form method="POST" class="p-6 space-y-4">
                        <div>
                            <label class="block text-xs font-bold text-slate-400 uppercase tracking-wide mb-1">District Name</label>
                            <input type="text" name="name" required class="w-full px-4 py-2 bg-slate-900/50 border border-slate-700 rounded-xl text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 transition outline-none text-white placeholder-slate-600" placeholder="e.g. Colombo">
                        </div>
                        <button type="submit" name="add_district" class="w-full bg-indigo-600 hover:bg-indigo-500 text-white font-bold py-3 rounded-xl shadow-lg shadow-indigo-600/20 hover:shadow-indigo-600/40 transition transform active:scale-95 flex items-center justify-center">
                            Add District
                        </button>
                    </form>
                </div>
            </div>

            <!-- Locations List -->
            <div class="lg:col-span-2 space-y-4">
                <?php foreach ($locations as $district_id => $district): ?>
                <div class="glass-panel rounded-2xl shadow-md border border-slate-700/50 overflow-hidden group hover:border-indigo-500/30 transition">
                    <!-- District Header -->
                    <div class="p-4 bg-slate-800/30 flex justify-between items-center cursor-pointer hover:bg-slate-700/30 transition" onclick="toggleAccordion(<?php echo $district_id; ?>, this)">
                        <div class="flex items-center gap-3">
                            <i data-lucide="chevron-down" class="text-slate-400 rotate-icon"></i>
                            <h3 class="text-lg font-bold text-white"><?php echo htmlspecialchars($district['name']); ?></h3>
                            <span class="bg-indigo-500/10 text-indigo-400 text-xs font-bold px-2 py-1 rounded-full border border-indigo-500/20"><?php echo count($district['divisions']); ?> Divisions</span>
                        </div>
                        <div class="flex items-center gap-2">
                            <form method="POST" onsubmit="return confirm('Are you sure? This will delete the district and ALL its divisions.');" class="inline">
                                <input type="hidden" name="id" value="<?php echo $district_id; ?>">
                                <button type="submit" name="delete_district" class="text-red-400 hover:text-red-300 p-2 rounded hover:bg-red-500/10 transition" onclick="event.stopPropagation();">
                                    <i data-lucide="trash-2" class="w-4 h-4"></i>
                                </button>
                            </form>
                        </div>
                    </div>

                    <!-- Divisions Content -->
                    <div id="district-<?php echo $district_id; ?>" class="accordion-content bg-slate-900/40 border-t border-slate-700/50">
                        <div class="p-4 pl-10">
                            <!-- Add Division Form -->
                            <form method="POST" class="mb-4 flex gap-2">
                                <input type="hidden" name="district_id" value="<?php echo $district_id; ?>">
                                <input type="text" name="division_name" placeholder="Add Division to <?php echo htmlspecialchars($district['name']); ?>" required class="flex-1 bg-slate-900/50 border border-slate-700 rounded-xl px-3 py-2 text-sm focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 text-white placeholder-slate-600">
                                <button type="submit" name="add_division" class="bg-indigo-600 hover:bg-indigo-500 text-white px-4 py-2 rounded-xl text-sm transition font-medium"><i data-lucide="plus" class="w-4 h-4"></i></button>
                            </form>

                            <!-- Divisions Grid -->
                            <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-3">
                                <?php if (empty($district['divisions'])): ?>
                                    <p class="text-slate-500 text-xs col-span-full italic">No divisions added yet.</p>
                                <?php else: ?>
                                    <?php foreach ($district['divisions'] as $div): ?>
                                    <div class="flex justify-between items-center bg-slate-800/40 border border-slate-700 rounded-lg px-3 py-2 shadow-sm hover:border-slate-600 transition group/div">
                                        <span class="text-slate-300 text-sm"><?php echo htmlspecialchars($div['name']); ?></span>
                                        <form method="POST" onsubmit="return confirm('Delete this division?');">
                                            <input type="hidden" name="id" value="<?php echo $div['id']; ?>">
                                            <button type="submit" name="delete_division" class="text-slate-600 group-hover/div:text-red-400 hover:text-red-300 transition opacity-0 group-hover/div:opacity-100">
                                                <i data-lucide="x" class="w-3 h-3"></i>
                                            </button>
                                        </form>
                                    </div>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <!-- Simple Footer -->
    <footer class="bg-slate-900 border-t border-slate-800 py-8 text-center text-slate-500 text-sm mt-12">
        <p>&copy; <?=date('Y')?> Work For Sri Lanka. All rights reserved.</p>
    </footer>

    <script>
        lucide.createIcons();

        function toggleAccordion(id, headerElement) {
            // Close all other accordions (optional, but cleaner)
            // document.querySelectorAll('.accordion-content.active').forEach(el => {
            //     if(el.id !== 'district-' + id) el.classList.remove('active');
            // });
            // document.querySelectorAll('.rotate-icon').forEach(icon => {
            //     // Logic to reset icon rotation if needed
            // });

            const content = document.getElementById('district-' + id);
            content.classList.toggle('active');
            headerElement.classList.toggle('active');
        }
    </script>
</body>
</html>
