<?php
// POST action=cable_buy&api_key=KEY&plan_id=ID&smart_card_no=NUMBER&phone=NUMBER
// Buy cable TV subscription

$user_id       = $GLOBALS['api_user_id'];
$plan_id       = (int)($_POST['plan_id'] ?? $_GET['plan_id'] ?? 0);
$smart_card_no = trim($_POST['smart_card_no'] ?? $_GET['smart_card_no'] ?? '');
$phone         = trim($_POST['phone'] ?? $_GET['phone'] ?? '');

if (!$plan_id || empty($smart_card_no) || empty($phone)) {
    api_response(['status' => 'error', 'message' => 'Missing plan_id, smart_card_no, or phone.'], 400);
}

$_POST['action']        = 'buy_cable';
$_POST['plan_id']       = $plan_id;
$_POST['smart_card_no'] = $smart_card_no;
$_POST['phone_number']  = $phone;

$_SESSION['user_id']   = $user_id;
$_SESSION['logged_in'] = true;

ob_start();
require __DIR__ . '/../../user/ajax/vtu-purchase.php';
$output = ob_get_clean();

$data = json_decode($output, true);
if (!$data) {
    api_response(['status' => 'error', 'message' => 'Internal processing error.'], 500);
}

if ($data['status'] === '1') {
    api_response([
        'status'  => 'success',
        'message' => $data['msg'] ?? 'Cable TV subscription purchased.',
        'smart_card' => $smart_card_no,
    ]);
} else {
    api_response(['status' => 'error', 'message' => $data['msg'] ?? 'Purchase failed.'], 400);
}
