<?php
require_once __DIR__ . '/../library/auth.php'; 
$school_id = $_SESSION['school_id'];
allow_roles(['admin', 'accountant']);

// ======================================================
// ADD CATEGORY
// ======================================================

if (isset($_POST['add_category'])) {

    $name = trim($_POST['name']);

    // Duplicate Check
    $check = $pdo->prepare("
        SELECT id 
        FROM expense_categories 
        WHERE school_id = ? AND name = ?
    ");

    $check->execute([$school_id, $name]);

    if ($check->rowCount() > 0) {

        header("Location: expense_category.php?msg=⚠️ Category Already Exists!");
        exit;
    }

    // Insert Category
    $stmt = $pdo->prepare("
        INSERT INTO expense_categories (school_id, name) 
        VALUES (?, ?)
    ");

    $stmt->execute([$school_id, $name]);

    header("Location: expense_category.php?msg=✅ Category Added!");
    exit;
}


// ======================================================
// DELETE CATEGORY
// ======================================================

if (isset($_GET['delete'])) {

    $stmt = $pdo->prepare("
        DELETE FROM expense_categories 
        WHERE id = ? AND school_id = ?
    ");

    $stmt->execute([$_GET['delete'], $school_id]);

    header("Location: expense_category.php?msg=🗑️ Category Deleted!");
    exit;
}


// ======================================================
// EDIT CATEGORY
// ======================================================

$edit_data = null;

if (isset($_GET['edit'])) {

    $stmt = $pdo->prepare("
        SELECT * 
        FROM expense_categories 
        WHERE id = ? AND school_id = ?
    ");

    $stmt->execute([$_GET['edit'], $school_id]);

    $edit_data = $stmt->fetch(PDO::FETCH_ASSOC);
}


// ======================================================
// UPDATE CATEGORY
// ======================================================

if (isset($_POST['update_category'])) {

    $name = trim($_POST['name']);

    // Duplicate Check
    $check = $pdo->prepare("
        SELECT id 
        FROM expense_categories 
        WHERE school_id = ? 
        AND name = ?
        AND id != ?
    ");

    $check->execute([
        $school_id,
        $name,
        $_POST['id']
    ]);

    if ($check->rowCount() > 0) {

        header("Location: expense_category.php?msg=⚠️ Category Already Exists!");
        exit;
    }

    // Update Query
    $stmt = $pdo->prepare("
        UPDATE expense_categories 
        SET name = ?
        WHERE id = ? AND school_id = ?
    ");

    $stmt->execute([
        $name,
        $_POST['id'],
        $school_id
    ]);

    header("Location: expense_category.php?msg=🔄 Category Updated!");
    exit;
}


// ======================================================
// FETCH ALL CATEGORIES
// ======================================================

$stmt = $pdo->prepare("
    SELECT * 
    FROM expense_categories 
    WHERE school_id = ?
    ORDER BY id DESC
");

$stmt->execute([$school_id]);

$categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
$page_title = 'Expense Categories';
require_once __DIR__ . '/../include/header.php';
require_once __DIR__ . '/../include/sidebar.php';

?>

<div class="content-wrapper">
    <section class="content-header"><h1>Manage Expense Categories</h1></section>
    <section class="content">
        <div class="container-fluid">
            <?php if(isset($_GET['msg'])): ?>
                <div class="alert alert-success"><?= htmlspecialchars($_GET['msg']) ?></div>
            <?php endif; ?>

            <div class="row">
                <!-- Form Add/Edit -->
                <div class="col-md-4">
                    <div class="card">
                        <div class="card-header bg-danger text-white">
                            <h5><?= $edit_data ? 'Edit Category' : 'Add New Category' ?></h5>
                        </div>
                        <div class="card-body">
                            <form method="POST">
                                <?php if($edit_data): ?> <input type="hidden" name="id" value="<?= $edit_data['id'] ?>"> <?php endif; ?>
                                <div class="form-group">
                                    <label>Category Name</label>
                                    <input type="text" name="name" class="form-control" value="<?= $edit_data['name'] ?? '' ?>" required>
                                </div>
                                <button type="submit" name="<?= $edit_data ? 'update_category' : 'add_category' ?>" class="btn btn-danger btn-block">
                                    <?= $edit_data ? 'Update' : 'Save' ?>
                                </button>
                                <?php if($edit_data): ?> <a href="expense_category.php" class="btn btn-default btn-block">Cancel</a> <?php endif; ?>
                            </form>
                        </div>
                    </div>
                </div>

                <!-- View List -->
                <div class="col-md-8">
                    <div class="card">
                        <div class="card-body">
                            <table class="table table-bordered">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Name</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach($categories as $cat): ?>
                                    <tr>
                                        <td><?= $cat['id'] ?></td>
                                        <td><?= $cat['name'] ?></td>
                                        <td>
                                            <a href="expense_category.php?edit=<?= $cat['id'] ?>" class="btn btn-sm btn-warning"><i class="fa fa-edit"></i></a>
                                            <a href="expense_category.php?delete=<?= $cat['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Sure?')"><i class="fa fa-trash"></i></a>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

<?php require_once __DIR__ . '/../include/footer.php'; ?>