<?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/Transaction.php';

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

$transaction = new Transaction();

if ($method === 'POST' && $action === 'create') {
    $data = json_decode(file_get_contents("php://input"), true);
    
    // Generate transaction ID if not provided
    if (!isset($data['id'])) {
        $data['id'] = 'INV-' . time();
    }
    
    // Ensure date is set
    if (!isset($data['date'])) {
        $data['date'] = date('Y-m-d H:i:s');
    }
    
    $result = $transaction->createTransaction($data);
    echo json_encode($result);
} else if ($method === 'GET' && $action === 'get') {
    $id = isset($_GET['id']) ? $_GET['id'] : '';
    $trans = $transaction->getTransaction($id);
    
    if ($trans) {
        echo json_encode($trans);
    } else {
        http_response_code(404);
        echo json_encode(['error' => 'Transaction not found']);
    }
} else 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['status'])) $filters['status'] = $_GET['status'];
    if (isset($_GET['customer_id'])) $filters['customer_id'] = $_GET['customer_id'];
    
    $transactions = $transaction->getAllTransactions($filters);
    echo json_encode($transactions);
} else if ($method === 'GET' && $action === 'sales_stats') {
    $start_date = isset($_GET['start_date']) ? $_GET['start_date'] : null;
    $end_date = isset($_GET['end_date']) ? $_GET['end_date'] : null;
    
    $stats = $transaction->getSalesStats($start_date, $end_date);
    echo json_encode($stats);
} else {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid action']);
}
?>
