<?php
/**
 * Reseller API v1 - Router
 * 
 * Base URL: /api/v1/?action=ACTION&api_key=YOUR_KEY
 * All responses are JSON.
 */

ob_start();
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');

require_once __DIR__ . '/../../include/config.php';

// ── Helper: Clean JSON response ─────────────────────────────────────────────
function api_response($data, $http_code = 200) {
    ob_clean();
    http_response_code($http_code);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

// ── Check global API switch ─────────────────────────────────────────────────
$api_global = intval($site_data['api_enabled_global'] ?? 1);
if (!$api_global) {
    api_response(['status' => 'error', 'message' => 'API is currently disabled.'], 503);
}

// ── Get action ──────────────────────────────────────────────────────────────
$action = trim($_GET['action'] ?? $_POST['action'] ?? '');
if (empty($action)) {
    api_response(['status' => 'error', 'message' => 'Missing action parameter. See /api/v1/?action=help'], 400);
}

// ── Help / Docs endpoint (no auth required) ─────────────────────────────────
if ($action === 'help') {
    api_response([
        'status' => 'success',
        'message' => 'Reseller API v1',
        'endpoints' => [
            // Account
            'balance'          => 'GET ?action=balance&api_key=KEY',
            // Virtual Numbers (SMS)
            'sms_countries'    => 'GET ?action=sms_countries&api_key=KEY',
            'sms_services'     => 'GET ?action=sms_services&api_key=KEY&country_id=ID',
            'sms_buy'          => 'GET ?action=sms_buy&api_key=KEY&country_id=ID&service_id=SVC',
            'sms_check'        => 'GET ?action=sms_check&api_key=KEY&order_id=ORDERID',
            'sms_cancel'       => 'GET ?action=sms_cancel&api_key=KEY&order_id=ORDERID',
            'sms_history'      => 'GET ?action=sms_history&api_key=KEY',
            // SMM (Social Boost)
            'smm_services'     => 'GET ?action=smm_services&api_key=KEY',
            'smm_order'        => 'POST action=smm_order&api_key=KEY&service_id=ID&link=URL&quantity=QTY',
            'smm_status'       => 'GET ?action=smm_status&api_key=KEY&order_id=ID',
            // VTU (Data & Airtime)
            'vtu_plans'        => 'GET ?action=vtu_plans&api_key=KEY&network=MTN',
            'vtu_buy_data'     => 'POST action=vtu_buy_data&api_key=KEY&plan_id=ID&phone=NUMBER',
            'vtu_buy_airtime'  => 'POST action=vtu_buy_airtime&api_key=KEY&network=MTN&phone=NUMBER&amount=500',
            // Cable TV
            'cable_plans'      => 'GET ?action=cable_plans&api_key=KEY&provider=GOTV',
            'cable_buy'        => 'POST action=cable_buy&api_key=KEY&plan_id=ID&smart_card_no=NUM&phone=NUM',
            // Electricity
            'electricity_buy'  => 'POST action=electricity_buy&api_key=KEY&disco=IKEDC&meter_no=NUM&amount=5000&phone=NUM&type=prepaid',
            // Gift Cards
            'giftcard_list'    => 'GET ?action=giftcard_list&api_key=KEY&country=US',
            'giftcard_buy'     => 'POST action=giftcard_buy&api_key=KEY&product_id=ID&quantity=1',
            // Virtual Cards
            'vcard_create'     => 'POST action=vcard_create&api_key=KEY&currency=USD&amount=5',
            'vcard_list'       => 'GET ?action=vcard_list&api_key=KEY',
        ],
    ]);
}

// ── Authenticate API key ────────────────────────────────────────────────────
$api_key = trim($_GET['api_key'] ?? $_POST['api_key'] ?? '');
if (empty($api_key)) {
    api_response(['status' => 'error', 'message' => 'Missing api_key parameter.'], 401);
}

try {
    $auth_stmt = $pdo->prepare("SELECT id, username, main_balance, api_enabled, status FROM users WHERE api_key = :key LIMIT 1");
    $auth_stmt->execute([':key' => $api_key]);
    $api_user = $auth_stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    api_response(['status' => 'error', 'message' => 'Authentication error.'], 500);
}

if (!$api_user) {
    api_response(['status' => 'error', 'message' => 'Invalid API key.'], 401);
}
if ($api_user['status'] != '1') {
    api_response(['status' => 'error', 'message' => 'Account suspended.'], 403);
}
if (!$api_user['api_enabled']) {
    api_response(['status' => 'error', 'message' => 'API access not enabled for this account. Generate an API key from your dashboard.'], 403);
}

$api_user_id = (int)$api_user['id'];
$api_markup  = floatval($site_data['api_markup'] ?? 0);

// ── Log the request ─────────────────────────────────────────────────────────
$ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
try {
    $pdo->prepare("INSERT INTO api_logs (user_id, endpoint, method, ip_address, request_data) VALUES (:uid, :ep, :m, :ip, :data)")
        ->execute([
            ':uid'  => $api_user_id,
            ':ep'   => $action,
            ':m'    => $_SERVER['REQUEST_METHOD'],
            ':ip'   => $ip,
            ':data' => json_encode(array_merge($_GET, $_POST), JSON_UNESCAPED_UNICODE),
        ]);
} catch (PDOException $e) { /* non-fatal */ }

// ── Route to action handlers ────────────────────────────────────────────────
$handler_file = __DIR__ . '/handlers/' . $action . '.php';
if (!file_exists($handler_file)) {
    api_response(['status' => 'error', 'message' => "Unknown action: {$action}. Use action=help for available endpoints."], 400);
}

// Pass these to handler files
$GLOBALS['api_user']    = $api_user;
$GLOBALS['api_user_id'] = $api_user_id;
$GLOBALS['api_markup']  = $api_markup;

require $handler_file;
