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

$input       = json_decode(file_get_contents('php://input'), true);
$phone       = preg_replace('/[^0-9]/', '', $input['phone'] ?? '');
$operator_id = intval($input['operator_id'] ?? 0);
$package_id  = intval($input['package_id'] ?? 0);
$amount      = floatval($input['amount'] ?? 0);

if (!$phone || !$operator_id || !$package_id || $amount <= 0) jsonResponse(false, 'সব তথ্য সঠিকভাবে দিন!');
if (strlen($phone) !== 11) jsonResponse(false, 'সঠিক ফোন নম্বর দিন! (১১ ডিজিট)');

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

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

$op = $db->prepare("SELECT * FROM operators WHERE id=? AND status='active'");
$op->execute([$operator_id]);
$operator = $op->fetch();
if (!$operator) jsonResponse(false, 'অপারেটর পাওয়া যায়নি!');

$pkg = $db->prepare("SELECT * FROM packages WHERE id=? AND status='active'");
$pkg->execute([$package_id]);
$package = $pkg->fetch();
if (!$package) jsonResponse(false, 'প্যাকেজ পাওয়া যায়নি!');

$ref            = generateRef();
$balance_before = $user['balance'];
$balance_after  = $balance_before - $amount;
$api_key        = getSetting('successtopup_key');
$api_secret     = getSetting('successtopup_secret');
$api_pkg_id     = $package['api_package_id'] ?? null;

$db->beginTransaction();
try {
    // ব্যালেন্স কেটে রাখো
    $db->prepare("UPDATE users SET balance = balance - ? WHERE id=?")->execute([$amount, $user['id']]);

    $status       = 'pending';
    $note         = 'Package: ' . $package['name'] . ' | Awaiting admin approval';
    $api_response = null;
    $api_tried    = false;
    $commissionAmt = 0;

    // API Key ও Package ID থাকলে চেষ্টা করো
    if ($api_key && $api_secret && $api_pkg_id) {
        $api_tried    = true;
        $api_response = successTopupDrive($phone, $api_pkg_id, $operator['code'], $ref);

        if (isset($api_response['result']) && $api_response['result'] === true) {
            // ✅ API SUCCESS
            $status = 'success';
            $note   = 'Drive via SuccessTopUp API ✅ | ' . $package['name'];

            // Commission যোগ করো
            $commPct = floatval($operator['commission_percent'] ?? 0);
            if ($commPct > 0) {
                $commissionAmt = round($amount * $commPct / 100, 2);
                $db->prepare("UPDATE users SET balance = balance + ? WHERE id=?")->execute([$commissionAmt, $user['id']]);
                $db->prepare("INSERT INTO transactions (user_id,type,amount,charge,net_amount,balance_before,balance_after,reference,status,note) VALUES (?,?,?,0,?,?,?,?,?,?)")
                   ->execute([$user['id'],'commission',$commissionAmt,$commissionAmt,
                       $balance_after,$balance_after+$commissionAmt,'CM-'.$ref,'success',
                       'Commission '.$commPct.'% for drive ৳'.$amount]);
                $db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'success')")
                   ->execute([$user['id'],'🎁 কমিশন পেয়েছেন!',
                       CURRENCY.number_format($commissionAmt,2).' কমিশন যোগ হয়েছে।']);
            }

        } else {
            // ❌ API FAILED — Pending রাখো
            $status = 'pending';
            $apiMsg = $api_response['message'] ?? 'API failed';
            $note   = 'API failed: '.$apiMsg.' | Package: '.$package['name'].' | Awaiting admin approval';
        }
    } elseif ($api_key && $api_secret && !$api_pkg_id) {
        // API আছে কিন্তু package ID নেই — pending
        $note = 'Package: '.$package['name'].' | No API package ID | Awaiting admin approval';
    }

    // Transaction save
    $stmt = $db->prepare("INSERT INTO transactions
        (user_id, type, amount, charge, net_amount, balance_before, balance_after,
         operator_id, package_id, phone_number, reference, status, note, api_response)
        VALUES (?, 'drive', ?, 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute([
        $user['id'], $amount, $amount,
        $balance_before, $balance_after,
        $operator_id, $package_id, $phone, $ref,
        $status, $note,
        $api_response ? json_encode($api_response) : null
    ]);

    // User notification
    if ($status === 'success') {
        $notifMsg = $phone.' নম্বরে '.$package['name'].' সক্রিয় হয়েছে।';
        if ($commissionAmt > 0) $notifMsg .= ' কমিশন: '.CURRENCY.number_format($commissionAmt,2);
        $db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'success')")
           ->execute([$user['id'], '✅ Drive সফল!', $notifMsg]);
    }

    // Admin notification
    $adminTitle = $status === 'success' ? '✅ Auto Drive Success' : '⏳ নতুন Drive রিকোয়েস্ট';
    $adminMsg   = $user['name'].' → '.$phone.' | '.$package['name'].' | ৳'.number_format($amount,2)
                . ($status === 'success' ? ' [AUTO ✅]' : ' [PENDING]');
    $db->prepare("INSERT INTO notifications (title,message,type,is_global) VALUES (?,?,'info',0)")
       ->execute([$adminTitle, $adminMsg]);

    $db->commit();

    // Telegram
    if ($status === 'success') {
        notifyDriveSuccess($user['name'], $phone, $package['name'], number_format($amount,2), $ref, number_format($commissionAmt,2));
    } else {
        notifyDriveRequest($user['name'], $phone, $package['name'], number_format($amount,2), $operator['name'], $ref);
        // Universal pending notify
        notifyPending('drive', $user['name'], [
            '📱 নম্বর'    => $phone,
            '📡 অপারেটর' => $operator['name'],
            '📦 প্যাকেজ'  => $package['name'],
            '💰 মূল্য'    => CURRENCY . number_format($amount, 2),
            '🔖 Ref'      => $ref,
        ]);
    }

    // User response
    if ($status === 'success') {
        jsonResponse(true, '✅ Drive সফল! '.$package['name'].' সক্রিয় হবে।', [
            'reference'    => $ref,
            'new_balance'  => $balance_after + $commissionAmt,
            'status'       => 'success',
            'commission'   => $commissionAmt
        ]);
    } else {
        $userMsg = $api_tried
            ? '⏳ Drive রিকোয়েস্ট পাঠানো হয়েছে। API সমস্যায় Admin অনুমোদন করবেন।'
            : '⏳ Drive রিকোয়েস্ট পাঠানো হয়েছে। Admin অনুমোদনের পরে সক্রিয় হবে।';
        jsonResponse(true, $userMsg, [
            'reference'   => $ref,
            'new_balance' => $balance_after,
            'status'      => 'pending'
        ]);
    }

} catch (Exception $e) {
    $db->rollBack();
    jsonResponse(false, 'সিস্টেম ত্রুটি! আবার চেষ্টা করুন।');
}
