<?php
session_start();
header('Content-Type: application/json');
if (empty($_SESSION['user'])) { echo json_encode(['success'=>false,'message'=>'Not authenticated']); exit; }

$input = json_decode(file_get_contents('php://input'), true);
$class_id = isset($input['class_id']) ? (int)$input['class_id'] : null;
$class_time = isset($input['class_time']) ? $input['class_time'] : null;
$credits_needed = isset($input['credits']) ? (int)$input['credits'] : 1;
if (!$class_id || !$class_time) { echo json_encode(['success'=>false,'message'=>'Missing class or time']); exit; }

// require bootstrap (project-root safe)
$root = dirname(__DIR__, 2);
require_once $root . '/bootstrap.php'; // must expose $db (PDO)

// require helper
require_once $root . '/lib/credits.php';

try {
    // Start a transaction so booking + credit consumption are atomic
    $db->beginTransaction();

    // consume credits (helper expects to run inside transaction when manageTx=false)
    $used = consume_credits($db, $_SESSION['user']['id'], $credits_needed, false);
    if ($used === false) {
        $db->rollBack();
        echo json_encode(['success'=>false,'message'=>'Insufficient credits']);
        exit;
    }

    // insert booking with consumed_credits set
    $stmt = $db->prepare('INSERT INTO bookings (user_id, class_id, class_time, consumed_credits, status, created_at) VALUES (?, ?, ?, ?, "booked", NOW())');
    $stmt->execute([$_SESSION['user']['id'], $class_id, $class_time, $credits_needed]);
    $bookingId = $db->lastInsertId();

    $db->commit();
    echo json_encode(['success'=>true,'message'=>'Booked', 'booking_id'=>$bookingId, 'used'=>$used]);
} catch (Exception $ex) {
    if ($db->inTransaction()) $db->rollBack();
    echo json_encode(['success'=>false,'message'=>'Error: ' . $ex->getMessage()]);
}