<?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 (no HTML output) ─────────────────────────────────────────────
$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 Reloadly API class ───────────────────────────────────────────────────
$reloadly_path = dirname(__DIR__, 2) . '/include/Reloadly.php';
if (!file_exists($reloadly_path)) {
    echo json_encode(['status' => '0', 'msg' => 'Reloadly class file not found']); exit;
}
require_once $reloadly_path;

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

$user_id = (int)$_SESSION['user_id'];
$action  = trim($_POST['action'] ?? '');

// ════════════════════════════════════════════════════════════════════════════
//  ACTION: buy_giftcard
// ════════════════════════════════════════════════════════════════════════════
if ($action === 'buy_giftcard') {

    // ── Input ────────────────────────────────────────────────────
    $product_id      = (int)($_POST['product_id']      ?? 0);
    $country_code    = strtoupper(trim($_POST['country_code']    ?? ''));
    $currency        = strtoupper(trim($_POST['currency']        ?? ''));
    $unit_price      = (float)($_POST['unit_price']     ?? 0);
    $ngn_rate        = (float)($_POST['ngn_rate']       ?? 0);
    $ngn_charge      = (float)($_POST['ngn_charge']     ?? 0);
    $recipient_email = filter_var(trim($_POST['recipient_email'] ?? ''), FILTER_SANITIZE_EMAIL);
    $sender_name     = htmlspecialchars(trim($_POST['sender_name'] ?? ''), ENT_QUOTES);

    // ── Validate ──────────────────────────────────────────────────
    if (!$product_id || !$country_code || !$currency || $unit_price <= 0 || $ngn_charge <= 0) {
        echo json_encode(['status' => '0', 'msg' => 'Invalid order data. Please try again.']); exit;
    }
    if (!filter_var($recipient_email, FILTER_VALIDATE_EMAIL)) {
        echo json_encode(['status' => '0', 'msg' => 'Please enter a valid recipient email.']); exit;
    }
    if (strlen($sender_name) < 2) {
        echo json_encode(['status' => '0', 'msg' => 'Please enter a valid sender name.']); exit;
    }

    // ── Check Reloadly is enabled ────────────────────────���────────
    if (empty($site_data['reloadly_enabled'])) {
        echo json_encode(['status' => '0', 'msg' => 'Gift card service is currently disabled.']); exit;
    }

    // ── Fetch user with row-level lock (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;
        }

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

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

        // ── Product lookup ────────────────────────────────────────
        $prod_stmt = $pdo->prepare("SELECT * FROM gift_card_products WHERE product_id = :pid AND status = 1 LIMIT 1");
        $prod_stmt->execute(['pid' => $product_id]);
        $product = $prod_stmt->fetch(PDO::FETCH_ASSOC);

        if (!$product) {
            $pdo->rollBack();
            echo json_encode(['status' => '0', 'msg' => 'Gift card product not found or unavailable.']); exit;
        }

        // ── Generate unique custom identifier ─────────────────────
        $custom_id = 'GC_' . date('YmdHis') . '_' . strtoupper(bin2hex(random_bytes(4)));

        // ── Deduct balance & create pending order atomically ──────
        $deduct = $pdo->prepare(
            "UPDATE users SET main_balance = main_balance - :amt WHERE id = :uid AND main_balance >= :amt"
        );
        $deduct->execute(['amt' => $ngn_charge, 'uid' => $user_id]);

        if ($deduct->rowCount() === 0) {
            $pdo->rollBack();
            echo json_encode(['status' => '0', 'msg' => 'Insufficient balance. Please refresh and try again.']); exit;
        }

        $insert = $pdo->prepare(
            "INSERT INTO gift_card_orders
             (user_id, product_id, product_name, brand_name, country_code, currency_code,
              unit_price, quantity, ngn_rate, charge, recipient_email, sender_name,
              custom_identifier, status)
             VALUES (:uid, :pid, :pname, :brand, :country, :currency,
                     :unit, 1, :rate, :charge, :email, :sname, :cid, 'pending')"
        );
        $insert->execute([
            'uid'     => $user_id,
            'pid'     => $product_id,
            'pname'   => $product['product_name'],
            'brand'   => $product['brand_name'],
            'country' => $country_code,
            'currency'=> $currency,
            'unit'    => $unit_price,
            'rate'    => $ngn_rate,
            'charge'  => $ngn_charge,
            'email'   => $recipient_email,
            'sname'   => $sender_name,
            'cid'     => $custom_id,
        ]);
        $order_db_id = $pdo->lastInsertId();

        $pdo->commit();

    } catch (PDOException $e) {
        $pdo->rollBack();
        error_log('[giftcard-handler] DB error: ' . $e->getMessage());
        echo json_encode(['status' => '0', 'msg' => 'Database error. Please try again.']); exit;
    }

    // ── Call Reloadly API (outside transaction) ───────────────────
    try {
        $reloadly = new Reloadly(
            $site_data['reloadly_client_id'],
            $site_data['reloadly_client_secret'],
            (bool)$site_data['reloadly_sandbox']
        );

        $api_result = $reloadly->placeOrder(
            $product_id,
            $country_code,
            $unit_price,
            1,
            $recipient_email,
            $sender_name,
            $custom_id
        );
    } catch (Exception $e) {
        $api_result = ['success' => false, 'error' => $e->getMessage()];
    }

    // ── Handle API response ───────────────────────────────────────
    if ($api_result['success'] && !empty($api_result['data']['transactionId'])) {
        $txn    = $api_result['data'];
        $txn_id = (int)$txn['transactionId'];

        $card_number = null;
        $card_pin    = null;
        $redeem_url  = null;

        try {
            $code_result = $reloadly->getRedeemCode($txn_id);
            if ($code_result['success'] && !empty($code_result['data'])) {
                $codes       = $code_result['data'];
                $code_entry  = is_array($codes[0] ?? null) ? $codes[0] : $codes;
                $card_number = $code_entry['cardNumber'] ?? ($code_entry['code'] ?? null);
                $card_pin    = $code_entry['pinCode']    ?? null;
                $redeem_url  = $code_entry['redemptionUrl'] ?? null;
            }
        } catch (Exception $e) {
            // Code fetch failed — order still successful
        }

        try {
            $pdo->prepare(
                "UPDATE gift_card_orders SET
                    status = 'completed', reloadly_txn_id = :txn, reloadly_status = :rstatus,
                    card_number = :cnum, card_pin = :cpin, redeem_url = :rurl, api_response = :resp
                 WHERE id = :oid"
            )->execute([
                'txn'     => $txn_id,
                'rstatus' => $txn['status'] ?? 'SUCCESSFUL',
                'cnum'    => $card_number,
                'cpin'    => $card_pin,
                'rurl'    => $redeem_url,
                'resp'    => json_encode($txn),
                'oid'     => $order_db_id,
            ]);
        } catch (PDOException $e) {
            error_log('[giftcard-handler] order update error: ' . $e->getMessage());
        }

        echo json_encode([
            'status'      => '1',
            'msg'         => 'Gift card purchased successfully! Check your email for the code.',
            'order_id'    => $order_db_id,
            'card_number' => $card_number,
            'card_pin'    => $card_pin,
            'redeem_url'  => $redeem_url,
        ]);

    } else {
        // ── Refund user on API failure ────────────────────────────
        try {
            $pdo->prepare("UPDATE users SET main_balance = main_balance + :amt WHERE id = :uid")
                ->execute(['amt' => $ngn_charge, 'uid' => $user_id]);

            $pdo->prepare(
                "UPDATE gift_card_orders SET status = 'failed', api_response = :resp WHERE id = :oid"
            )->execute([
                'resp' => json_encode($api_result['data'] ?? ['error' => $api_result['error']]),
                'oid'  => $order_db_id,
            ]);
        } catch (PDOException $e) {
            error_log('[giftcard-handler] refund error: ' . $e->getMessage());
        }

        echo json_encode([
            'status' => '0',
            'msg'    => 'Gift card purchase failed: ' . ($api_result['error'] ?? 'Unknown error') . '. Your wallet has been refunded.',
        ]);
    }

    exit;
}

// ── Unknown action ────────────────────────────────────────────────────────────
echo json_encode(['status' => '0', 'msg' => 'Invalid action.']);
exit;