<?php
/**
 * ajaxCalls/buyMatrixPackage.php  v8
 *
 * Manual purchase of a global matrix pool slot.
 * This records a REAL TX hash (not AUTO_) so it satisfies the gate
 * that unlocks the next working package step.
 *
 * Flow:
 *   1. Validate eligibility (trigger working pkg must be done)
 *   2. Enter BFS pool slot
 *   3. Record with real TX hash → gate satisfied → working pkg unlocked
 */
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'];
$matrixId = (int)  ($_POST['matrix_id']  ?? 0);
$pkgPrice = (float)($_POST['pkg_price']  ?? 0);
$trxAmt   = (float)($_POST['trx_amount'] ?? 0);
$txHash   = trim(   $_POST['trx_hash']   ?? '');
$myWallet = trim(   $_POST['wallet']     ?? '');

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

try {
    $db = getDB();

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

    // Validate eligibility (must have trigger working pkg)
    $engine  = new MatrixEngine();
    $result  = $engine->processGlobalPurchase($memberId, $matrixId, $pkgPrice, $txHash);

    if (isset($result['error'])) {
        ob_end_clean();
        echo json_encode(['status'=>'error','message'=>$result['error']]); exit;
    }

    // Update the purchase record with the real TX hash + wallet
    // (enterGlobalMatrix already inserted with 'MANUAL' via hash)
    $db->prepare(
        "UPDATE gm_package_purchases
         SET trx_hash=?, trx_amount=?, wallet_address=?
         WHERE member_id=? AND package_id=? AND buy_type=3
         ORDER BY id DESC LIMIT 1"
    )->execute([$txHash, $trxAmt, $myWallet, $memberId, $matrixId]);

    $mp = $db->prepare('SELECT * FROM meddolic_config_matrix_package WHERE matrixId=? LIMIT 1');
    $mp->execute([$matrixId]);
    $poolInfo = $mp->fetch();

    ob_end_clean();
    echo json_encode([
        'status'    => 'ok',
        'message'   => 'Successfully joined ' . ($poolInfo['poolName'] ?? 'pool') . '!',
        'entry_id'  => $result['entry_id'],
        'pool_name' => $poolInfo['poolName'] ?? '',
    ]);

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