<?php
require 'config.php';
require_login();

header('Content-Type: application/json');

$user_id = $_SESSION['user_id'];
$cost = 3.0;

try {
    $pdo->beginTransaction();

    // ১. ব্যালেন্স চেক (row lock)
    $user = $pdo
        ->prepare("SELECT balance FROM users WHERE id = ? FOR UPDATE")
        ->execute([$user_id]);

    $user = $pdo
        ->query("SELECT balance FROM users WHERE id = $user_id FOR UPDATE")
        ->fetch(PDO::FETCH_ASSOC);

    if (!$user || $user['balance'] < $cost) {
        throw new Exception("আপনার পর্যাপ্ত ব্যালেন্স নেই।");
    }

    // ২. ব্যালেন্স আপডেট
    $new_balance = $user['balance'] - $cost;

    $pdo
        ->prepare("UPDATE users SET balance = ? WHERE id = ?")
        ->execute([$new_balance, $user_id]);

    // ৩. সার্ভিস ও সাবক্যাটাগরি আইডি
    $service = $pdo->query("SELECT id FROM services LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    $subcat  = $pdo->query("SELECT id FROM subcategories LIMIT 1")->fetch(PDO::FETCH_ASSOC);

    if ($service && $subcat) {
        $nid_number = $_POST['nid'] ?? 'N/A';

        $pdo
            ->prepare("
                INSERT INTO orders 
                (user_id, service_id, subcategory_id, price, id_number, status)
                VALUES (?, ?, ?, ?, ?, 'Completed')
            ")
            ->execute([
                $user_id,
                $service['id'],
                $subcat['id'],
                $cost,
                $nid_number
            ]);
    }

    $pdo->commit();

    echo json_encode([
        'success' => true,
        'message' => 'Balance deducted successfully'
    ]);

} catch (Throwable $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }

    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
