<?php
include 'layouts/session.php';
include 'layouts/dbconn.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get form data
    $expense_id = intval($_POST['expense_id']);
    $description = $_POST['description'] ?? '';
    $amount = $_POST['amount'] ?? 0;
    $currency = $_POST['currency'] ?? 'TZS';
    $office_cost = $_POST['expense_type'] ?? ''; // Using expense_type as office_cost
    $pay_mode = $_POST['payment_method'] ?? ''; // Using payment_method as pay_mode
    $file_number = $_POST['reference_number'] ?? null; // Using reference_number as file_number
    
    // Get expense date from form
    $expense_date = !empty($_POST['expense_date']) ? date('Y-m-d H:i:s', strtotime($_POST['expense_date'])) : date('Y-m-d H:i:s');
    
    // Validate the essential inputs
    $errors = [];
    
    if (empty($office_cost)) {
        $errors[] = "Expense type is required";
    }
    
    if (empty($amount) || !is_numeric($amount)) {
        $errors[] = "Valid amount is required";
    }
    
    if (empty($pay_mode)) {
        $errors[] = "Payment method is required";
    }
    
    // If there are validation errors
    if (!empty($errors)) {
        $_SESSION['sweet_alert'] = [
            'title' => 'Error!',
            'text' => "Please correct the following errors:<br>" . implode("<br>", $errors),
            'icon' => 'error'
        ];
        header("Location: edit_expense.php?id=$expense_id");
        exit();
    }
    
    try {
        // Get the current expense info for audit
        $select_stmt = $conn->prepare("SELECT * FROM expenses WHERE id = ?");
        $select_stmt->bind_param("i", $expense_id);
        $select_stmt->execute();
        $old_expense = $select_stmt->get_result()->fetch_assoc();
        $select_stmt->close();
        
        // Prepare SQL statement for update
        $stmt = $conn->prepare("UPDATE expenses SET 
            currency = ?, 
            description = ?, 
            office_cost = ?, 
            pay_mode = ?, 
            file_number = ?, 
            amount = ?,
            created_date = ?
            WHERE id = ?");
        
        // Corrected bind_param call with the right number of parameters
        $stmt->bind_param("sssssdsi", 
            $currency, 
            $description, 
            $office_cost, 
            $pay_mode, 
            $file_number, 
            $amount,
            $expense_date,
            $expense_id
        );
        
        if ($stmt->execute()) {
            // Log the update in audit log (if you have one)
            // logAuditAction('expense_update', 'Updated expense ID: ' . $expense_id, $old_expense, $_POST);
            
            $_SESSION['sweet_alert'] = [
                'title' => 'Success!',
                'text' => "Expense has been updated successfully.",
                'icon' => 'success'
            ];
        } else {
            $_SESSION['sweet_alert'] = [
                'title' => 'Error!',
                'text' => "Failed to update expense: " . $stmt->error,
                'icon' => 'error'
            ];
        }
        
        $stmt->close();
    } catch (Exception $e) {
        $_SESSION['sweet_alert'] = [
            'title' => 'Error!',
            'text' => "An exception occurred: " . $e->getMessage(),
            'icon' => 'error'
        ];
    }
    
    // Redirect back to expense list
    header("Location: all_expenses.php");
    exit();
}
?>