<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech


ob_start();
header('Content-Type: application/json; charset=utf-8');

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


// Ensure no stray output breaks JSON
if (!function_exists('json_clean_response')) {
    function json_clean_response(array $data, int $code = 200): void {
        ob_clean();
        http_response_code($code);
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode($data);
        exit;
    }
}

// ── Input validation ─────────────────────────────────────────────────────────

if (empty($_GET['order_id'])) {
    json_clean_response(['status' => '500', 'message' => 'Invalid Order ID']);
}
if (empty($_GET['token'])) {
    json_clean_response(['status' => '500', 'message' => 'Token Blank']);
}

$token    = trim($_GET['token']);
$order_id = trim($_GET['order_id']);

// ── Auth ─────────────────────────────────────────────────────────────────────

$user_id = otp_verify_user($token, $pdo);
if ($user_id === false) {
    json_clean_response(['status' => '500', 'message' => 'Invalid session. Please login again.']);
}

// ── Fetch active order ────────────────────────────────────────────────────────

try {
    $stmt = $pdo->prepare(
        "SELECT * FROM active_number
          WHERE order_id      = :oid
            AND user_id       = :uid
            AND active_status = '2'
          LIMIT 1"
    );
    $stmt->execute([':oid' => $order_id, ':uid' => $user_id]);
    $active = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    json_clean_response(['status' => '500', 'message' => 'Database error.']);
}

if (!$active) {
    json_clean_response(['status' => '500', 'message' => 'Order not found or already cancelled.']);
}

// ── Cannot cancel if SMS already received ────────────────────────────────────

if ($active['status'] === '1' && !empty($active['sms_text'])) {
    json_clean_response(['status' => '500', 'message' => 'Cannot cancel. SMS has already been received.']);
}

$provider = $active['provider'] ?? 'smscodes';

// ── Provider-specific pre-cancel logic ───────────────────────────────────────
// smscodes.io: no API cancel call needed (only charges on SMS delivery)
// smspva.com:  also charges only on SMS delivery, so no API cancel call needed.
// Both providers: cancellation is a local action — mark order cancelled + refund.
// NOTE: If smspva ever introduces a cancel endpoint, add the call here.

// ── Cancel and refund ────────────────────────────────────────────────────────

try {
    $pdo->beginTransaction();

    $w = $pdo->prepare("SELECT main_balance FROM users WHERE id = :uid FOR UPDATE");
    $w->execute([':uid' => $user_id]);
    $wallet = $w->fetch(PDO::FETCH_ASSOC);

    $new_balance = (float)$wallet['main_balance'] + (float)$active['service_price'];

    $pdo->prepare("UPDATE users SET main_balance = :b WHERE id = :uid")
        ->execute([':b' => $new_balance, ':uid' => $user_id]);

    // status='3' (cancelled/refunded), active_status='1' (inactive/finalised)
    $pdo->prepare(
        "UPDATE active_number SET active_status = '1', status = '3' WHERE id = :id"
    )->execute([':id' => $active['id']]);

    $pdo->commit();

} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    json_clean_response(['status' => '500', 'message' => 'Error processing cancellation.']);
}

$provider_label = ($provider === 'smspva') ? 'Server1' : 'Server2';

json_clean_response([
    'status'   => '200',
    'message'  => 'Number Cancelled. ₦' . number_format((float)$active['service_price'], 2) . ' Refunded.',
    'provider' => $provider_label,
]);