<?php
require 'db.php';

// 1. Handle SAVE (Add or Edit)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_account') {
    $code = trim($_POST['code']);
    $description = trim($_POST['description']);
    $category = trim($_POST['category']);
    $location_id = $_POST['location_id'];
    $id = $_POST['account_id'] ?? '';

    if (!empty($code) && !empty($description) && !empty($location_id)) {
        if (!empty($id)) {
            // UPDATE existing
            $stmt = $pdo->prepare("UPDATE accounts SET code = ?, description = ?, category = ?, location_id = ? WHERE id = ?");
            $stmt->execute([$code, $description, $category, $location_id, $id]);
        } else {
            // INSERT new
            $stmt = $pdo->prepare("INSERT INTO accounts (code, description, category, location_id) VALUES (?, ?, ?, ?)");
            $stmt->execute([$code, $description, $category, $location_id]);
        }
        header("Location: accounts.php?success=1");
        exit;
    }
}

// 2. Handle DELETE
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete'])) {
    // Note: Deleting an account will fail if there are timesheet entries tied to it due to foreign key constraints.
    // That's a good thing! It prevents accidental data loss.
    try {
        $stmt = $pdo->prepare("DELETE FROM accounts WHERE id = ?");
        $stmt->execute([$_POST['delete']]);
        header("Location: accounts.php?deleted=1");
        exit;
    } catch (PDOException $e) {
        $error = "Cannot delete this account. It is currently being used in a timesheet.";
    }
}

// 3. Fetch Data for EDIT MODE
$edit_data = null;
if (isset($_GET['edit'])) {
    $stmt = $pdo->prepare("SELECT * FROM accounts WHERE id = ?");
    $stmt->execute([$_GET['edit']]);
    $edit_data = $stmt->fetch();
}

// 4. Fetch Dropdowns & Table Data
$locations = $pdo->query("SELECT * FROM locations ORDER BY name ASC")->fetchAll();

$sql = "SELECT a.*, l.name as location_name 
        FROM accounts a 
        LEFT JOIN locations l ON a.location_id = l.id 
        ORDER BY l.name ASC, a.category DESC, a.code ASC";
$accounts = $pdo->query($sql)->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>Account Codes - 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">

    <?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">Timesheet Account Codes</h2>
        </header>

        <div class="flex-1 overflow-auto p-4 flex flex-col gap-4">
            
            <?php if (isset($error)): ?>
                <div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-3 rounded text-xs font-bold shadow-sm">
                    <i class="fas fa-exclamation-triangle mr-2"></i> <?= htmlspecialchars($error) ?>
                </div>
            <?php endif; ?>

            <div class="bg-white dark:bg-gray-800 p-4 rounded shadow border dark:border-gray-700 shrink-0">
                <div class="text-[10px] font-bold text-gray-400 uppercase tracking-wide mb-3">
                    <?= $edit_data ? 'Edit Account Code' : 'Add New Account Code' ?>
                </div>
                <form method="POST" class="flex flex-wrap items-end gap-4">
                    <input type="hidden" name="action" value="save_account">
                    <input type="hidden" name="account_id" value="<?= $edit_data['id'] ?? '' ?>">
                    
                    <div class="w-full md:w-auto">
                        <label class="block text-[10px] font-bold text-gray-500 dark:text-gray-400 uppercase mb-1">Location</label>
                        <select name="location_id" required class="w-full md:w-40 h-[34px] bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-2 focus:outline-none focus:border-blue-500 transition text-xs">
                            <option value="">Select Location...</option>
                            <?php foreach($locations as $loc): ?>
                                <option value="<?= $loc['id'] ?>" <?= ($edit_data && $edit_data['location_id'] == $loc['id']) ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($loc['name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="w-full md:w-auto">
                        <label class="block text-[10px] font-bold text-gray-500 dark:text-gray-400 uppercase mb-1">Category</label>
                        <select name="category" required class="w-full md:w-32 h-[34px] bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-2 focus:outline-none focus:border-blue-500 transition text-xs">
                            <option value="EXPENSE" <?= ($edit_data && $edit_data['category'] === 'EXPENSE') ? 'selected' : '' ?>>EXPENSE</option>
                            <option value="CAPITAL" <?= ($edit_data && $edit_data['category'] === 'CAPITAL') ? 'selected' : '' ?>>CAPITAL</option>
                        </select>
                    </div>

                    <div class="w-full md:w-auto">
                        <label class="block text-[10px] font-bold text-gray-500 dark:text-gray-400 uppercase mb-1">Code</label>
                        <input type="text" name="code" value="<?= htmlspecialchars($edit_data['code'] ?? '') ?>" required placeholder="e.g. 6410.000" class="w-full md:w-32 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 transition font-mono text-xs">
                    </div>

                    <div class="w-full md:w-auto flex-1">
                        <label class="block text-[10px] font-bold text-gray-500 dark:text-gray-400 uppercase mb-1">Description</label>
                        <input type="text" name="description" value="<?= htmlspecialchars($edit_data['description'] ?? '') ?>" required placeholder="Account description..." 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 transition text-xs">
                    </div>

                    <div class="flex gap-2">
                        <button type="submit" class="bg-blue-600 hover:bg-blue-500 text-white px-4 h-[34px] rounded shadow font-bold uppercase text-xs transition">
                            <?= $edit_data ? 'Update' : 'Add Code' ?>
                        </button>
                        <?php if($edit_data): ?>
                            <a href="accounts.php" class="bg-gray-500 hover:bg-gray-400 text-white px-4 h-[34px] rounded shadow font-bold uppercase text-xs transition flex items-center">Cancel</a>
                        <?php endif; ?>
                    </div>
                </form>
            </div>

            <div class="bg-white dark:bg-gray-800 rounded shadow border dark:border-gray-700 flex flex-col flex-1 overflow-hidden">
                <div class="overflow-x-auto flex-1">
                    <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 sticky top-0 z-10">
                                <th class="px-4 py-3 w-32">Location</th>
                                <th class="px-4 py-3 w-24">Category</th>
                                <th class="px-4 py-3 w-28">Code</th>
                                <th class="px-4 py-3">Description</th>
                                <th class="px-4 py-3 w-20 text-right">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-100 dark:divide-gray-700 text-xs">
                            <?php if(empty($accounts)): ?>
                                <tr><td colspan="5" class="p-8 text-center text-gray-400 italic">No account codes found.</td></tr>
                            <?php else: ?>
                                <?php foreach ($accounts as $acc): ?>
                                <tr class="hover:bg-gray-50 dark:hover:bg-gray-700/30 transition-colors group">
                                    <td class="px-4 py-2 font-bold text-gray-600 dark:text-gray-300"><?= htmlspecialchars($acc['location_name'] ?? 'Unknown') ?></td>
                                    <td class="px-4 py-2">
                                        <?php if ($acc['category'] === 'EXPENSE'): ?>
                                            <span class="inline-flex text-[9px] font-bold uppercase rounded-full bg-orange-100 text-orange-800 dark:bg-orange-900/50 dark:text-orange-400 px-2 py-0.5">Expense</span>
                                        <?php else: ?>
                                            <span class="inline-flex text-[9px] font-bold uppercase rounded-full bg-indigo-100 text-indigo-800 dark:bg-indigo-900/50 dark:text-indigo-400 px-2 py-0.5">Capital</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="px-4 py-2 font-mono text-gray-500"><?= htmlspecialchars($acc['code']) ?></td>
                                    <td class="px-4 py-2 truncate max-w-[300px]" title="<?= htmlspecialchars($acc['description']) ?>"><?= htmlspecialchars($acc['description']) ?></td>
                                    <td class="px-4 py-2 text-right">
                                        <div class="flex justify-end gap-3 opacity-0 group-hover:opacity-100 transition-opacity">
                                            <a href="accounts.php?edit=<?= $acc['id'] ?>" class="text-gray-400 hover:text-blue-500 transition" title="Edit"><i class="fas fa-pen"></i></a>
                                            <form method="POST" class="inline" onsubmit="return confirm('Delete this account code?');">
                                                <input type="hidden" name="delete" value="<?= $acc['id'] ?>">
                                                <button type="submit" class="text-gray-400 hover:text-red-500 transition" title="Delete"><i class="fas fa-trash-alt"></i></button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            
        </div>
    </main>

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