<?php
session_start();
if (!isset($_SESSION['logged_in'])) {
    header('Location: login.php');
    exit;
}

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/helpers.php';

// Check Permission
if (!can('expenses', 'view')) {
    die('Access Denied');
}

$message = '';

// Handle Adding New Category
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_category'])) {
    $name = trim($_POST['expense_name'] ?? '');
    $desc = trim($_POST['description'] ?? '');
    
    if ($name) {
        $stmt = $pdo->prepare("INSERT INTO expenses (expense_name, description, status) VALUES (?, ?, 'active')");
        $stmt->execute([$name, $desc]);
        $message = "Category added successfully.";
    }
}

// Handle Status Toggle (Active/Inactive)
if (isset($_GET['toggle_id'])) {
    $id = $_GET['toggle_id'];
    $current_status = $_GET['current'];
    $new_status = ($current_status == 'active') ? 'inactive' : 'active';
    
    $stmt = $pdo->prepare("UPDATE expenses SET status = ? WHERE expense_id = ?");
    $stmt->execute([$new_status, $id]);
    header("Location: expense_types.php");
    exit;
}

// Fetch all expense categories
$categories = $pdo->query("SELECT * FROM expenses ORDER BY expense_name ASC")->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Expense Categories</title>
    <link href="../assets/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="../assets/font-awesome/css/all.min.css">
    <style>
        body { background:#f8fafc; font-family:'Inter', sans-serif; }
        .main-card { background:#fff; border-radius:12px; border:1px solid #e2e8f0; }
        .badge-active { background:#dcfce7; color:#15803d; }
        .badge-inactive { background:#fee2e2; color:#b91c1c; }
    </style>
</head>
<body>

<div class="container py-5">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3 class="fw-bold m-0 text-dark">Expense Categories</h3>
        <div class="d-flex gap-2">
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addModal">
                <i class="fas fa-plus me-2"></i>New Category
            </button>
            <a href="expenses.php" class="btn btn-outline-secondary">Back to Transactions</a>
        </div>
    </div>

    <?php if ($message): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <?= $message ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div class="main-card shadow-sm">
        <table class="table table-hover align-middle mb-0">
            <thead class="table-light">
                <tr>
                    <th class="ps-4">Category Name</th>
                    <th>Description</th>
                    <th>Created At</th>
                    <th class="text-center">Status</th>
                    <th class="text-center pe-4">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($categories as $cat): ?>
                <tr>
                    <td class="ps-4 fw-bold"><?= htmlspecialchars($cat['expense_name']) ?></td>
                    <td class="text-muted small"><?= htmlspecialchars($cat['description']) ?></td>
                    <td class="small"><?= date('d/m/Y', strtotime($cat['created_at'])) ?></td>
                    <td class="text-center">
                        <span class="badge <?= $cat['status'] == 'active' ? 'badge-active' : 'badge-inactive' ?>">
                            <?= ucfirst($cat['status']) ?>
                        </span>
                    </td>
                    <td class="text-center pe-4">
                        <a href="expense_types.php?toggle_id=<?= $cat['expense_id'] ?>&current=<?= $cat['status'] ?>" 
                           class="btn btn-sm <?= $cat['status'] == 'active' ? 'btn-outline-danger' : 'btn-outline-success' ?>"
                           title="Change Status">
                            <i class="fas <?= $cat['status'] == 'active' ? 'fa-ban' : 'fa-check' ?>"></i>
                        </a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<div class="modal fade" id="addModal" tabindex="-1">
    <div class="modal-dialog">
        <form method="POST" class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add New Category</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label fw-bold">Category Name</label>
                    <input type="text" name="expense_name" class="form-control" placeholder="e.g. Office Rent" required>
                </div>
                <div class="mb-3">
                    <label class="form-label fw-bold">Description</label>
                    <textarea name="description" class="form-control" rows="3" placeholder="Optional details..."></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="submit" name="add_category" class="btn btn-primary">Save Category</button>
            </div>
        </form>
    </div>
</div>

<script src="../assets/js/bootstrap.bundle.min.js"></script>
</body>
</html>