<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech
// admin/ajax/vcard_ajax.php – Admin AJAX for virtual card management

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

$config_path = dirname(__DIR__, 2) . '/include/config.php';
if (!file_exists($config_path)) {
    echo json_encode(array('status'=>'0','msg'=>'Config not found')); exit;
}
include($config_path);

// ── Admin auth ────────────────────────────────────────────────
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    echo json_encode(array('status'=>'0','msg'=>'Unauthorized')); exit;
}
try {
    $adm = $pdo->prepare("SELECT is_admin FROM users WHERE id = :uid");
    $adm->execute(array(':uid' => $_SESSION['user_id']));
    $adm = $adm->fetch(PDO::FETCH_ASSOC);
    if (!$adm || $adm['is_admin'] != 1) {
        echo json_encode(array('status'=>'0','msg'=>'Unauthorized')); exit;
    }
} catch (PDOException $e) {
    echo json_encode(array('status'=>'0','msg'=>'Auth error')); exit;
}

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

$action = isset($_POST['action']) ? trim($_POST['action']) : '';

// ── Load StroWallet class ─────────────────────────────────────
$stro_path = dirname(__DIR__, 2) . '/include/StroWallet.php';
if (!file_exists($stro_path)) {
    echo json_encode(array('status'=>'0','msg'=>'StroWallet class not found')); exit;
}
require_once $stro_path;

// ── Helpers ───────────────────────────────────────────────────
function getSettings($pdo)
{
    $row = $pdo->query("SELECT * FROM settings WHERE id = 1 LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    return $row ? $row : array();
}

function initApi($pdo)
{
    $cfg         = getSettings($pdo);
    $sandbox_val = isset($cfg['strowallet_sandbox']) ? $cfg['strowallet_sandbox'] : 1;
    $sandbox     = ($sandbox_val == 1 || $sandbox_val === '1' || $sandbox_val === true);
    $pub         = isset($cfg['strowallet_public_key']) ? $cfg['strowallet_public_key'] : '';
    return new StroWallet($pub, $sandbox);
}

// ════════════════════════════════════════════════════════════════
// ACTION: save_strowallet_settings
// ════════════════════════════════════════════════════════════════
if ($action === 'save_strowallet_settings') {
    $fields = array(
        'strowallet_public_key' => trim(isset($_POST['strowallet_public_key']) ? $_POST['strowallet_public_key'] : ''),
        'strowallet_secret_key' => trim(isset($_POST['strowallet_secret_key']) ? $_POST['strowallet_secret_key'] : ''),
        'strowallet_sandbox'    => (int)(isset($_POST['strowallet_sandbox'])    ? $_POST['strowallet_sandbox']    : 1),
        'strowallet_enabled'    => (int)(isset($_POST['strowallet_enabled'])    ? $_POST['strowallet_enabled']    : 0),
        'vcard_creation_fee'    => (float)(isset($_POST['vcard_creation_fee'])  ? $_POST['vcard_creation_fee']   : 0),
        'vcard_fund_rate'       => (float)(isset($_POST['vcard_fund_rate'])     ? $_POST['vcard_fund_rate']      : 1600),
        'vcard_withdraw_rate'   => (float)(isset($_POST['vcard_withdraw_rate']) ? $_POST['vcard_withdraw_rate']  : 1550),
        'vcard_min_balance'     => (float)(isset($_POST['vcard_min_balance'])   ? $_POST['vcard_min_balance']    : 1),
        'vcard_min_fund'        => (float)(isset($_POST['vcard_min_fund'])      ? $_POST['vcard_min_fund']       : 5),
        'vcard_max_per_user'    => (int)(isset($_POST['vcard_max_per_user'])    ? $_POST['vcard_max_per_user']   : 3),
    );

    try {
        $pdo->prepare("UPDATE settings SET
            strowallet_public_key = :strowallet_public_key,
            strowallet_secret_key = :strowallet_secret_key,
            strowallet_sandbox    = :strowallet_sandbox,
            strowallet_enabled    = :strowallet_enabled,
            vcard_creation_fee    = :vcard_creation_fee,
            vcard_fund_rate       = :vcard_fund_rate,
            vcard_withdraw_rate   = :vcard_withdraw_rate,
            vcard_min_balance     = :vcard_min_balance,
            vcard_min_fund        = :vcard_min_fund,
            vcard_max_per_user    = :vcard_max_per_user
            WHERE id = 1")->execute($fields);

        echo json_encode(array('status'=>'1','msg'=>'StroWallet settings saved successfully.'));
    } catch (PDOException $e) {
        echo json_encode(array('status'=>'0','msg'=>'DB error: '.$e->getMessage()));
    }
    exit;
}

// ════════════════════════════════════════════════════════════════
// ACTION: test_strowallet_connection
// Uses fetch-nfccard-detail with a dummy card_id — any HTTP response
// means the API endpoint is reachable and the key is being processed
// ════════════════════════════════════════════════════════════════
if ($action === 'test_strowallet_connection') {
    $cfg = getSettings($pdo);
    if (empty($cfg['strowallet_public_key'])) {
        echo json_encode(array('status'=>'0','msg'=>'Public key not configured.')); exit;
    }

    try {
        $api    = initApi($pdo);
        // Test with fetch-nfccard-detail using a dummy ID
        // Any HTTP response (including 400/404) means the API is reachable
        $result = $api->getCardDetails('test_connection_check');
        if (isset($result['code']) && $result['code'] > 0) {
            echo json_encode(array('status'=>'1','msg'=>'Connection successful! API is reachable (HTTP '.$result['code'].').'));
        } else {
            echo json_encode(array('status'=>'0','msg'=>'API unreachable: '.(isset($result['error']) ? $result['error'] : 'No response.')));
        }
    } catch (Exception $e) {
        echo json_encode(array('status'=>'0','msg'=>'Error: '.$e->getMessage()));
    }
    exit;
}

// ════════════════════════════════════════════════════════════════
// ACTION: admin_view_card
// Fetches NFC card details — drills into response.card_detail
// ════════════════════════════════════════════════════════════════
if ($action === 'admin_view_card') {
    $card_id = isset($_POST['card_id']) ? trim($_POST['card_id']) : '';
    $user_id = (int)(isset($_POST['user_id']) ? $_POST['user_id'] : 0);

    if (!$card_id) { echo json_encode(array('status'=>'0','msg'=>'Invalid card ID.')); exit; }

    // Always get local DB row first
    try {
        $local = $pdo->prepare("SELECT vc.*, u.full_name as user_name, u.email as user_email FROM virtual_cards vc LEFT JOIN users u ON u.id = vc.user_id WHERE vc.card_id = :cid LIMIT 1");
        $local->execute(array('cid' => $card_id));
        $local_data = $local->fetch(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        $local_data = null;
    }

    try {
        $api    = initApi($pdo);
        $result = $api->getCardDetails($card_id);
    } catch (Exception $e) {
        $result = array('success'=>false,'error'=>$e->getMessage(),'data'=>null);
    }

    if ($result['success'] && !empty($result['data'])) {
        $d = $result['data'];

        // NFC fetch-nfccard-detail: response.card_detail holds the actual card fields
        if (isset($d['card_detail']) && is_array($d['card_detail'])) {
            $d = $d['card_detail'];
        }

        // Merge API data over local DB data (API wins for card fields)
        if ($local_data) {
            $merged = array_merge($local_data, $d);
        } else {
            $merged = $d;
        }

        // Always use StroWallet's default billing address
        $merged['billing_address'] = '3401 N. Miami, Ave. Ste 230';
        $merged['billing_city']    = 'Miami';
        $merged['billing_state']   = 'Florida';
        $merged['billing_zip']     = '33127';
        $merged['billing_country'] = 'United States';

        echo json_encode(array('status'=>'1','card'=>$merged));
    } else {
        // Return local DB data as fallback
        if ($local_data) {
            $local_data['billing_address'] = '3401 N. Miami, Ave. Ste 230';
            $local_data['billing_city']    = 'Miami';
            $local_data['billing_state']   = 'Florida';
            $local_data['billing_zip']     = '33127';
            $local_data['billing_country'] = 'United States';
            echo json_encode(array('status'=>'1','card'=>$local_data));
        } else {
            echo json_encode(array('status'=>'0','msg'=>isset($result['error']) ? $result['error'] : 'Card not found.'));
        }
    }
    exit;
}

// ════════════════════════════════════════════════════════════════
// ACTION: admin_freeze_card
// NFC endpoint: POST nfc-cards/status/ status=frozen|active
// ════════════════════════════════════════════════════════════════
if ($action === 'admin_freeze_card') {
    $card_id      = isset($_POST['card_id'])      ? trim($_POST['card_id'])      : '';
    $freeze_action= isset($_POST['freeze_action']) ? trim($_POST['freeze_action']) : '';

    if (!in_array($freeze_action, array('freeze','unfreeze'))) {
        echo json_encode(array('status'=>'0','msg'=>'Invalid action.')); exit;
    }

    try {
        $api    = initApi($pdo);
        $result = ($freeze_action === 'freeze')
            ? $api->freezeCard($card_id)
            : $api->unfreezeCard($card_id);
    } catch (Exception $e) {
        echo json_encode(array('status'=>'0','msg'=>$e->getMessage())); exit;
    }

    // Accept: API success OR confirmed status in response
    $confirmed = '';
    if (!empty($result['data']) && isset($result['data']['status'])) {
        $confirmed = strtolower($result['data']['status']);
    }
    $expected = ($freeze_action === 'freeze') ? 'frozen' : 'active';
    $accepted = $result['success'] || $confirmed === $expected;

    if ($accepted) {
        $is_frozen = ($expected === 'frozen') ? 1 : 0;
        try {
            $pdo->prepare("UPDATE virtual_cards SET is_frozen = :f, status = :s WHERE card_id = :cid")
                ->execute(array('f'=>$is_frozen,'s'=>$expected,'cid'=>$card_id));
        } catch (PDOException $e) { /* */ }
        $msg = ($freeze_action === 'freeze') ? 'Card frozen successfully.' : 'Card unfrozen successfully.';
        echo json_encode(array('status'=>'1','msg'=>$msg));
    } else {
        $err = !empty($result['error']) ? $result['error'] : 'Operation failed.';
        echo json_encode(array('status'=>'0','msg'=>$err));
    }
    exit;
}

// ════════════════════════════════════════════════════════════════
// ACTION: admin_delete_card
// NFC has no delete endpoint — freeze card + mark terminated locally
// ════════════════════════════════════════════════════════════════
if ($action === 'admin_delete_card') {
    $card_id = isset($_POST['card_id']) ? trim($_POST['card_id']) : '';
    if (!$card_id) { echo json_encode(array('status'=>'0','msg'=>'Invalid card ID.')); exit; }

    // Freeze card via API (closest to deletion in NFC)
    try {
        $api = initApi($pdo);
        $api->freezeCard($card_id);
    } catch (Exception $e) { /* proceed regardless */ }

    // Mark terminated in local DB
    try {
        $pdo->prepare("UPDATE virtual_cards SET status = 'terminated', is_frozen = 1, updated_at = NOW() WHERE card_id = :cid")
            ->execute(array('cid' => $card_id));
        echo json_encode(array('status'=>'1','msg'=>'Card terminated successfully.'));
    } catch (PDOException $e) {
        echo json_encode(array('status'=>'0','msg'=>'DB error: '.$e->getMessage()));
    }
    exit;
}

// ════════════════════════════════════════════════════════════════
// ACTION: admin_get_txns
// NFC endpoint: GET nfc-card-transactions/
// ════════════════════════════════════════════════════════════════
if ($action === 'admin_get_txns') {
    $card_id = isset($_POST['card_id']) ? trim($_POST['card_id']) : '';
    if (!$card_id) { echo json_encode(array('status'=>'0','msg'=>'Invalid card ID.')); exit; }

    try {
        $api    = initApi($pdo);
        $result = $api->getCardTransactions($card_id);
    } catch (Exception $e) {
        $result = array('success'=>false,'error'=>$e->getMessage(),'data'=>null);
    }

    if ($result['success'] && !empty($result['data'])) {
        $data = $result['data'];
        // Drill into card_transactions sub-key
        if (isset($data['card_transactions']) && is_array($data['card_transactions'])) {
            $txns = $data['card_transactions'];
        } elseif (is_array($data) && isset($data[0])) {
            $txns = $data;
        } else {
            $txns = array();
        }
        echo json_encode(array('status'=>'1','transactions'=>$txns));
    } else {
        // Fallback: local DB
        try {
            $stmt = $pdo->prepare("SELECT * FROM virtual_card_transactions WHERE card_id = :cid ORDER BY created_at DESC LIMIT 50");
            $stmt->execute(array('cid'=>$card_id));
            echo json_encode(array('status'=>'1','transactions'=>$stmt->fetchAll(PDO::FETCH_ASSOC)));
        } catch (PDOException $e) {
            echo json_encode(array('status'=>'0','msg'=>'Could not load transactions.'));
        }
    }
    exit;
}

echo json_encode(array('status'=>'0','msg'=>'Invalid action.'));
exit;