<?php
require_once '../includes/config.php';
requireLogin();
$user = getCurrentUser();
$db   = getDB();

// bKash credentials from settings
$bkash_app_key    = getSetting('bkash_app_key')    ?? '';
$bkash_app_secret = getSetting('bkash_app_secret') ?? '';
$bkash_username   = getSetting('bkash_username')   ?? '';
$bkash_password   = getSetting('bkash_password')   ?? '';
$bkash_mode       = getSetting('bkash_mode')        ?? 'sandbox';

$base_url = $bkash_mode === 'live'
    ? 'https://tokenized.pay.bka.sh/v1.2.0-beta'
    : 'https://tokenized.sandbox.bka.sh/v1.2.0-beta';

if (!$bkash_app_key || !$bkash_username) {
    jsonResponse(false, 'bKash not configured. Please contact admin.');
}

$input  = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? '';
$amount = floatval($input['amount'] ?? 0);

// ===== GET TOKEN =====
function bkash_token($base_url, $app_key, $app_secret, $username, $password) {
    $data = json_encode(['app_key'=>$app_key,'app_secret'=>$app_secret]);
    $ch = curl_init($base_url.'/tokenized/checkout/token/grant');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => $data,
        CURLOPT_HTTPHEADER     => [
            'Content-Type: application/json',
            'username: '.$username,
            'password: '.$password,
        ],
        CURLOPT_SSL_VERIFYPEER => false,
    ]);
    $res = curl_exec($ch);
    curl_close($ch);
    return json_decode($res, true);
}

// ===== CREATE PAYMENT =====
if ($action === 'create') {
    if ($amount < 1) jsonResponse(false, 'Invalid amount');

    $tokenRes = bkash_token($base_url, $bkash_app_key, $bkash_app_secret, $bkash_username, $bkash_password);
    $token = $tokenRes['id_token'] ?? null;
    if (!$token) jsonResponse(false, 'bKash token error: '.($tokenRes['msg']??'Unknown'));

    $ref = 'BK'.strtoupper(substr(uniqid(),7));
    $siteUrl = getSetting('site_url') ?: 'https://p1.enotice.top/telecom';

    $data = json_encode([
        'mode'            => '0011',
        'payerReference'  => $user['phone'],
        'callbackURL'     => $siteUrl.'/api/bkash_callback.php',
        'amount'          => number_format($amount, 2, '.', ''),
        'currency'        => 'BDT',
        'intent'          => 'sale',
        'merchantInvoiceNumber' => $ref,
    ]);

    $ch = curl_init($base_url.'/tokenized/checkout/create');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => $data,
        CURLOPT_HTTPHEADER     => [
            'Content-Type: application/json',
            'Authorization: '.$token,
            'X-APP-Key: '.$bkash_app_key,
        ],
        CURLOPT_SSL_VERIFYPEER => false,
    ]);
    $res = json_decode(curl_exec($ch), true);
    curl_close($ch);

    if (($res['statusCode']??'') === '0000') {
        // Save pending payment
        $db->prepare("INSERT INTO deposits (user_id,amount,method,transaction_ref,status) VALUES (?,?,'bkash',?,?)")
           ->execute([$user['id'], $amount, $ref, 'pending']);
        // Store token temporarily
        $db->prepare("INSERT INTO settings (`key`,`value`) VALUES (?,?) ON DUPLICATE KEY UPDATE `value`=?")
           ->execute(['bkash_tmp_'.$ref, json_encode(['token'=>$token,'user_id'=>$user['id'],'amount'=>$amount]), json_encode(['token'=>$token,'user_id'=>$user['id'],'amount'=>$amount])]);

        jsonResponse(true, 'Payment created', [
            'bkash_url'  => $res['bkashURL'],
            'payment_id' => $res['paymentID'],
            'ref'        => $ref,
        ]);
    } else {
        jsonResponse(false, 'bKash error: '.($res['statusMessage']??'Unknown error'));
    }
}

// ===== EXECUTE PAYMENT =====
if ($action === 'execute') {
    $paymentID = $input['paymentID'] ?? '';
    $ref       = $input['ref'] ?? '';
    if (!$paymentID || !$ref) jsonResponse(false, 'Invalid request');

    // Get stored token
    $tmpData = $db->query("SELECT value FROM settings WHERE `key`='bkash_tmp_{$ref}'")->fetchColumn();
    $tmp = $tmpData ? json_decode($tmpData, true) : null;
    if (!$tmp) jsonResponse(false, 'Session expired');

    $ch = curl_init($base_url.'/tokenized/checkout/execute');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode(['paymentID'=>$paymentID]),
        CURLOPT_HTTPHEADER     => [
            'Content-Type: application/json',
            'Authorization: '.$tmp['token'],
            'X-APP-Key: '.$bkash_app_key,
        ],
        CURLOPT_SSL_VERIFYPEER => false,
    ]);
    $res = json_decode(curl_exec($ch), true);
    curl_close($ch);

    if (($res['statusCode']??'') === '0000' && ($res['transactionStatus']??'') === 'Completed') {
        $trxId  = $res['trxID'];
        $amount = floatval($res['amount']);

        // Add balance
        $db->prepare("UPDATE users SET balance=balance+? WHERE id=?")->execute([$amount, $user['id']]);
        $newBal = floatval($db->query("SELECT balance FROM users WHERE id={$user['id']}")->fetchColumn());
        $oldBal = $newBal - $amount;

        // Update deposit
        $db->prepare("UPDATE deposits SET status='approved', transaction_ref=? WHERE transaction_ref=?")->execute([$trxId, $ref]);

        // Transaction record
        $db->prepare("INSERT INTO transactions (user_id,type,amount,charge,net_amount,balance_before,balance_after,reference,status,note) VALUES (?,?,?,0,?,?,?,?,?,?)")
           ->execute([$user['id'],'deposit',$amount,$amount,$oldBal,$newBal,$trxId,'success','bKash deposit: '.$trxId]);

        // Notification
        $db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'success')")
           ->execute([$user['id'],'✅ bKash Payment Successful!','৳'.number_format($amount,2).' added to your balance via bKash. TrxID: '.$trxId]);

        // Cleanup tmp
        $db->prepare("DELETE FROM settings WHERE `key`=?")->execute(['bkash_tmp_'.$ref]);

        jsonResponse(true, '✅ Payment successful!', [
            'amount'      => $amount,
            'trxID'       => $trxId,
            'new_balance' => $newBal,
        ]);
    } else {
        jsonResponse(false, 'Payment failed: '.($res['statusMessage']??'Unknown'));
    }
}

jsonResponse(false, 'Invalid action');
