<?php
require 'db.php';

// 1. Handle Add / Update
if (isset($_POST['action']) && $_POST['action'] === 'save') {
    $name = trim($_POST['name']);
    
    if (!empty($_POST['id'])) {
        // Update existing
        $stmt = $pdo->prepare("UPDATE networks SET name = ? WHERE id = ?");
        $stmt->execute([$name, $_POST['id']]);
    } else {
        // Insert new (check for duplicates first, case-insensitive)
        $stmtCheck = $pdo->prepare("SELECT id FROM networks WHERE LOWER(name) = LOWER(?)");
        $stmtCheck->execute([$name]);
        if (!$stmtCheck->fetch()) {
            $stmt = $pdo->prepare("INSERT INTO networks (name) VALUES (?)");
            $stmt->execute([$name]);
        }
    }
    header("Location: networks.php");
    exit;
}

// 2. Handle Delete
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete'])) {
    $stmt = $pdo->prepare("DELETE FROM networks WHERE id = ?");
    $stmt->execute([$_POST['delete']]);
    header("Location: networks.php");
    exit;
}

// Fetch Data
$networks = $pdo->query("SELECT * FROM networks ORDER BY name ASC")->fetchAll();

$edit_network = null;
if (isset($_GET['edit'])) {
    $stmt = $pdo->prepare("SELECT * FROM networks WHERE id = ?");
    $stmt->execute([$_GET['edit']]);
    $edit_network = $stmt->fetch();
}
?>
<!DOCTYPE html>
<html lang="en" class="h-full">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Networks</title>
    <link rel="stylesheet" href="/assets/css/tailwind.min.css">
    
    <script>
        if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
            document.documentElement.classList.add('dark');
            document.documentElement.style.backgroundColor = '#111827';
        } else {
            document.documentElement.classList.remove('dark');
            document.documentElement.style.backgroundColor = '#f3f4f6';
        }
    </script>
    <link href="/assets/css/font-awesome.min.css" rel="stylesheet">
</head>
<body class="bg-gray-100 dark:bg-gray-900 text-gray-800 dark:text-gray-200 h-full flex overflow-hidden text-sm">

    <?php include 'sidebar.php'; ?>

    <main class="flex-1 flex flex-col h-full overflow-hidden relative">
        <header class="h-14 bg-white dark:bg-gray-800 shadow flex items-center px-6 justify-between shrink-0">
            <div class="flex items-center">
                <button class="open-sidebar-btn md:hidden mr-3 text-gray-500 hover:text-blue-600 transition">
                    <i class="fas fa-bars text-xl"></i>
                </button>
                <h2 class="font-bold text-lg text-gray-700 dark:text-gray-200">Manage Networks</h2>
            </div>
        </header>

        <div class="flex-1 overflow-auto p-4 md:p-6 flex flex-col md:flex-row gap-6 items-start">
            
            <div class="w-full md:w-1/3 bg-white dark:bg-gray-800 p-5 rounded shadow border border-gray-200 dark:border-gray-700 shrink-0 md:sticky md:top-0">
                <h3 class="font-bold uppercase tracking-wider text-xs text-gray-500 mb-4"><?= $edit_network ? 'Edit Network' : 'Add New Network' ?></h3>
                <form method="POST" class="flex flex-col gap-4">
                    <input type="hidden" name="action" value="save">
                    <input type="hidden" name="id" value="<?= $edit_network['id'] ?? '' ?>">
                    
                    <div>
                        <label class="block text-[10px] font-bold text-gray-400 uppercase mb-1">Network Name</label>
                        <input type="text" name="name" value="<?= htmlspecialchars($edit_network['name'] ?? '') ?>" required placeholder="e.g. Benk XGS S1" class="w-full h-[34px] bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-3 focus:outline-none focus:border-blue-500">
                    </div>

                    <div class="flex gap-2 mt-2">
                        <?php if($edit_network): ?>
                            <a href="networks.php" class="bg-gray-500 text-white px-4 py-2 rounded text-xs font-bold uppercase w-1/3 text-center flex items-center justify-center">Cancel</a>
                        <?php endif; ?>
                        <button type="submit" class="bg-blue-600 hover:bg-blue-500 text-white px-4 py-2 rounded shadow font-bold uppercase text-xs transition flex-1">Save Network</button>
                    </div>
                </form>
            </div>

            <div class="w-full md:w-2/3 bg-white dark:bg-gray-800 rounded shadow border border-gray-200 dark:border-gray-700 flex flex-col h-full overflow-hidden relative">
                <div class="overflow-x-auto overflow-y-auto flex-1 w-full">
                    <table class="w-full text-left border-collapse min-w-[400px]">
                        <thead>
                            <tr class="bg-gray-50 dark:bg-gray-700/50 text-[10px] uppercase text-gray-500 dark:text-gray-400 font-bold border-b dark:border-gray-700 tracking-wider sticky top-0 z-10 backdrop-blur-sm">
                                <th class="px-4 py-3 whitespace-nowrap">Network Name</th>
                                <th class="px-4 py-3 w-24 text-right whitespace-nowrap">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-100 dark:divide-gray-700 text-xs">
                            <?php foreach($networks as $net): ?>
                            <tr class="hover:bg-gray-50 dark:hover:bg-gray-700/30 transition-colors group">
                                <td class="px-4 py-3 font-bold text-gray-700 dark:text-gray-200 whitespace-nowrap"><?= htmlspecialchars($net['name']) ?></td>
                                <td class="px-4 py-3 text-right">
                                    <div class="flex justify-end gap-3 md:opacity-0 md:group-hover:opacity-100 transition-opacity">
                                        <a href="networks.php?edit=<?= $net['id'] ?>" class="text-blue-500 hover:text-blue-600 p-2 md:p-0"><i class="fas fa-pen"></i></a>
                                        <form method="POST" class="inline" onsubmit="return confirm('Are you sure you want to delete this network?');">
                                            <input type="hidden" name="delete" value="<?= $net['id'] ?>">
                                            <button type="submit" class="text-red-400 hover:text-red-500 p-2 md:p-0"><i class="fas fa-trash"></i></button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php if (empty($networks)): ?>
                            <tr>
                                <td colspan="2" class="p-8 text-center text-gray-400 italic">No networks found.</td>
                            </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

        </div>
    </main>

    <script>
    </script>
</body>
</html>