<?php
session_start();

header('Content-Type: application/json');

if (!isset($_SESSION['role_id']) || !in_array($_SESSION['role_id'], [1, 3, 4])) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

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

$id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);
$amount = filter_input(INPUT_POST, 'amount', FILTER_VALIDATE_FLOAT);
$description = trim($_POST['description'] ?? '');
$category_id = filter_input(INPUT_POST, 'category_id', FILTER_VALIDATE_INT);

// Basic validation
if (!$id || !$amount || $amount <= 0 || !$category_id) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid input data.']);
    exit;
}

try {
    $stmt = $conn->prepare("
        UPDATE expenses
        SET amount = ?, description = ?, expense_category_id = ?, updated_at = NOW()
        WHERE id = ?
    ");
    if (!$stmt) {
        throw new Exception('Prepare failed: ' . $conn->error);
    }

    $stmt->bind_param("dsii", $amount, $description, $category_id, $id);

    if (!$stmt->execute()) {
        throw new Exception('Execute failed: ' . $stmt->error);
    }

    echo json_encode(['success' => true, 'message' => 'Expense updated successfully.']);

    $stmt->close();
    $conn->close();

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
