<?php
<?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);
$booking_id = isset($input['booking_id']) ? (int)$input['booking_id'] : 0;
if (!$booking_id) { echo json_encode(['success'=>false,'message'=>'Missing booking id']); exit; }

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

try {
  $db->beginTransaction();
  $stmt = $db->prepare('SELECT * FROM bookings WHERE id = ? AND user_id = ? FOR UPDATE');
  $stmt->execute([$booking_id, $_SESSION['user']['id']]);
  $b = $stmt->fetch(PDO::FETCH_ASSOC);
  if (!$b) { $db->rollBack(); echo json_encode(['success'=>false,'message'=>'Booking not found']); exit; }
  if ($b['status'] !== 'booked') { $db->rollBack(); echo json_encode(['success'=>false,'message'=>'Already cancelled']); exit; }

  $stmt = $db->prepare('UPDATE bookings SET status = "cancelled", cancelled_at = NOW() WHERE id = ?');
  $stmt->execute([$booking_id]);

  $refundCredits = (int)$b['consumed_credits'];
  if ($refundCredits > 0) {
    // create refund as a new bundle (1 month expiry)
    $stmt = $db->prepare('INSERT INTO credit_bundles (user_id, credits, credits_remaining, expires_at) VALUES (?, ?, ?, DATE_ADD(NOW(), INTERVAL 1 MONTH))');
    $stmt->execute([$_SESSION['user']['id'], $refundCredits, $refundCredits]);
  }

  $db->commit();
  echo json_encode(['success'=>true,'message'=>'Booking cancelled. Credits refunded if applicable.']);
} catch (Exception $ex) {
  if ($db->inTransaction()) $db->rollBack();
  echo json_encode(['success'=>false,'message'=>'Error: '.$ex->getMessage()]);
}