<?php
require_once("../../autoloader.php");
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");

// SIMPLE LOG FUNCTION
function log_api($title, $data) {
    $logPath = __DIR__ . "/log.txt";
    $entry = "\n-------------------------------\n";
    $entry .= date("Y-m-d H:i:s") . " - $title\n";
    $entry .= print_r($data, true);
    file_put_contents($logPath, $entry, FILE_APPEND);
}

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

$controller = new SubscriberModel();
date_default_timezone_set('Africa/Lagos');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(["status" => "error", "message" => "Method not allowed"]);
    exit();
}

// Read JSON input or POST
$input = json_decode(file_get_contents('php://input'), true);
if (!$input) $input = $_POST;

// LOG INPUT
log_api("INPUT", $input);

$user_id = $input['user_id'] ?? null;
if (!$user_id || !is_numeric($user_id)) {
    $resp = ["status" => "error", "message" => "Valid user_id is required"];

    // LOG OUTPUT
    log_api("OUTPUT", $resp);

    http_response_code(400);
    echo json_encode($resp);
    exit();
}

// Build options from input
$options = [
    'page'         => max(1, (int)($input['page'] ?? 1)),
    'per_page'     => min(500, max(10, (int)($input['per_page'] ?? 50))),
    'start_date'   => $input['start_date'] ?? null,
    'end_date'     => $input['end_date'] ?? null,
    'servicename'  => $input['servicename'] ?? null,
    'status'       => $input['status'] ?? null,
    'transref'     => $input['transref'] ?? null,
    'search'       => $input['search'] ?? null,
    'sort_by'      => $input['sort_by'] ?? 'date',
    'sort_order'   => $input['sort_order'] ?? 'DESC',
    'with_analysis'=> filter_var($input['with_analysis'] ?? false, FILTER_VALIDATE_BOOLEAN)
];

$result = $controller->getUserTransactionOptions((int)$user_id, $options);

if (isset($result['error'])) {
    $resp = ["status" => "error", "message" => $result['error']];

    // LOG OUTPUT
    log_api("OUTPUT", $resp);

    http_response_code(500);
    echo json_encode($resp);
} else {
    $resp = [
        "status" => "success",
        "data" => $result['data'],
        "pagination" => $result['pagination'],
        "analysis" => $result['analysis']
    ];

    // LOG OUTPUT
    log_api("OUTPUT", $resp);

    echo json_encode($resp);
}
