<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech
// Single AJAX handler for all Sudo Africa virtual card operations

if (session_status() === PHP_SESSION_NONE) session_start();

// Auth check
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true || !isset($_SESSION['user_id'])) {
    echo json_encode(['status' => '0', 'msg' => 'Unauthorized. Please log in.']);
    exit();
}

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

// ── Sudo Africa API Config ──
// Add these to your settings table or define here
define('SUDO_API_KEY',      $site_data['sudo_api_key']      ?? 'YOUR_SUDO_API_KEY');
define('SUDO_SANDBOX',      ($site_data['sudo_sandbox']      ?? '1') === '1');
define('SUDO_CARD_PROGRAM', $site_data['sudo_card_program']  ?? '');  // Your Card Program ID from Sudo dashboard
define('CARD_CREATION_FEE', (float)($site_data['card_creation_fee'] ?? 0)); // Fee charged per card creation (in NGN)

$sudo    = new SudoAfrica(SUDO_API_KEY, SUDO_SANDBOX);
$user_id = (int)$_SESSION['user_id'];
$action  = trim($_POST['action'] ?? '');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => '0', 'msg' => 'Invalid request method']);
    exit();
}

// ── Load current user ──
try {
    $u_stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id LIMIT 1");
    $u_stmt->execute(['id' => $user_id]);
    $user = $u_stmt->fetch(PDO::FETCH_ASSOC);
    if (!$user) throw new Exception('User not found');
} catch (Exception $e) {
    echo json_encode(['status' => '0', 'msg' => 'User not found.']);
    exit();
}

switch ($action) {

    // ════════════════════════════════════════════════
    // CREATE CARD
    // ════════════════════════════════════════════════
    case 'create_card':
        $currency = in_array(strtoupper($_POST['currency'] ?? 'NGN'), ['NGN','USD']) ? strtoupper($_POST['currency']) : 'NGN';

        // Check balance for card creation fee
        if (CARD_CREATION_FEE > 0 && (float)$user['main_balance'] < CARD_CREATION_FEE) {
            echo json_encode(['status' => '0', 'msg' => 'Insufficient balance. Card creation fee: ₦' . number_format(CARD_CREATION_FEE, 2)]);
            exit();
        }

        try {
            $pdo->beginTransaction();

            // ── Step 1: Create or reuse Sudo customer ──
            $sudo_customer_id = $user['sudo_customer_id'] ?? null;

            if (empty($sudo_customer_id)) {
                $customer_res = $sudo->createCustomer([
                    'type'   => 'individual',
                    'name'   => !empty($user['full_name']) ? $user['full_name'] : $user['username'],
                    'status' => 'active',
                    'individual' => [
                        'firstName' => explode(' ', $user['full_name'] ?? $user['username'])[0],
                        'lastName'  => explode(' ', $user['full_name'] ?? $user['username'])[1] ?? $user['username'],
                    ],
                    'emailAddress' => $user['email'],
                    'phoneNumber'  => $user['phone'] ?? null,
                    'billingAddress' => [
                        'line1'      => '1 Main Street',
                        'city'       => 'Lagos',
                        'state'      => 'Lagos',
                        'country'    => 'NG',
                        'postalCode' => '100001',
                    ],
                ]);

                if (!$customer_res['success']) {
                    $pdo->rollBack();
                    echo json_encode(['status' => '0', 'msg' => 'Failed to create card profile: ' . ($customer_res['message'] ?? 'Unknown error')]);
                    exit();
                }

                $sudo_customer_id = $customer_res['data']['_id'] ?? null;
                if (!$sudo_customer_id) {
                    $pdo->rollBack();
                    echo json_encode(['status' => '0', 'msg' => 'Invalid response from card provider.']);
                    exit();
                }

                // Save customer ID to user
                $pdo->prepare("UPDATE users SET sudo_customer_id = :cid WHERE id = :uid")
                    ->execute(['cid' => $sudo_customer_id, 'uid' => $user_id]);
            }

            // ── Step 2: Create virtual card ──
            $card_res = $sudo->createVirtualCard($sudo_customer_id, $currency, SUDO_CARD_PROGRAM);

            if (!$card_res['success']) {
                $pdo->rollBack();
                echo json_encode(['status' => '0', 'msg' => 'Failed to create card: ' . ($card_res['message'] ?? 'Unknown error')]);
                exit();
            }

            $card_data = $card_res['data'];
            $sudo_card_id = $card_data['_id'] ?? null;

            if (!$sudo_card_id) {
                $pdo->rollBack();
                echo json_encode(['status' => '0', 'msg' => 'Invalid card response from provider.']);
                exit();
            }

            // ── Step 3: Deduct creation fee if applicable ──
            if (CARD_CREATION_FEE > 0) {
                $pdo->prepare("UPDATE users SET main_balance = main_balance - :fee WHERE id = :uid")
                    ->execute(['fee' => CARD_CREATION_FEE, 'uid' => $user_id]);

                // Log fee transaction
                $fee_ref = 'CARD_FEE_' . strtoupper(uniqid());
                $pdo->prepare("INSERT INTO transactions (user_id, transaction_ref, payment_gateway, transaction_type, amount, currency, status, created_at)
                                VALUES (:uid, :ref, 'balance', 'logs_purchase', :amount, 'NGN', 'successful', NOW())")
                    ->execute(['uid' => $user_id, 'ref' => $fee_ref, 'amount' => CARD_CREATION_FEE]);
            }

            // ── Step 4: Save card to DB ──
            $masked_pan  = $card_data['maskedPan'] ?? null;
            $last_four   = $masked_pan ? substr(str_replace(' ', '', $masked_pan), -4) : null;
            $expiry_m    = $card_data['expiryMonth']  ?? null;
            $expiry_y    = $card_data['expiryYear']   ?? null;

            $pdo->prepare("INSERT INTO virtual_cards (user_id, sudo_card_id, sudo_customer_id, currency, status, last_four, expiry_month, expiry_year, created_at)
                            VALUES (:uid, :card_id, :cust_id, :currency, 'active', :last_four, :exp_m, :exp_y, NOW())")
                ->execute([
                    'uid'      => $user_id,
                    'card_id'  => $sudo_card_id,
                    'cust_id'  => $sudo_customer_id,
                    'currency' => $currency,
                    'last_four'=> $last_four,
                    'exp_m'    => $expiry_m,
                    'exp_y'    => $expiry_y,
                ]);

            $pdo->commit();

            echo json_encode([
                'status' => '1',
                'msg'    => $currency . ' virtual card created successfully!' . (CARD_CREATION_FEE > 0 ? ' ₦' . number_format(CARD_CREATION_FEE, 2) . ' creation fee charged.' : ''),
            ]);

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

    // ════════════════════════════════════════════════
    // REVEAL CARD (sensitive PAN + CVV via vault)
    // ════════════════════════════════════════════════
    case 'reveal_card':
        $sudo_card_id = trim($_POST['sudo_card_id'] ?? '');
        $db_card_id   = (int)($_POST['db_card_id']  ?? 0);

        if (!$sudo_card_id || !$db_card_id) {
            echo json_encode(['status' => '0', 'msg' => 'Invalid card']);
            exit();
        }

        // Verify ownership
        $own = $pdo->prepare("SELECT id FROM virtual_cards WHERE id = :dbid AND user_id = :uid AND sudo_card_id = :cid LIMIT 1");
        $own->execute(['dbid' => $db_card_id, 'uid' => $user_id, 'cid' => $sudo_card_id]);
        if (!$own->fetch()) {
            echo json_encode(['status' => '0', 'msg' => 'Card not found']);
            exit();
        }

        $res = $sudo->revealCard($sudo_card_id);

        if (!$res['success']) {
            echo json_encode(['status' => '0', 'msg' => 'Failed to retrieve card details: ' . ($res['message'] ?? 'Unknown error')]);
            exit();
        }

        $d = $res['data'];
        echo json_encode([
            'status' => '1',
            'card'   => [
                'pan'     => $d['number']     ?? $d['maskedPan'] ?? '—',
                'expiry'  => sprintf('%02d/%s', $d['expiryMonth'] ?? 0, substr($d['expiryYear'] ?? '0', -2)),
                'cvv'     => $d['cvv2']        ?? '—',
                'address' => '1 Main Street, Lagos, NG',
            ],
        ]);
        break;

    // ════════════════════════════════════════════════
    // FREEZE CARD
    // ════════════════════════════════════════════════
    case 'freeze_card':
        $sudo_card_id = trim($_POST['sudo_card_id'] ?? '');
        $db_card_id   = (int)($_POST['db_card_id']  ?? 0);

        $own = $pdo->prepare("SELECT id FROM virtual_cards WHERE id = :dbid AND user_id = :uid AND sudo_card_id = :cid AND status = 'active' LIMIT 1");
        $own->execute(['dbid' => $db_card_id, 'uid' => $user_id, 'cid' => $sudo_card_id]);
        if (!$own->fetch()) { echo json_encode(['status' => '0', 'msg' => 'Card not found or already frozen']); exit(); }

        $res = $sudo->freezeCard($sudo_card_id);
        if (!$res['success']) { echo json_encode(['status' => '0', 'msg' => 'Failed to freeze card: ' . ($res['message'] ?? 'Unknown error')]); exit(); }

        $pdo->prepare("UPDATE virtual_cards SET status = 'inactive', updated_at = NOW() WHERE id = :id AND user_id = :uid")
            ->execute(['id' => $db_card_id, 'uid' => $user_id]);

        echo json_encode(['status' => '1', 'msg' => 'Card frozen successfully.']);
        break;

    // ════════════════════════════════════════════════
    // UNFREEZE CARD
    // ════════════════════════════════════════════════
    case 'unfreeze_card':
        $sudo_card_id = trim($_POST['sudo_card_id'] ?? '');
        $db_card_id   = (int)($_POST['db_card_id']  ?? 0);

        $own = $pdo->prepare("SELECT id FROM virtual_cards WHERE id = :dbid AND user_id = :uid AND sudo_card_id = :cid AND status = 'inactive' LIMIT 1");
        $own->execute(['dbid' => $db_card_id, 'uid' => $user_id, 'cid' => $sudo_card_id]);
        if (!$own->fetch()) { echo json_encode(['status' => '0', 'msg' => 'Card not found or already active']); exit(); }

        $res = $sudo->unfreezeCard($sudo_card_id);
        if (!$res['success']) { echo json_encode(['status' => '0', 'msg' => 'Failed to unfreeze card: ' . ($res['message'] ?? 'Unknown error')]); exit(); }

        $pdo->prepare("UPDATE virtual_cards SET status = 'active', updated_at = NOW() WHERE id = :id AND user_id = :uid")
            ->execute(['id' => $db_card_id, 'uid' => $user_id]);

        echo json_encode(['status' => '1', 'msg' => 'Card activated successfully.']);
        break;

    // ════════════════════════════════════════════════
    // FUND CARD (deduct from main_balance → credit Sudo card)
    // ════════════════════════════════════════════════
    case 'fund_card':
        $sudo_card_id = trim($_POST['sudo_card_id'] ?? '');
        $db_card_id   = (int)($_POST['db_card_id']  ?? 0);
        $amount       = filter_var($_POST['amount'] ?? 0, FILTER_VALIDATE_FLOAT);

        if (!$sudo_card_id || !$db_card_id || !$amount || $amount < 100) {
            echo json_encode(['status' => '0', 'msg' => 'Invalid input. Minimum funding amount is ₦100.']);
            exit();
        }

        $own = $pdo->prepare("SELECT * FROM virtual_cards WHERE id = :dbid AND user_id = :uid AND sudo_card_id = :cid AND status = 'active' LIMIT 1");
        $own->execute(['dbid' => $db_card_id, 'uid' => $user_id, 'cid' => $sudo_card_id]);
        $card = $own->fetch(PDO::FETCH_ASSOC);
        if (!$card) { echo json_encode(['status' => '0', 'msg' => 'Card not found or inactive']); exit(); }

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

        try {
            $pdo->beginTransaction();

            // Deduct from main balance
            $pdo->prepare("UPDATE users SET main_balance = main_balance - :amt WHERE id = :uid")
                ->execute(['amt' => $amount, 'uid' => $user_id]);

            // NOTE: Sudo Africa card funding is done by transferring to the Sudo account
            // via bank transfer in production. In sandbox, use the simulator.
            // For production: user funds their Sudo account; cards draw from it.
            // Here we log the intent and record the deduction.
            $txn_ref = 'CARD_FUND_' . strtoupper(uniqid()) . '_' . time();
            $pdo->prepare("INSERT INTO transactions (user_id, transaction_ref, payment_gateway, transaction_type, amount, currency, status, metadata, created_at)
                            VALUES (:uid, :ref, 'sudo_africa', 'logs_purchase', :amount, :currency, 'successful', :meta, NOW())")
                ->execute([
                    'uid'      => $user_id,
                    'ref'      => $txn_ref,
                    'amount'   => $amount,
                    'currency' => $card['currency'],
                    'meta'     => json_encode(['sudo_card_id' => $sudo_card_id, 'action' => 'card_funding']),
                ]);

            $pdo->commit();

            echo json_encode([
                'status' => '1',
                'msg'    => '₦' . number_format($amount, 2) . ' has been queued to fund your card. It may take a few minutes to reflect.',
            ]);

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

    // ════════════════════════════════════════════════
    // TERMINATE CARD (permanent)
    // ════════════════════════════════════════════════
    case 'terminate_card':
        $sudo_card_id = trim($_POST['sudo_card_id'] ?? '');
        $db_card_id   = (int)($_POST['db_card_id']  ?? 0);

        $own = $pdo->prepare("SELECT id FROM virtual_cards WHERE id = :dbid AND user_id = :uid AND sudo_card_id = :cid LIMIT 1");
        $own->execute(['dbid' => $db_card_id, 'uid' => $user_id, 'cid' => $sudo_card_id]);
        if (!$own->fetch()) { echo json_encode(['status' => '0', 'msg' => 'Card not found']); exit(); }

        $res = $sudo->terminateCard($sudo_card_id);
        if (!$res['success']) { echo json_encode(['status' => '0', 'msg' => 'Failed to terminate card: ' . ($res['message'] ?? 'Unknown error')]); exit(); }

        $pdo->prepare("UPDATE virtual_cards SET status = 'terminated', updated_at = NOW() WHERE id = :id AND user_id = :uid")
            ->execute(['id' => $db_card_id, 'uid' => $user_id]);

        echo json_encode(['status' => '1', 'msg' => 'Card has been permanently terminated.']);
        break;

    default:
        echo json_encode(['status' => '0', 'msg' => 'Unknown action']);
        break;
}
?>