<?php
/**
 * ajaxCalls/buyNormalPackage.php  v11
 *
 * RULES:
 * - Packages $30,$40 = Registration only (processRegister.php handles those)
 * - This file handles pkg3($60), pkg4($200), pkg5($500), pkg6, pkg7, pkg8
 * - Pays income (referral + upgrade) via processManualUpgrade()
 * - Does NOT auto-enter global matrix (except pkg3 auto-enters SMART — handled in engine)
 * - Does NOT call checkWorkingAutoUpgrade (auto-upgrade only via 3/9/27 team, called AFTER commit)
 */
ob_start();
header('Content-Type: application/json');

$absDir = dirname(__DIR__, 2);
require_once $absDir . '/connection/db.php';
require_once $absDir . '/connection/MatrixEngine.php';

register_shutdown_function(function () {
    $err = error_get_last();
    if ($err && in_array($err['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) {
        ob_clean();
        echo json_encode(['status' => 'error', 'message' => 'PHP Fatal: ' . $err['message']]);
    }
});

requireLogin();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    ob_end_clean();
    echo json_encode(['status' => 'error', 'message' => 'POST only']);
    exit;
}

$memberId = (int)$_SESSION['member_id'];
$pkgId    = (int)($_POST['pkg_id']     ?? 0);
$pkgPrice = (float)($_POST['pkg_price']  ?? 0);
$trxAmt   = (float)($_POST['trx_amount'] ?? 0);
$txHash   = trim($_POST['trx_hash']   ?? '');
$myWallet = trim($_POST['wallet']     ?? '');
$trxPrice = (float)($_POST['trx_price']  ?? 3.48);

if (!$pkgId || !$pkgPrice || !$txHash || !$myWallet) {
    ob_end_clean();
    echo json_encode(['status' => 'error', 'message' => 'Missing required fields']);
    exit;
}

// Packages 1 & 2 ($30/$40) are registration-only — handled by processRegister.php
if ($pkgId <= 2) {
    ob_end_clean();
    echo json_encode(['status' => 'error', 'message' => 'Registration packages are processed during registration only.']);
    exit;
}

try {
    $db = getDB();

    // Duplicate TX guard
    $txChk = $db->prepare('SELECT id FROM gm_package_purchases WHERE trx_hash=? LIMIT 1');
    $txChk->execute([$txHash]);
    if ($txChk->fetch()) {
        ob_end_clean();
        echo json_encode(['status' => 'error', 'message' => 'Transaction already processed']);
        exit;
    }

    // Package must exist and be active
    $pkgQ = $db->prepare('SELECT * FROM meddolic_config_pool_list WHERE id=? AND poolStatus=1 LIMIT 1');
    $pkgQ->execute([$pkgId]);
    $pkg = $pkgQ->fetch();
    if (!$pkg) {
        ob_end_clean();
        echo json_encode(['status' => 'error', 'message' => 'Package not found']);
        exit;
    }

    $engine   = new MatrixEngine();
    $user     = getUserById($memberId);
    $sponsorId = (int)($user['sponser_id'] ?? 0);

    // Validate: sequential order + global-gate check
    $validErr = $engine->validateWorkingPurchase($memberId, $pkgId);
    if ($validErr) {
        ob_end_clean();
        echo json_encode(['status' => 'error', 'message' => $validErr]);
        exit;
    }

    $db->beginTransaction();

    // ── 1. Purchase log ───────────────────────────────────────────────
    $db->prepare(
        "INSERT INTO gm_package_purchases
           (member_id, sponser_id, package_id, package_price, trx_amount,
            trx_hash, wallet_address, buy_type, purchase_date, status)
         VALUES (?, ?, ?, ?, ?, ?, ?, 2, NOW(), 1)"
    )->execute([$memberId, $sponsorId, $pkgId, $pkgPrice, $trxAmt, $txHash, $myWallet]);

    // ── 2. Activation log ─────────────────────────────────────────────
    $db->prepare(
        "INSERT INTO meddolic_user_activation_details
           (member_id, sponser_id, packageId, investPrice, transHash,
            walletAddress, date_time, status, activate_by, buyType)
         VALUES (?, ?, ?, ?, ?, ?, NOW(), 1, ?, 2)"
    )->execute([$memberId, $sponsorId, $pkgId, $pkgPrice, $txHash, $myWallet, $memberId]);

    // ── 3. Process income distribution + advance package ──────────────
    //      (processManualUpgrade does NOT call checkWorkingAutoUpgrade)
    $result = $engine->processManualUpgrade($memberId, $sponsorId, $pkgPrice, $pkgId, $txHash);

    $db->commit();

    // ── 4. Post-commit: check if sponsor qualifies for auto-upgrade ───
    //      Only triggered by 3/9/27 team counts — not by direct purchase
    try {
        $engine->checkWorkingAutoUpgrade($sponsorId);
    } catch (Throwable $autoErr) {
        error_log('[buyNormalPackage] auto-upgrade error: ' . $autoErr->getMessage());
    }

    $preview     = $engine->calculateIncomePreview($pkgId, $pkgPrice);
 

    ob_end_clean();
    echo json_encode([
        'status'          => 'ok',
        'message'         => 'Package purchased!',
        'income'          => [
            'sponsor_net' => $preview['direct_net']  ?? 0,
            'upline_net'  => $preview['upline_net']  ?? 0,
            'admin_fee'   => $preview['total_admin'] ?? 0,
        ],
      
    ]);

} catch (Throwable $e) {
    if (isset($db) && $db->inTransaction()) $db->rollBack();
    error_log('[buyNormalPackage] ' . $e->getMessage());
    ob_end_clean();
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
