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

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Generate a unique expense number
    $exp_no = "EXP-" . date('YmdHis') . "-" . rand(100, 999);
    
    // Get form data
    $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
    $user_id = $_SESSION['user_id'];
    $status = 'Pending'; // Default status
    
    // 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['error_msg'] = "Please correct the following errors:<br>" . implode("<br>", $errors);
        header("Location: add_expense.php");
        exit();
    }
    
    try {
        // Prepare SQL statement that matches your database schema
        $stmt = $conn->prepare("INSERT INTO expenses (exp_no, status, currency, description, office_cost, user_id, pay_mode, file_number, amount, created_date) 
                               VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        
        $stmt->bind_param("sssssissds", 
            $exp_no, 
            $status, 
            $currency, 
            $description, 
            $office_cost, 
            $user_id, 
            $pay_mode, 
            $file_number, 
            $amount,
            $expense_date
        );
        
        if ($stmt->execute()) {
            $_SESSION['success_msg'] = "Expense saved successfully";
            
            // Add script to show SweetAlert
            $_SESSION['sweet_alert'] = [
                'title' => 'Success!',
                'text' => "Expense $exp_no has been saved successfully.",
                'icon' => 'success'
            ];
        } else {
            $_SESSION['error_msg'] = "Error saving expense: " . $stmt->error;
            
            // Add script to show SweetAlert
            $_SESSION['sweet_alert'] = [
                'title' => 'Error!',
                'text' => "Failed to save expense: " . $stmt->error,
                'icon' => 'error'
            ];
        }
        
        $stmt->close();
    } catch (Exception $e) {
        $_SESSION['error_msg'] = "Error: " . $e->getMessage();
        
        // Add script to show SweetAlert
        $_SESSION['sweet_alert'] = [
            'title' => 'Error!',
            'text' => "An exception occurred: " . $e->getMessage(),
            'icon' => 'error'
        ];
    }
    
    // Redirect back to expense list
    header("Location: all_expenses.php");
    exit();
}
?>