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

if (session_status() === PHP_SESSION_NONE) session_start();

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

require_once '../include/config.php';

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

$service_id = filter_var($_POST['service_id'] ?? 0, FILTER_VALIDATE_INT);
$user_id    = (int)$_SESSION['user_id'];

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

try {
    // ── 1. Fetch service (lock row so concurrent purchases don't double-sell) ──
    $svc_stmt = $pdo->prepare("SELECT * FROM sm_services WHERE id = :id AND status = 'available' LIMIT 1 FOR UPDATE");

    $pdo->beginTransaction();

    $svc_stmt->execute(['id' => $service_id]);
    $service = $svc_stmt->fetch(PDO::FETCH_ASSOC);

    if (!$service) {
        $pdo->rollBack();
        echo json_encode(['status' => '0', 'msg' => 'This log is no longer available']);
        exit();
    }

    $price = (float)$service['amount'];

    // ── 2. Fetch user balance (lock) ──
    $usr_stmt = $pdo->prepare("SELECT id, main_balance, username, email FROM users WHERE id = :uid LIMIT 1 FOR UPDATE");
    $usr_stmt->execute(['uid' => $user_id]);
    $user_row = $usr_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 < $price) {
        $pdo->rollBack();
        echo json_encode(['status' => '0', 'msg' => 'Insufficient balance. Please fund your wallet.']);
        exit();
    }

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

    // ── 4. Create purchase record ──
    $order_id = 'LOG_' . strtoupper(substr(md5(uniqid(mt_rand(), true)), 0, 12));
    $pdo->prepare("INSERT INTO sm_purchases (user_id, service_id, amount, order_id, status, purchase_date)
                   VALUES (:uid, :sid, :amount, :order_id, 'completed', NOW())")
        ->execute(['uid' => $user_id, 'sid' => $service_id, 'amount' => $price, 'order_id' => $order_id]);

    // ── 5. Mark service as sold ──
    $pdo->prepare("UPDATE sm_services SET status = 'sold' WHERE id = :id")
        ->execute(['id' => $service_id]);

    // ── 6. Log in transactions table ──
    $txn_ref = 'LOG_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, created_at)
        VALUES
            (:uid, :ref, 'balance', 'logs_purchase', :amount, 'NGN', 'successful', :ip, NOW())
    ")->execute(['uid' => $user_id, 'ref' => $txn_ref, 'amount' => $price, 'ip' => $ip]);

    $pdo->commit();

    echo json_encode([
        'status' => '1',
        'msg'    => 'Purchase successful! "' . htmlspecialchars($service['service_name']) . '" is now in your logs.'
    ]);

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