<?php include 'layouts/session.php'; ?>
<?php include 'layouts/main.php'; ?>
<?php include 'layouts/dbconn.php'; ?>

<?php
// Check if ID parameter exists
if (!isset($_GET['id']) || empty($_GET['id'])) {
    $_SESSION['sweet_alert'] = [
        'title' => 'Error!',
        'text' => "No expense ID provided",
        'icon' => 'error'
    ];
    header('Location: all_expenses.php');
    exit();
}

$expense_id = intval($_GET['id']);

// Fetch expense details
$query = "SELECT * FROM expenses WHERE id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $expense_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $_SESSION['sweet_alert'] = [
        'title' => 'Error!',
        'text' => "Expense not found",
        'icon' => 'error'
    ];
    header('Location: all_expenses.php');
    exit();
}

$expense = $result->fetch_assoc();
$stmt->close();
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Edit Expense')); ?>
    
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <?php include 'layouts/head-css.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>

<body>
    <!-- Begin page -->
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <!-- ============================================================== -->
        <!-- Start right Content here -->
        <!-- ============================================================== -->
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Expenses Management', 'title' => 'Edit Expense')); ?>
            
                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h4 class="card-title mb-0">Edit Expense</h4>
                                    <?php if ($_SESSION['role_id'] == 1): ?>
                                    <div>
                                        <button type="button" class="btn btn-success" onclick="approveExpense(<?php echo $expense_id; ?>)">
                                            <i class="ri-check-line"></i> Approve
                                        </button>
                                        <button type="button" class="btn btn-danger" onclick="rejectExpense(<?php echo $expense_id; ?>)">
                                            <i class="ri-close-line"></i> Reject
                                        </button>
                                    </div>
                                    <?php endif; ?>
                                </div>
                                <div class="card-body">
                                    <form id="editExpenseForm" method="POST" action="update_expense.php">
                                        <input type="hidden" name="expense_id" value="<?php echo $expense_id; ?>">
                                        
                                        <div class="row gy-4">
                                            <div class="col-md-6">
                                                <div class="mb-3">
                                                    <label for="expense_type" class="form-label">Expense Type</label>
                                                    <select class="form-select" id="expense_type" name="expense_type" required>
                                                        <option value="">Select Type</option>
                                                        <option value="fuel" <?php echo ($expense['office_cost'] == 'fuel') ? 'selected' : ''; ?>>Fuel</option>
                                                        <option value="maintenance" <?php echo ($expense['office_cost'] == 'maintenance') ? 'selected' : ''; ?>>Maintenance</option>
                                                        <option value="repairs" <?php echo ($expense['office_cost'] == 'repairs') ? 'selected' : ''; ?>>Repairs</option>
                                                        <option value="insurance" <?php echo ($expense['office_cost'] == 'insurance') ? 'selected' : ''; ?>>Insurance</option>
                                                        <option value="licenses" <?php echo ($expense['office_cost'] == 'licenses') ? 'selected' : ''; ?>>Licenses</option>
                                                        <option value="salaries" <?php echo ($expense['office_cost'] == 'salaries') ? 'selected' : ''; ?>>Salaries</option>
                                                        <option value="rent" <?php echo ($expense['office_cost'] == 'rent') ? 'selected' : ''; ?>>Rent</option>
                                                        <option value="utilities" <?php echo ($expense['office_cost'] == 'utilities') ? 'selected' : ''; ?>>Utilities</option>
                                                        <option value="office_supplies" <?php echo ($expense['office_cost'] == 'office_supplies') ? 'selected' : ''; ?>>Office Supplies</option>
                                                        <option value="travel" <?php echo ($expense['office_cost'] == 'travel') ? 'selected' : ''; ?>>Travel</option>
                                                        <option value="marketing" <?php echo ($expense['office_cost'] == 'marketing') ? 'selected' : ''; ?>>Marketing</option>
                                                        <option value="other" <?php echo ($expense['office_cost'] == 'other') ? 'selected' : ''; ?>>Other</option>
                                                    </select>
                                                </div>
                                                <div class="mb-3">
                                                    <label for="amount" class="form-label">Amount</label>
                                                    <input type="number" step="0.01" class="form-control" id="amount" name="amount" required value="<?php echo $expense['amount']; ?>">
                                                </div>
                                                <div class="mb-3">
                                                    <label for="currency" class="form-label">Currency</label>
                                                    <select class="form-select" id="currency" name="currency" required>
                                                        <option value="TZS" <?php echo ($expense['currency'] == 'TZS') ? 'selected' : ''; ?>>TZS</option>
                                                        <option value="USD" <?php echo ($expense['currency'] == 'USD') ? 'selected' : ''; ?>>USD</option>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="mb-3">
                                                    <label for="expense_date" class="form-label">Expense Date</label>
                                                    <input type="date" class="form-control" id="expense_date" name="expense_date" required 
                                                           value="<?php echo date('Y-m-d', strtotime($expense['created_date'])); ?>">
                                                </div>
                                                <div class="mb-3">
                                                    <label for="payment_method" class="form-label">Payment Method</label>
                                                    <select class="form-select" id="payment_method" name="payment_method" required>
                                                        <option value="cash" <?php echo ($expense['pay_mode'] == 'cash') ? 'selected' : ''; ?>>Cash</option>
                                                        <option value="bank_transfer" <?php echo ($expense['pay_mode'] == 'bank_transfer') ? 'selected' : ''; ?>>Bank Transfer</option>
                                                        <option value="mobile_money" <?php echo ($expense['pay_mode'] == 'mobile_money') ? 'selected' : ''; ?>>Mobile Money</option>
                                                        <option value="credit_card" <?php echo ($expense['pay_mode'] == 'credit_card') ? 'selected' : ''; ?>>Credit Card</option>
                                                        <option value="check" <?php echo ($expense['pay_mode'] == 'check') ? 'selected' : ''; ?>>Check</option>
                                                    </select>
                                                </div>
                                                <div class="mb-3">
                                                    <label for="reference_number" class="form-label">Reference Number</label>
                                                    <input type="text" class="form-control" id="reference_number" name="reference_number" value="<?php echo htmlspecialchars($expense['file_number'] ?? ''); ?>">
                                                </div>
                                            </div>
                                            <div class="col-12">
                                                <div class="mb-3">
                                                    <label for="description" class="form-label">Description</label>
                                                    <textarea class="form-control" id="description" name="description" rows="3"><?php echo htmlspecialchars($expense['description'] ?? ''); ?></textarea>
                                                </div>
                                            </div>
                                            <div class="col-12">
                                                <div class="d-flex">
                                                    <button type="submit" class="btn btn-primary me-2">Update Expense</button>
                                                    <a href="all_expenses.php" class="btn btn-secondary">Cancel</a>
                                                </div>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <?php include 'layouts/footer.php'; ?>
        </div>
        <!-- end main content-->
    </div>
    <!-- END layout-wrapper -->

    <?php include 'layouts/vendor-scripts.php'; ?>

    <script src="assets/libs/prismjs/prism.js"></script>
    <script src="assets/js/app.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script src="assets/js/pages/select2.init.js"></script>

    <script>
        function approveExpense(expenseId) {
            Swal.fire({
                title: 'Approve Expense',
                text: "Are you sure you want to approve this expense?",
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Yes, approve it!',
                cancelButtonText: 'No, cancel!',
                confirmButtonClass: 'btn btn-success mt-2',
                cancelButtonClass: 'btn btn-danger ms-2 mt-2',
                buttonsStyling: false
            }).then(function(result) {
                if (result.isConfirmed) {
                    window.location.href = 'change_expense_status.php?id=' + expenseId + '&status=Approved';
                }
            });
        }

        function rejectExpense(expenseId) {
            Swal.fire({
                title: 'Reject Expense',
                text: "Are you sure you want to reject this expense?",
                icon: 'warning',
                input: 'text',
                inputPlaceholder: 'Enter reason for rejection (optional)',
                inputAttributes: {
                    autocapitalize: 'off'
                },
                showCancelButton: true,
                confirmButtonText: 'Yes, reject it!',
                cancelButtonText: 'No, cancel!',
                confirmButtonClass: 'btn btn-danger mt-2',
                cancelButtonClass: 'btn btn-secondary ms-2 mt-2',
                buttonsStyling: false
            }).then(function(result) {
                if (result.isConfirmed) {
                    let reason = result.value || '';
                    window.location.href = 'change_expense_status.php?id=' + expenseId + '&status=Rejected&reason=' + encodeURIComponent(reason);
                }
            });
        }
    </script>
</body>
</html>