<?php
session_start();
header('Content-Type: application/json');

include_once('../../includes/config.php');

// Check if user is logged in
if (!isset($_SESSION['uid'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

$userId = $_SESSION['uid'];

// Get POST data
$expenseDate = $_POST['expenseDate'] ?? '';
$expenseCategory = $_POST['expenseCategory'] ?? '';
$expenseDescription = $_POST['expenseDescription'] ?? '';
$amount = $_POST['amount'] ?? 0;
$paymentMode = $_POST['paymentMode'] ?? 'Cash';
$reference = $_POST['reference'] ?? '';

// Validate required fields
if (empty($expenseDate) || empty($expenseCategory) || empty($amount) || $amount <= 0) {
    echo json_encode(['success' => false, 'message' => 'Please fill all required fields']);
    exit();
}

// Insert expense into database
$query = "INSERT INTO tblexpenses (ExpenseDate, ExpenseCategory, ExpenseDescription, Amount, PaymentMode, Reference, CreatedBy) 
          VALUES (?, ?, ?, ?, ?, ?, ?)";

$stmt = mysqli_prepare($con, $query);
mysqli_stmt_bind_param($stmt, 'sssdssi', $expenseDate, $expenseCategory, $expenseDescription, $amount, $paymentMode, $reference, $userId);

if (mysqli_stmt_execute($stmt)) {
    $expenseId = mysqli_insert_id($con);
    echo json_encode([
        'success' => true, 
        'message' => 'Expense registered successfully',
        'expenseId' => $expenseId
    ]);
} else {
    echo json_encode([
        'success' => false, 
        'message' => 'Failed to register expense: ' . mysqli_error($con)
    ]);
}

mysqli_stmt_close($stmt);
mysqli_close($con);
?>
