<?php
session_start();
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Logger.php';
require_once __DIR__ . '/../../classes/Expense.php';
require_once __DIR__ . '/../../classes/Branch.php';


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


$auth = new Auth($conn);


if (!isset($_SESSION['user_id'])) {
    header('Location: ../../login.php');
    exit();
}
$auth->enforceSuperAdminPrivileges($_SESSION['user_id']);


$logger = new Logger($conn, $_SESSION['user_id'], $_SESSION['username'], $_SESSION['role']);


$expense = new Expense($conn, $logger);
$branch = new Branch($conn);


$expense_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$expense_id) {
    header('Location: manage_expenses.php');
    exit();
}


$categories = $expense->getAllCategories();


$branches = $branch->getAllBranches();


$expense->expense_id = $expense_id;
if (!$expense->read()) {
    header('Location: manage_expenses.php');
    exit();
}


$expense_category_id = $expense->expense_category_id;
$description = $expense->description;
$amount = $expense->amount;
$expense_date = $expense->expense_date;
$branch_id = $expense->branch_id;
$errors = [];
$success_message = '';


if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $expense_category_id = trim($_POST['expense_category_id'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $amount = trim($_POST['amount'] ?? '');
    $expense_date = trim($_POST['expense_date'] ?? '');
    $branch_id = trim($_POST['branch_id'] ?? '');


    if (empty($expense_category_id)) {
        $errors[] = 'Expense category is required';
    }

    if (empty($description)) {
        $errors[] = 'Description is required';
    }

    if (empty($amount)) {
        $errors[] = 'Amount is required';
    } elseif (!is_numeric($amount) || $amount <= 0) {
        $errors[] = 'Amount must be a positive number';
    }

    if (empty($expense_date)) {
        $errors[] = 'Expense date is required';
    } elseif (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $expense_date)) {
        $errors[] = 'Expense date must be in YYYY-MM-DD format';
    }


    if (empty($errors)) {
        $expense->expense_category_id = $expense_category_id;
        $expense->description = $description;
        $expense->amount = $amount;
        $expense->expense_date = $expense_date;
        $expense->branch_id = $branch_id ?: null;

        if ($expense->update()) {
            $success_message = 'Expense updated successfully!';
        } else {
            $errors[] = 'Failed to update expense. Please try again.';
        }
    }
}
?>

<?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="manage_expenses.php" class="btn btn-secondary">
                    <i class="fas fa-arrow-left"></i> Back to Expenses
                </a>
            </div>
        </div>

        <div class="card">
            <div class="card-header bg-primary text-white">
                <h2 class="mb-0">Edit Expense</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="">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="expense_category_id">Expense Category <span class="text-danger">*</span></label>
                                <select class="form-control" id="expense_category_id" name="expense_category_id" required>
                                    <option value="">Select Category</option>
                                    <?php while ($category = $categories->fetch(PDO::FETCH_ASSOC)): ?>
                                        <option value="<?php echo htmlspecialchars($category['category_id']); ?>" <?php echo ($expense_category_id == $category['category_id']) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($category['category_name']); ?>
                                        </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>

                            <div class="form-group">
                                <label for="description">Description <span class="text-danger">*</span></label>
                                <textarea class="form-control" id="description" name="description" rows="3" required><?php echo htmlspecialchars($description); ?></textarea>
                            </div>
                        </div>

                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="amount">Amount <span class="text-danger">*</span></label>
                                <div class="input-group">
                                    <span class="input-group-text">$</span>
                                    <input type="number" class="form-control" id="amount" name="amount" step="0.01" min="0.01" value="<?php echo htmlspecialchars($amount); ?>" required>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="expense_date">Expense Date <span class="text-danger">*</span></label>
                                <input type="date" class="form-control" id="expense_date" name="expense_date" value="<?php echo htmlspecialchars($expense_date); ?>" required>
                            </div>

                            <div class="form-group">
                                <label for="branch_id">Branch (Optional)</label>
                                <select class="form-control" id="branch_id" name="branch_id">
                                    <option value="">Select Branch</option>
                                    <?php while ($branch_item = $branches->fetch(PDO::FETCH_ASSOC)): ?>
                                        <option value="<?php echo htmlspecialchars($branch_item['branch_id']); ?>" <?php echo ($branch_id == $branch_item['branch_id']) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($branch_item['branch_name']); ?>
                                        </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div class="mt-4">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i> Update Expense
                        </button>
                        <a href="manage_expenses.php" class="btn btn-secondary">
                            <i class="fas fa-times"></i> Cancel
                        </a>
                    </div>
                </form>
            </div>
        </div>
    </div>

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