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

if (session_status() === PHP_SESSION_NONE) session_start();
header('Content-Type: application/json');

// ── Load config ───────────────────────────────────────────────────────────────
$config_path = dirname(__DIR__, 2) . '/include/config.php';
if (!file_exists($config_path)) {
    echo json_encode(['status' => '0', 'msg' => 'Configuration error']); exit();
}
include($config_path);

// ── Load CDH API class ────────────────────────────────────────────────────────
$cdh_include = dirname(__DIR__, 2) . '/include/CheapDataHub.php';
if (!file_exists($cdh_include)) {
    echo json_encode(['status' => '0', 'msg' => 'API class file not found']); exit();
}
include($cdh_include);

// ── Auth check ────────────────────────────────────────────────────────────────
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['status' => '0', 'msg' => 'Please log in to continue']); exit();
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => '0', 'msg' => 'Invalid request method']); exit();
}

// ── Check CDH is enabled and API key is set ───────────────────────────────────
$cdh_key     = trim($site_data['cdh_api_key'] ?? '');
$cdh_enabled = (int)($site_data['cdh_enabled'] ?? 0);

if (!$cdh_enabled || empty($cdh_key)) {
    echo json_encode(['status' => '0', 'msg' => 'VTU services are currently unavailable. Please try again later.']); exit();
}

// ── Initialise CDH client ─────────────────────────────────────────────────────
$cdh     = new CheapDataHub($cdh_key, 'https://www.cheapdatahub.ng/api/v1/resellers');
$user_id = (int)$_SESSION['user_id'];
$action  = trim($_POST['action'] ?? '');

// ── Open DB transaction with row-level lock to prevent double-spend ───────────
$pdo->beginTransaction();

try {
    $u_stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id FOR UPDATE");
    $u_stmt->execute(['id' => $user_id]);
    $user_row = $u_stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user_row) {
        $pdo->rollBack();
        echo json_encode(['status' => '0', 'msg' => 'User not found']); exit();
    }

    $balance = (float)$user_row['main_balance'];

    // ══════════════════════════════════════════════════════════════════════════
    //  BUY DATA  (working — do not modify)
    // ══════════════════════════════════════════════════════════════════════════

    if ($action === 'buy_data') {
        $plan_db_id = (int)($_POST['plan_id'] ?? 0);
        $phone      = trim($_POST['phone'] ?? '');

        if (!$plan_db_id || strlen($phone) < 10) {
            $pdo->rollBack();
            echo json_encode(['status' => '0', 'msg' => 'Valid plan and phone number required']); exit();
        }

        $p_stmt = $pdo->prepare("SELECT * FROM vtu_data_plans WHERE id = :id AND status = 1");
        $p_stmt->execute(['id' => $plan_db_id]);
        $plan = $p_stmt->fetch(PDO::FETCH_ASSOC);

        if (!$plan) {
            $pdo->rollBack();
            echo json_encode(['status' => '0', 'msg' => 'Selected plan not found or is currently unavailable']); exit();
        }

        $amount    = (float)$plan['sell_price'];
        $bundle_id = (int)$plan['plan_id'];

        if ($balance < $amount) {
            $pdo->rollBack();
            echo json_encode(['status' => '0', 'msg' => 'Insufficient wallet balance. Please fund your wallet.']); exit();
        }

        $api_result  = $cdh->buyData($phone, $bundle_id);
        $api_status  = $api_result['success'] ? 'success' : 'failed';
        $new_balance = $api_result['success'] ? $balance - $amount : $balance;

        if ($api_result['success']) {
            $pdo->prepare("UPDATE users SET main_balance = :bal WHERE id = :id")
                ->execute(['bal' => $new_balance, 'id' => $user_id]);
        }

        $ref = 'DATA_' . date('YmdHis') . '_' . strtoupper(substr(uniqid(), -6));

        $pdo->prepare(
            "INSERT INTO vtu_history (user_id, txn_id, service_type, network, phone, plan_name, amount, provider_ref, status, api_response)
             VALUES (:uid, 0, 'data', :net, :phone, :plan, :amt, :pref, :status, :resp)"
        )->execute([
            'uid'    => $user_id,
            'net'    => $plan['network'],
            'phone'  => $phone,
            'plan'   => $plan['plan_name'],
            'amt'    => $amount,
            'pref'   => $api_result['data']['transaction_id'] ?? $ref,
            'status' => $api_status,
            'resp'   => json_encode($api_result['data'] ?? []),
        ]);

        $pdo->commit();

        if ($api_result['success']) {
            echo json_encode(['status' => '1', 'msg' => "✅ {$plan['plan_name']} sent to {$phone} successfully!"]);
        } else {
            echo json_encode(['status' => '0', 'msg' => 'Purchase failed: ' . ($api_result['error'] ?? 'Unknown error. Please contact support.')]);
        }
        exit();
    }

    // ══════════════════════════════════════════════════════════════════════════
    //  BUY AIRTIME  (working — do not modify)
    // ══════════════════════════════════════════════════════════════════════════

    if ($action === 'buy_airtime') {
        $network = strtoupper(trim($_POST['network'] ?? ''));
        $phone   = trim($_POST['phone'] ?? '');
        $raw_amt = (float)($_POST['amount'] ?? 0);

        if (!$network || strlen($phone) < 10 || $raw_amt < 50) {
            $pdo->rollBack();
            echo json_encode(['status' => '0', 'msg' => 'Network, phone (min 10 digits) and amount (min ₦50) required']); exit();
        }

        // Flat NGN service fee stored in cdh_airtime_markup
        $flat_fee = (float)($site_data['cdh_airtime_markup'] ?? 0);
        $amount   = round($raw_amt + $flat_fee, 2);

        if ($balance < $amount) {
            $pdo->rollBack();
            echo json_encode(['status' => '0', 'msg' => 'Insufficient wallet balance.']); exit();
        }

        $api_result  = $cdh->buyAirtime($network, $phone, $raw_amt);
        $api_status  = $api_result['success'] ? 'success' : 'failed';
        $new_balance = $api_result['success'] ? $balance - $amount : $balance;

        if ($api_result['success']) {
            $pdo->prepare("UPDATE users SET main_balance = :bal WHERE id = :id")
                ->execute(['bal' => $new_balance, 'id' => $user_id]);
        }

        $ref = 'AIR_' . date('YmdHis') . '_' . strtoupper(substr(uniqid(), -6));

        $pdo->prepare(
            "INSERT INTO vtu_history (user_id, txn_id, service_type, network, phone, plan_name, amount, provider_ref, status, api_response)
             VALUES (:uid, 0, 'airtime', :net, :phone, :plan, :amt, :pref, :status, :resp)"
        )->execute([
            'uid'    => $user_id,
            'net'    => $network,
            'phone'  => $phone,
            'plan'   => "₦{$raw_amt} Airtime",
            'amt'    => $amount,
            'pref'   => $api_result['data']['transaction_id'] ?? $ref,
            'status' => $api_status,
            'resp'   => json_encode($api_result['data'] ?? []),
        ]);

        $pdo->commit();

        if ($api_result['success']) {
            echo json_encode(['status' => '1', 'msg' => "✅ ₦{$raw_amt} {$network} airtime sent to {$phone}!"]);
        } else {
            echo json_encode(['status' => '0', 'msg' => 'Purchase failed: ' . ($api_result['error'] ?? 'Unknown error')]);
        }
        exit();
    }

    // ══════════════════════════════════════════════════════════════════════════
    //  BUY CABLE TV
    //  CDH endpoint: POST /cable/purchase/
    //  Required fields:
    //    provider_id   — numeric: GOTV=1, DSTV=2, STARTIMES=3
    //    plan_id       — numeric bouquet code from vtu_cable_plans.plan_code
    //    smart_card_no — decoder smartcard/IUC number
    //    phone_number  — customer phone for SMS confirmation
    //
    //  POST params from cable-tv.php:
    //    action, provider, plan_id (our DB id), card_no, phone
    // ══════════════════════════════════════════════════════════════════════════

    if ($action === 'buy_cable') {

        // 1. Read and sanitise inputs
        $provider   = strtoupper(trim($_POST['provider'] ?? ''));
        $plan_db_id = (int)($_POST['plan_id']  ?? 0);
        $card_no    = trim($_POST['card_no']   ?? '');
        $phone      = trim($_POST['phone']     ?? '');

        // 2. Validate all required fields
        if (empty($provider)) {
            $pdo->rollBack();
            echo json_encode(['status' => '0', 'msg' => 'Cable provider is required']); exit();
        }
        if (!CheapDataHub::getCableProviderId($provider)) {
            $pdo->rollBack();
            echo json_encode(['status' => '0', 'msg' => 'Unknown cable provider: ' . $provider]); exit();
        }
        if (!$plan_db_id) {
            $pdo->rollBack();
            echo json_encode(['status' => '0', 'msg' => 'Please select a plan']); exit();
        }
        if (empty($card_no) || strlen($card_no) < 5) {
            $pdo->rollBack();
            echo json_encode(['status' => '0', 'msg' => 'Enter a valid SmartCard / IUC number']); exit();
        }
        if (strlen($phone) < 10) {
            $pdo->rollBack();
            echo json_encode(['status' => '0', 'msg' => 'Enter a valid phone number (min 10 digits)']); exit();
        }

        // 3. Fetch plan from DB — never trust client-side price
        $cp_stmt = $pdo->prepare("SELECT * FROM vtu_cable_plans WHERE id = :id AND status = 1");
        $cp_stmt->execute(['id' => $plan_db_id]);
        $cable_plan = $cp_stmt->fetch(PDO::FETCH_ASSOC);

        if (!$cable_plan) {
            $pdo->rollBack();
            echo json_encode(['status' => '0', 'msg' => 'Selected plan not found or is unavailable']); exit();
        }

        if (empty($cable_plan['plan_code'])) {
            $pdo->rollBack();
            echo json_encode(['status' => '0', 'msg' => 'Plan configuration error (missing plan code). Contact support.']); exit();
        }

        // 4. Calculate total (plan price + flat service fee)
        $flat_fee     = (float)($site_data['cdh_cable_markup'] ?? 0);
        $plan_price   = (float)$cable_plan['sell_price'];
        $total_charge = round($plan_price + $flat_fee, 2);

        // 5. Balance check
        if ($balance < $total_charge) {
            $pdo->rollBack();
            echo json_encode(['status' => '0', 'msg' => 'Insufficient wallet balance. Please fund your wallet.']); exit();
        }

        // 6. Call CDH API
        //    buyCable($provider, $card_no, $plan_code, $phone)
        //    Internally resolves provider name → numeric provider_id
        //    Sends: provider_id, plan_id, smart_card_no, phone_number
        $api_result = $cdh->buyCable(
            $provider,
            $card_no,
            $cable_plan['plan_code'],
            $phone
        );

        $api_status  = $api_result['success'] ? 'success' : 'failed';
        $new_balance = $api_result['success'] ? $balance - $total_charge : $balance;

        // 7. Deduct balance only on success
        if ($api_result['success']) {
            $pdo->prepare("UPDATE users SET main_balance = :bal WHERE id = :id")
                ->execute(['bal' => $new_balance, 'id' => $user_id]);
        }

        // 8. Log to vtu_history regardless of outcome
        $ref = 'CAB_' . date('YmdHis') . '_' . strtoupper(substr(uniqid(), -6));

        $pdo->prepare(
            "INSERT INTO vtu_history
                (user_id, txn_id, service_type, network, phone, plan_name, amount, provider_ref, status, api_response)
             VALUES
                (:uid, 0, 'cable', :net, :phone, :plan, :amt, :pref, :status, :resp)"
        )->execute([
            'uid'    => $user_id,
            'net'    => $provider,
            'phone'  => $phone,
            'plan'   => $cable_plan['plan_name'],
            'amt'    => $total_charge,
            'pref'   => $api_result['data']['transaction_id'] ?? $ref,
            'status' => $api_status,
            'resp'   => json_encode($api_result['data'] ?? []),
        ]);

        $pdo->commit();

        // 9. Respond to client
        if ($api_result['success']) {
            echo json_encode([
                'status' => '1',
                'msg'    => "✅ {$provider} — {$cable_plan['plan_name']} subscription activated for card {$card_no}!",
            ]);
        } else {
            echo json_encode([
                'status' => '0',
                'msg'    => 'Payment failed: ' . ($api_result['error'] ?? 'Unknown error from provider'),
            ]);
        }
        exit();
    }

    // ══════════════════════════════════════════════════════════════════════════
    //  BUY ELECTRICITY
    //  CDH endpoint: POST /electricity/purchase/
    //  Required fields:
    //    disco_id     — numeric ID (AEDC=1, EKEDC=2, etc.)
    //    meter_number — customer meter number
    //    amount       — amount in NGN (min ₦500)
    //    phone_number — customer phone for token SMS
    //    meter_type   — "prepaid" or "postpaid"
    //
    //  No meter validation needed.
    //
    //  POST params from electricity.php:
    //    action, disco, meter_no, meter_type, phone, amount
    // ══════════════════════════════════════════════════════════════════════════

    if ($action === 'buy_electricity') {

        // 1. Read and sanitise inputs
        $disco      = strtoupper(trim($_POST['disco']       ?? ''));
        $meter_no   = trim($_POST['meter_no']               ?? '');
        $meter_type = trim($_POST['meter_type']             ?? 'prepaid');
        $phone      = trim($_POST['phone']                  ?? '');
        $raw_amount = (float)($_POST['amount']              ?? 0);

        // Enforce prepaid | postpaid only
        if (!in_array($meter_type, ['prepaid', 'postpaid'])) {
            $meter_type = 'prepaid';
        }

        // 2. Validate all required fields
        if (empty($disco)) {
            $pdo->rollBack();
            echo json_encode(['status' => '0', 'msg' => 'Please select a DISCO (electricity provider)']); exit();
        }
        if (!CheapDataHub::getDiscoId($disco)) {
            $pdo->rollBack();
            echo json_encode(['status' => '0', 'msg' => "Unknown DISCO: {$disco}. Please contact support."]); exit();
        }
        if (empty($meter_no)) {
            $pdo->rollBack();
            echo json_encode(['status' => '0', 'msg' => 'Meter number is required']); exit();
        }
        if (strlen($phone) < 10) {
            $pdo->rollBack();
            echo json_encode(['status' => '0', 'msg' => 'Enter a valid phone number (min 10 digits)']); exit();
        }
        if ($raw_amount < 1000) {
            $pdo->rollBack();
            echo json_encode(['status' => '0', 'msg' => 'Minimum electricity purchase amount is ₦1000']); exit();
        }

        // 3. Calculate total (electricity amount + flat service fee)
        $flat_fee     = (float)($site_data['cdh_electricity_markup'] ?? 0);
        $total_charge = round($raw_amount + $flat_fee, 2);

        // 4. Balance check
        if ($balance < $total_charge) {
            $pdo->rollBack();
            echo json_encode(['status' => '0', 'msg' => 'Insufficient wallet balance. Please fund your wallet.']); exit();
        }

        // 5. Call CDH API
        //    buyElectricity($disco, $meter_no, $amount, $type, $phone)
        //    Internally resolves DISCO name → numeric disco_id
        //    Sends: disco_id, meter_number, amount, phone_number, meter_type
        $api_result = $cdh->buyElectricity(
            $disco,
            $meter_no,
            $raw_amount,
            $meter_type,
            $phone
        );

        $api_status  = $api_result['success'] ? 'success' : 'failed';
        $new_balance = $api_result['success'] ? $balance - $total_charge : $balance;

        // Extract token from various possible response keys
        $token = $api_result['data']['token']
              ?? $api_result['data']['meter_token']
              ?? $api_result['data']['units']
              ?? null;

        // 6. Deduct balance only on success
        if ($api_result['success']) {
            $pdo->prepare("UPDATE users SET main_balance = :bal WHERE id = :id")
                ->execute(['bal' => $new_balance, 'id' => $user_id]);
        }

        // 7. Log to vtu_history
        $ref = 'ELEC_' . date('YmdHis') . '_' . strtoupper(substr(uniqid(), -6));

        $pdo->prepare(
            "INSERT INTO vtu_history
                (user_id, txn_id, service_type, network, phone, plan_name, amount, token, provider_ref, status, api_response)
             VALUES
                (:uid, 0, 'electricity', :net, :phone, :plan, :amt, :token, :pref, :status, :resp)"
        )->execute([
            'uid'    => $user_id,
            'net'    => $disco,
            'phone'  => $phone,
            'plan'   => ucfirst($meter_type) . ' — ₦' . number_format($raw_amount, 2),
            'amt'    => $total_charge,
            'token'  => $token,
            'pref'   => $api_result['data']['transaction_id'] ?? $ref,
            'status' => $api_status,
            'resp'   => json_encode($api_result['data'] ?? []),
        ]);

        $pdo->commit();

        // 8. Respond to client
        if ($api_result['success']) {
            $response = [
                'status' => '1',
                'msg'    => "✅ ₦{$raw_amount} electricity purchased for meter {$meter_no}!",
            ];
            if ($token) {
                $response['token'] = $token;
            }
            echo json_encode($response);
        } else {
            echo json_encode([
                'status' => '0',
                'msg'    => 'Payment failed: ' . ($api_result['error'] ?? 'Unknown error from provider'),
            ]);
        }
        exit();
    }

    // ── Unknown action ────────────────────────────────────────────────────────
    $pdo->rollBack();
    echo json_encode(['status' => '0', 'msg' => 'Unknown action: ' . htmlspecialchars($action)]);

} catch (PDOException $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    error_log('[vtu-purchase] DB error: ' . $e->getMessage());
    echo json_encode(['status' => '0', 'msg' => 'A server error occurred. Please try again later.']);
} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    error_log('[vtu-purchase] Exception: ' . $e->getMessage());
    echo json_encode(['status' => '0', 'msg' => 'An unexpected error occurred.']);
}