<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header("Content-Type: application/json; charset=UTF-8");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

require_once __DIR__ . '/../config/Database.php';
require_once __DIR__ . '/../models/Expense.php';

$method = $_SERVER['REQUEST_METHOD'];
$action = isset($_GET['action']) ? $_GET['action'] : '';

$expense = new Expense();

if ($method === 'GET' && $action === 'get_all') {
    $filters = [];
    if (isset($_GET['start_date'])) $filters['start_date'] = $_GET['start_date'];
    if (isset($_GET['end_date'])) $filters['end_date'] = $_GET['end_date'];
    if (isset($_GET['category'])) $filters['category'] = $_GET['category'];
    
    $expenses = $expense->getAllExpenses($filters);
    echo json_encode($expenses);
} else if ($method === 'POST' && $action === 'create') {
    $data = json_decode(file_get_contents("php://input"), true);
    
    if (!isset($data['id'])) {
        $data['id'] = 'EXP-' . time();
    }
    
    if ($expense->createExpense($data)) {
        echo json_encode(['success' => true, 'message' => 'Expense created']);
    } else {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to create expense']);
    }
} else if ($method === 'PUT' && $action === 'update') {
    $id = isset($_GET['id']) ? $_GET['id'] : '';
    $data = json_decode(file_get_contents("php://input"), true);
    
    if ($expense->updateExpense($id, $data)) {
        echo json_encode(['success' => true, 'message' => 'Expense updated']);
    } else {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to update expense']);
    }
} else if ($method === 'GET' && $action === 'stats') {
    $start_date = isset($_GET['start_date']) ? $_GET['start_date'] : null;
    $end_date = isset($_GET['end_date']) ? $_GET['end_date'] : null;
    
    $stats = $expense->getExpenseStats($start_date, $end_date);
    echo json_encode($stats);
} else if ($method === 'GET' && $action === 'total') {
    $start_date = isset($_GET['start_date']) ? $_GET['start_date'] : null;
    $end_date = isset($_GET['end_date']) ? $_GET['end_date'] : null;
    
    $total = $expense->getTotalExpenses($start_date, $end_date);
    echo json_encode(['total' => $total]);
} else {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid action']);
}
?>
