<?php
session_start();

require_once '../includes/functions.php';
require_once '../includes/db.php';

requireLogin();

$isAdmin = isAdmin();
$isManager = isManager();

if (!$isAdmin && !$isManager) {
    header('Location: /pages/dashboard.php');
    exit;
}

$accessibleBranches = getAccessibleBranches($pdo);
if (empty($accessibleBranches)) {
    die('No branch access assigned.');
}

$hasSoftDelete = dbTableHasColumn($pdo, 'expenses', 'is_deleted');
$selectedBranch = $_GET['branch'] ?? '';
if ($selectedBranch === '' && count($accessibleBranches) === 1) {
    $selectedBranch = (string)$accessibleBranches[0];
}
if ($selectedBranch !== '') {
    $selectedBranch = (string)(int)$selectedBranch;
    if (!in_array((int)$selectedBranch, $accessibleBranches, true)) {
        die('Unauthorized branch access.');
    }
}

$supplierFilter = $hasSoftDelete ? 'AND is_deleted = 0' : '';
$supplierStmt = $pdo->prepare("
    SELECT DISTINCT supplier
    FROM expenses
    WHERE supplier IS NOT NULL
      AND supplier <> ''
      $supplierFilter
      AND branch_id IN (" . implode(',', array_fill(0, count($accessibleBranches), '?')) . ")
    ORDER BY supplier ASC
");
$supplierStmt->execute($accessibleBranches);
$suppliers = $supplierStmt->fetchAll(PDO::FETCH_COLUMN);

$message = '';
$success = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf($_POST['csrf_token'] ?? null);

    $supplier = trim($_POST['supplier'] ?? '');
    $itemName = trim($_POST['item_name'] ?? '');
    $purchaseDate = trim($_POST['purchase_date'] ?? '');
    $amount = (float)($_POST['amount'] ?? 0);
    $notes = trim($_POST['notes'] ?? '');
    $category = trim($_POST['category'] ?? '');
    $branchId = (int)($_POST['branch_id'] ?? 0);

    if (
        $supplier === '' ||
        $itemName === '' ||
        $purchaseDate === '' ||
        $category === '' ||
        $amount <= 0 ||
        !preg_match('/^\d{4}-\d{2}-\d{2}$/', $purchaseDate) ||
        !in_array($branchId, $accessibleBranches, true)
    ) {
        $message = 'Please fill all required fields correctly.';
    } else {
        try {
            $stmt = $pdo->prepare("
                INSERT INTO expenses (branch_id, supplier, item_name, category, purchase_date, amount, notes)
                VALUES (?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([$branchId, $supplier, $itemName, $category, $purchaseDate, $amount, $notes]);

            $expenseId = (int)$pdo->lastInsertId();
            logAudit(
                $pdo,
                'EXPENSE CREATED',
                'expenses',
                $expenseId,
                $branchId,
                "Expense added: {$itemName} (Rs. {$amount})"
            );

            $message = 'Expense added successfully.';
            $success = true;
            $selectedBranch = (string)$branchId;
        } catch (Throwable $e) {
            $message = 'Database error: ' . $e->getMessage();
        }
    }
}

$branchStmt = $pdo->prepare("
    SELECT id, branch_name
    FROM branches
    WHERE id IN (" . implode(',', array_fill(0, count($accessibleBranches), '?')) . ")
    ORDER BY branch_name
");
$branchStmt->execute($accessibleBranches);
$branches = $branchStmt->fetchAll(PDO::FETCH_ASSOC);

include '../includes/header.php';
?>

<section class="app-card p-4">
    <div class="page-toolbar">
        <div>
            <span class="app-eyebrow">Expenses</span>
            <h2 class="mb-1">Add expense</h2>
            <p class="text-muted mb-0">Capture a branch expense cleanly without leaving the modernized admin workflow.</p>
        </div>
        <a href="/pages/expenses.php" class="btn btn-outline-secondary rounded-pill px-4">Back to Ledger</a>
    </div>

    <?php if ($message): ?>
        <div class="alert <?= $success ? 'alert-success' : 'alert-danger' ?> border-0 rounded-4"><?= htmlspecialchars($message) ?></div>
    <?php endif; ?>

    <form method="POST" class="stack-form" autocomplete="off" id="expenseForm">
        <?= csrfField() ?>
        <div class="form-grid">
            <div>
                <label class="form-label fw-semibold">Branch</label>
                <select class="form-select" name="branch_id" required>
                    <option value="">Select branch</option>
                    <?php foreach ($branches as $branch): ?>
                        <option value="<?= (int)$branch['id'] ?>" <?= $selectedBranch === (string)$branch['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($branch['branch_name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label class="form-label fw-semibold">Supplier</label>
                <input class="form-control" list="supplier-list" name="supplier" id="supplier" required placeholder="Start typing supplier name">
                <datalist id="supplier-list">
                    <?php foreach ($suppliers as $supplier): ?>
                        <option value="<?= htmlspecialchars($supplier) ?>"></option>
                    <?php endforeach; ?>
                </datalist>
            </div>
            <div>
                <label class="form-label fw-semibold">Item / Service</label>
                <input class="form-control" type="text" name="item_name" required>
            </div>
            <div>
                <label class="form-label fw-semibold">Category</label>
                <select class="form-select" name="category" required>
                    <option value="">Select category</option>
                    <option value="Bills">Bills</option>
                    <option value="Chemicals">Chemicals</option>
                    <option value="Salary">Salary</option>
                    <option value="Other Expenses">Other Expenses</option>
                </select>
            </div>
            <div>
                <label class="form-label fw-semibold">Purchase / Paid Date</label>
                <input class="form-control" type="date" name="purchase_date" value="<?= date('Y-m-d') ?>" required>
            </div>
            <div>
                <label class="form-label fw-semibold">Amount</label>
                <input class="form-control" type="number" name="amount" min="0.01" step="0.01" required>
            </div>
        </div>

        <div>
            <label class="form-label fw-semibold">Notes</label>
            <textarea class="form-control" name="notes" rows="4" placeholder="Optional notes or invoice reference"></textarea>
        </div>

        <div class="d-flex gap-2 flex-wrap">
            <button type="submit" class="btn btn-retro">Save Expense</button>
            <a href="/pages/expenses.php" class="btn btn-outline-secondary rounded-pill px-4">Cancel</a>
        </div>
    </form>
</section>

<script>
(function () {
    try {
        const lastSupplier = localStorage.getItem('last_supplier');
        const supplierInput = document.getElementById('supplier');
        if (lastSupplier && supplierInput && !supplierInput.value) {
            supplierInput.value = lastSupplier;
        }

        document.getElementById('expenseForm').addEventListener('submit', function () {
            const supplier = (supplierInput.value || '').trim();
            if (supplier) {
                localStorage.setItem('last_supplier', supplier);
            }
        });
    } catch (error) {
        // Ignore localStorage failures.
    }
})();
</script>

<?php include '../includes/footer.php'; ?>
