<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/sonicpesa.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

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

if (!is_logged_in()) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);
$apiKey = trim($input['api_key'] ?? '');

if (empty($apiKey)) {
    echo json_encode(['success' => false, 'message' => 'Please enter an API Key first']);
    exit;
}

$res = sonicpesa_list_transactions($apiKey);

$status = $res['data']['status'] ?? '';
if ($res['code'] === 200 && ($status === 'success' || ($res['data']['success'] ?? false))) {
    $accountName = 'SonicPesa User';
    $balance = $res['data']['data']['balance'] ?? '0';
    echo json_encode([
        'success' => true, 
        'message' => "Connected! Account: $accountName | Balance: $balance"
    ]);
} else {
    $error = $res['data']['message'] ?? 'Connection failed. Please check your token.';
    if ($res['code'] === 401) $error = "Invalid API Key (Unauthorised)";
    echo json_encode(['success' => false, 'message' => $error]);
}

