<?php

ob_start();

session_start();
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Expense.php';


$database = new Database();
$conn = $database->getConnection();


$auth = new Auth($conn);

$auth->enforceSuperAdminPrivileges($_SESSION['user_id']);


$expense = new Expense($conn);


$category_id = isset($_GET['id']) ? (int)$_GET['id'] : null;
$category_name = '';
$description = '';
$errors = [];
$success_message = '';
$is_edit = false;


if ($category_id) {
    $query = "SELECT * FROM expense_categories WHERE category_id = :category_id";
    $stmt = $conn->prepare($query);
    $stmt->bindParam(':category_id', $category_id);
    $stmt->execute();
    $category = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($category) {
        $is_edit = true;
        $category_name = $category['category_name'];
        $description = $category['description'] ?? '';
    } else {
        $errors[] = 'Category not found.';
    }
}


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $category_name = trim($_POST['category_name'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $category_id = trim($_POST['category_id'] ?? '');


    if (empty($category_name)) {
        $errors[] = 'Category name is required';
    } elseif (strlen($category_name) > 100) {
        $errors[] = 'Category name must be 100 characters or less';
    }


    if (empty($errors)) {
        if ($category_id) {

            if ($expense->updateCategory($category_id, $category_name, $description)) {
                $success_message = 'Category updated successfully!';
            } else {
                $errors[] = 'Failed to update category. The category name may already exist.';
            }
        } else {

            if ($expense->createCategory($category_name, $description)) {
                $success_message = 'Category added successfully!';

                $category_name = '';
                $description = '';
            } else {
                $errors[] = 'Failed to add category. The category name may already exist.';
            }
        }
    }
}


if (isset($_GET['delete']) && $category_id) {
    if ($expense->deleteCategory($category_id)) {

        ob_end_clean();
        header('Location: manage_categories.php?success=Category deleted successfully');
        exit();
    } else {
        $errors[] = 'Failed to delete category. It may be in use by existing expenses.';
    }
}


ob_end_clean();
?>

<?php include __DIR__ . '/../../includes/header.php'; ?>
<style>
    .card {
        margin-bottom: 20px;
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    }
    .form-group {
        margin-bottom: 1rem;
    }
</style>
    <div class="container mt-4">
        <div class="row mb-3">
            <div class="col-auto">
                <a href="expense_categories.php" class="btn btn-secondary">
                    <i class="fas fa-arrow-left"></i> Back to Categories
                </a>
            </div>
        </div>

        <div class="card">
            <div class="card-header bg-primary text-white">
                <h2 class="mb-0"><?php echo $is_edit ? 'Edit Expense Category' : 'Add New Expense Category'; ?></h2>
            </div>
            <div class="card-body">
                <?php if ($success_message): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <?php echo htmlspecialchars($success_message); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>

                <?php if (!empty($errors)): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <ul class="mb-0">
                            <?php foreach ($errors as $error): ?>
                                <li><?php echo htmlspecialchars($error); ?></li>
                            <?php endforeach; ?>
                        </ul>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>

                <form method="post" action="">
                    <input type="hidden" name="category_id" value="<?php echo htmlspecialchars($category_id); ?>">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="category_name">Category Name <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="category_name" name="category_name" value="<?php echo htmlspecialchars($category_name); ?>" required maxlength="100">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="description">Description (Optional)</label>
                                <textarea class="form-control" id="description" name="description" rows="3"><?php echo htmlspecialchars($description); ?></textarea>
                            </div>
                        </div>
                    </div>

                    <div class="mt-4">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i> Save Category
                        </button>
                        <a href="manage_categories.php" class="btn btn-secondary">
                            <i class="fas fa-times"></i> Cancel
                        </a>
                        <?php if ($is_edit): ?>
                            <a href="javascript:void(0);" onclick="confirmDelete(<?php echo $category_id; ?>)" class="btn btn-danger">
                                <i class="fas fa-trash"></i> Delete Category
                            </a>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        function confirmDelete(id) {
            if (confirm('Are you sure you want to delete this category?')) {
                window.location.href = `?delete=1&id=${id}`;
            }
        }
    </script>
<?php include __DIR__ . '/../../includes/footer.php'; ?>