<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech

/**
 * XtraLogTools API Log Purchase Handler
 * API provider: TLogs Marketplace (https://tlogsmarketplace.com)
 * POST params: product_id (xtralog_products.id), quantity
 */

if (session_status() === PHP_SESSION_NONE) session_start();
header('Content-Type: application/json');

// ── Auth ──────────────────────────────────────────────────────────────────────
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true || !isset($_SESSION['user_id'])) {
    echo json_encode(['status' => '0', 'msg' => 'Unauthorized. Please log in.']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => '0', 'msg' => 'Invalid request method']);
    exit();
}

require_once dirname(__DIR__, 2) . '/include/config.php';
require_once dirname(__DIR__, 2) . '/include/XtraLogTools.php';

$user_id    = (int)$_SESSION['user_id'];
$product_db_id = filter_var($_POST['product_id'] ?? 0, FILTER_VALIDATE_INT);
$quantity   = max(1, (int)($_POST['quantity'] ?? 1));

if (!$product_db_id) {
    echo json_encode(['status' => '0', 'msg' => 'Invalid product selected.']);
    exit();
}

// ── Check XtraLogTools is enabled ─────────────────────────────────────────────
$xtl_enabled = (int)($site_data['xtralogtools_enabled'] ?? 0);
$xtl_key     = trim($site_data['xtralogtools_api_key'] ?? '');
$xtl_url     = trim($site_data['xtralogtools_api_url'] ?? '');

// Normalise URL
$xtl_url = preg_replace('#/[a-z_]+\.php$#i', '', rtrim($xtl_url, '/'));
if (empty($xtl_url) || !filter_var($xtl_url, FILTER_VALIDATE_URL)) {
    $xtl_url = XtraLogTools::BASE_URL;
}

if (!$xtl_enabled || empty($xtl_key)) {
    echo json_encode(['status' => '0', 'msg' => 'Logs API service is currently unavailable.']);
    exit();
}

try {
    $pdo->beginTransaction();

    // ── 1. Fetch product (lock row) ───────────────────────────────────────────
    $p_stmt = $pdo->prepare("SELECT * FROM xtralog_products WHERE id = :id AND status = 1 LIMIT 1 FOR UPDATE");
    $p_stmt->execute(['id' => $product_db_id]);
    $product = $p_stmt->fetch(PDO::FETCH_ASSOC);

    if (!$product) {
        $pdo->rollBack();
        echo json_encode(['status' => '0', 'msg' => 'Product not found or is currently unavailable.']);
        exit();
    }

    $unit_price   = (float)$product['our_price'];
    $total_charge = round($unit_price * $quantity, 2);

    if ($total_charge <= 0) {
        $pdo->rollBack();
        echo json_encode(['status' => '0', 'msg' => 'Invalid product price.']);
        exit();
    }

    // ── 2. Fetch user balance (lock) ──────────────────────────────────────────
    $u_stmt = $pdo->prepare("SELECT id, main_balance, username, email FROM users WHERE id = :uid LIMIT 1 FOR UPDATE");
    $u_stmt->execute(['uid' => $user_id]);
    $user_row = $u_stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user_row) {
        $pdo->rollBack();
        echo json_encode(['status' => '0', 'msg' => 'User not found.']);
        exit();
    }

    $balance = (float)$user_row['main_balance'];

    if ($balance < $total_charge) {
        $pdo->rollBack();
        echo json_encode([
            'status' => '0',
            'msg'    => 'Insufficient balance. You need ₦' . number_format($total_charge, 2) . ' but have ₦' . number_format($balance, 2) . '.',
        ]);
        exit();
    }

    // ── 3. Deduct balance immediately ─────────────────────────────────────────
    $pdo->prepare("UPDATE users SET main_balance = main_balance - :charge, updated_at = NOW() WHERE id = :uid")
        ->execute(['charge' => $total_charge, 'uid' => $user_id]);

    // ── 4. Generate order reference ───────────────────────────────────────────
    $order_ref = 'XTLLOG_' . strtoupper(substr(md5(uniqid(mt_rand(), true)), 0, 12)) . '_' . time();

    // ── 5. Insert pending order ───────────────────────────────────────────────
    $ins = $pdo->prepare("
        INSERT INTO xtralog_orders
            (user_id, product_id, product_name, server, quantity, unit_price, total_charge, order_ref, status, created_at)
        VALUES
            (:uid, :pid, :pname, :server, :qty, :unit, :total, :ref, 'pending', NOW())
    ");
    $ins->execute([
        'uid'    => $user_id,
        'pid'    => $product['product_id'],
        'pname'  => $product['product_name'],
        'server' => (int)$product['server'],
        'qty'    => $quantity,
        'unit'   => $unit_price,
        'total'  => $total_charge,
        'ref'    => $order_ref,
    ]);
    $db_order_id = (int)$pdo->lastInsertId();

    // ── 6. Call XtraLogTools API ──────────────────────────────────────────────
    $xtl    = new XtraLogTools($xtl_key, $xtl_url);
    $result = $xtl->buyLogs($product['product_id'], (int)$product['server'], $quantity);

    $api_response_json = json_encode($result['data'] ?? []);

    if ($result['success']) {
        $logs_data = $result['logs'] ?? '';

        // Update order to completed
        $pdo->prepare("
            UPDATE xtralog_orders
            SET status = 'completed', logs_data = :logs, api_response = :resp, updated_at = NOW()
            WHERE id = :id
        ")->execute(['logs' => $logs_data, 'resp' => $api_response_json, 'id' => $db_order_id]);

        // Log in transactions table
        $txn_ref = 'XTLLOG_TXN_' . strtoupper(uniqid()) . '_' . time();
        $ip      = $_SERVER['REMOTE_ADDR'] ?? null;
        $pdo->prepare("
            INSERT INTO transactions
                (user_id, transaction_ref, payment_gateway, transaction_type, amount, currency, status, ip_address, metadata, created_at)
            VALUES
                (:uid, :ref, 'balance', 'logs_purchase', :amount, 'NGN', 'successful', :ip, :meta, NOW())
        ")->execute([
            'uid'    => $user_id,
            'ref'    => $txn_ref,
            'amount' => $total_charge,
            'ip'     => $ip,
            'meta'   => json_encode([
                'source'       => 'xtralogstools',
                'product_id'   => $product['product_id'],
                'product_name' => $product['product_name'],
                'server'       => $product['server'],
                'quantity'     => $quantity,
                'order_ref'    => $order_ref,
            ]),
        ]);

        $pdo->commit();

        echo json_encode([
            'status'   => '1',
            'msg'      => 'Purchase successful! Your log credentials are ready.',
            'order_id' => $db_order_id,
            'logs'     => $logs_data,
        ]);

    } else {
        // API failed — refund the user
        $pdo->prepare("UPDATE users SET main_balance = main_balance + :charge, updated_at = NOW() WHERE id = :uid")
            ->execute(['charge' => $total_charge, 'uid' => $user_id]);

        // Mark order as failed
        $pdo->prepare("
            UPDATE xtralog_orders
            SET status = 'failed', api_response = :resp, updated_at = NOW()
            WHERE id = :id
        ")->execute(['resp' => $api_response_json, 'id' => $db_order_id]);

        $pdo->commit();

        $err_msg = $result['error'] ?? 'Unknown error from provider.';
        error_log('[purchase_log_api] API error for user ' . $user_id . ': ' . $err_msg);

        echo json_encode([
            'status' => '0',
            'msg'    => 'Purchase failed: ' . htmlspecialchars($err_msg) . ' Your balance has been refunded.',
        ]);
    }

} catch (PDOException $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    error_log('[purchase_log_api] DB error: ' . $e->getMessage());
    echo json_encode(['status' => '0', 'msg' => 'A server error occurred. Please try again.']);
} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    error_log('[purchase_log_api] Exception: ' . $e->getMessage());
    echo json_encode(['status' => '0', 'msg' => 'An unexpected error occurred.']);
}
