<?php
require_once '../includes/config.php';
require_once '../includes/commission.php';
require_once '../includes/dingconnect.php';
require_once '../includes/telegram.php';
requireLogin();

$input    = json_decode(file_get_contents('php://input'), true);
$sku      = sanitize($input['sku_code']  ?? '');
$amount   = floatval($input['amount']    ?? 0);
$currency = sanitize($input['currency'] ?? 'USD');
$pinName  = sanitize($input['pin_name'] ?? '');
$country  = sanitize($input['country']  ?? '');
$cardType = sanitize($input['card_type'] ?? 'pin'); // pin | gift

// Determine transaction type
$txnType = ($cardType === 'gift') ? 'gift' : 'pin';

if (!$sku || $amount <= 0) jsonResponse(false, 'সব তথ্য দিন!');

$user = getCurrentUser();
$db   = getDB();

$bdtAmount      = usdToBdt($amount);
$balance_before = $user['balance'];
$balance_after  = $balance_before - $bdtAmount;

if ($user['balance'] < $bdtAmount) {
    jsonResponse(false, 'অপর্যাপ্ত ব্যালেন্স! আপনার ব্যালেন্স: ৳'.number_format($user['balance'],2));
}

$ref       = 'PIN' . strtoupper(substr(md5(uniqid()), 0, 8));
$ding_mode = getSetting('ding_mode') ?: 'manual';

$db->beginTransaction();
try {
    $db->prepare("UPDATE users SET balance = balance - ? WHERE id=?")->execute([$bdtAmount, $user['id']]);

    $status   = 'pending';
    $pin_code = null;
    $note     = 'PIN: '.$pinName.' | SKU: '.$sku.' | '.CURRENCY.$bdtAmount;
    $api_resp = null;

    if ($ding_mode === 'auto' && dingIsConfigured()) {
        // PIN products এ AccountNumber = dummy
        $api_resp = dingBuyPin($sku, $amount, $ref);

        if (isset($api_resp['ResultCode']) && $api_resp['ResultCode'] == 1) {
            $status   = 'success';
            $pin_code = $api_resp['_pin_code']     ?? null;
            $receipt  = $api_resp['_receipt_text'] ?? '';
            if (!$pin_code && $receipt) $pin_code = $receipt;
            $note = 'PIN purchased ✅ | '.$pinName.' | PIN: '.($pin_code ?: 'See receipt');
        } else {
            $errCode = $api_resp['ErrorCodes'][0]['Code']    ?? 'Unknown';
            $errCtx  = $api_resp['ErrorCodes'][0]['Context'] ?? '';
            $note    = 'DingConnect Error: '.$errCode.' | '.$errCtx.' | Pending admin';
            $status  = 'pending';
        }
    }

    // Save transaction
    $db->prepare("INSERT INTO transactions
        (user_id,type,amount,charge,net_amount,balance_before,balance_after,
         reference,status,note,api_response)
        VALUES (?,?,?,0,?,?,?,?,?,?,?)")
       ->execute([
           $user['id'],$txnType,$bdtAmount,$bdtAmount,
           $balance_before,$balance_after,
           $ref,$status,$note,
           $api_resp ? json_encode($api_resp) : null
       ]);

    // Save PIN to user_cards table
    if ($pin_code) {
        try {
            $db->prepare("INSERT INTO user_cards (user_id,transaction_ref,card_name,card_type,sku_code,pin_code,amount,currency,status) VALUES (?,?,?,?,?,?,?,?,'active')")
               ->execute([$user['id'],$ref,$pinName,$txnType,$sku,$pin_code,$amount,$currency]);
        } catch(Exception $e) {}
        // User notification
        $db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'success')")
           ->execute([$user['id'],'🔢 PIN Purchase Successful!',$pinName.' — PIN: '.$pin_code]);
        notifyUser($user['id'], 'PIN/Gift Card কেনা সফল! 🔑', ['💰 পরিমাণ'=>CURRENCY.number_format($amount??0,2), '🔖 Ref'=>$ref??'']);
        // Commission
        applyCommission($db, $user['id'], $txnType, $bdtAmount, $ref);
    }

    // Telegram pending notification
    if ($status === 'pending') {
        notifyPending('other', $user['name'], [
            '🔢 PIN'     => $pinName,
            '🌍 দেশ'     => $country,
            '💰 পরিমাণ'  => $currency.' '.$amount,
            '🔖 Ref'     => $ref,
        ]);
    }

    $db->commit();

    $msg = $status === 'success'
        ? '✅ PIN কেনা সফল হয়েছে!'
        : '⏳ রিকোয়েস্ট পাঠানো হয়েছে। Admin অনুমোদন করবেন।';

    jsonResponse(true, $msg, [
        'reference'   => $ref,
        'pin_code'    => $pin_code,
        'status'      => $status,
        'new_balance' => $balance_after,
    ]);

} catch (Exception $e) {
    $db->rollBack();
    jsonResponse(false, 'সিস্টেম ত্রুটি: '.$e->getMessage());
}
