<?php
require 'db.php';

// Handle New Project Creation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'new_project') {
    $name = trim($_POST['project_name']);
    if (!empty($name)) {
        // Default empty data structure
        $default_data = json_encode(['cables' => [], 'splices' => []]);
        $stmt = $pdo->prepare("INSERT INTO projects (project_name, cable_data) VALUES (?, ?)");
        $stmt->execute([$name, $default_data]);
        $new_id = $pdo->lastInsertId();
        header("Location: cable_map.php?id=" . $new_id);
        exit;
    }
}

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

// Fetch Projects
$stmt = $pdo->query("SELECT * FROM projects ORDER BY updated_at DESC");
$projects = $stmt->fetchAll();
?>

<!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>Fiber Projects - Tech Dash</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" x-data="{ open: false }">

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

    <main class="flex-1 flex flex-col h-full overflow-hidden">
        <header class="h-14 bg-white dark:bg-gray-800 shadow flex items-center px-6 justify-between shrink-0 z-10">
            <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">Fiber Projects</h2>
            <button @click="open = true" class="bg-orange-600 hover:bg-orange-500 text-white px-4 py-2 rounded shadow font-bold uppercase text-xs transition flex items-center">
                <i class="fas fa-plus mr-2"></i> New Project
            </button>
        </header>

        <div class="flex-1 overflow-auto p-4">
            <div class="bg-white dark:bg-gray-800 rounded shadow overflow-hidden border dark:border-gray-700">
                <table class="w-full text-left border-collapse">
                    <thead>
                        <tr class="bg-gray-100 dark:bg-gray-700/80 text-[10px] uppercase text-gray-500 dark:text-gray-400 font-bold border-b dark:border-gray-700 tracking-wider">
                            <th class="px-6 py-3 w-16 text-center">ID</th>
                            <th class="px-6 py-3">Project Name</th>
                            <th class="px-6 py-3">Created</th>
                            <th class="px-6 py-3">Last Updated</th>
                            <th class="px-6 py-3 text-right">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-100 dark:divide-gray-700 text-xs">
                        <?php if (count($projects) === 0): ?>
                            <tr><td colspan="5" class="px-6 py-8 text-center text-gray-500 italic">No fiber projects found.</td></tr>
                        <?php endif; ?>

                        <?php foreach ($projects as $p): ?>
                            <tr class="hover:bg-gray-50 dark:hover:bg-gray-700/30 transition-colors group">
                                <td class="px-6 py-3 text-center font-mono text-gray-400">#<?= $p['id'] ?></td>
                                <td class="px-6 py-3 font-bold text-gray-900 dark:text-gray-200"><?= htmlspecialchars($p['project_name']) ?></td>
                                <td class="px-6 py-3 text-gray-500"><?= date('M j, Y', strtotime($p['created_at'])) ?></td>
                                <td class="px-6 py-3 text-gray-500"><?= date('M j, Y g:ia', strtotime($p['updated_at'])) ?></td>
                                <td class="px-6 py-3 text-right space-x-3">
                                    <a href="cable_map.php?id=<?= $p['id'] ?>" class="text-orange-600 hover:text-orange-500 font-bold uppercase tracking-wide text-[10px] transition"><i class="fas fa-map mr-1"></i> Map</a>
                                    <form method="POST" class="inline" onsubmit="return confirm('Delete this project permanently?');">
                                        <input type="hidden" name="delete" value="<?= $p['id'] ?>">
                                        <button type="submit" class="text-gray-400 hover:text-red-500 font-bold uppercase tracking-wide text-[10px] transition" title="Delete"><i class="fas fa-trash-alt"></i></button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </main>

    <!-- New Project Modal -->
    <div x-show="open" x-cloak x-init="$watch('open', v => v && $nextTick(() => $refs.projectName.focus()))"
         @click.self="open = false" @keydown.escape.window="open = false"
         class="fixed inset-0 bg-black/50 z-50 flex items-center justify-center">
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl p-6 w-full max-w-sm mx-4">
            <h3 class="font-bold text-sm uppercase tracking-wide text-gray-700 dark:text-gray-200 mb-4">New Fiber Project</h3>
            <form method="POST">
                <input type="hidden" name="action" value="new_project">
                <input x-ref="projectName" type="text" name="project_name" placeholder="e.g. Main Street Run" required
                    class="w-full bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-3 py-2 text-sm mb-4 focus:outline-none focus:border-orange-500">
                <div class="flex gap-2 justify-end">
                    <button type="button" @click="open = false"
                        class="px-4 py-2 text-xs font-bold uppercase rounded bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 transition">Cancel</button>
                    <button type="submit"
                        class="px-4 py-2 text-xs font-bold uppercase rounded bg-orange-600 hover:bg-orange-500 text-white shadow transition">Create</button>
                </div>
            </form>
        </div>
    </div>
</body>
</html>