<?php
/**
 * Service Details API
 * Fetch detailed information about a specific service reservation
 */

require_once __DIR__ . '/../config/session.php';
require_once __DIR__ . '/../config/database.php';

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

// Check if user is logged in
if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode([
        'success' => false,
        'message' => 'Not authenticated'
    ]);
    exit();
}

$userId = getCurrentUserId();
$serviceId = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (!$serviceId) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => 'Service ID is required'
    ]);
    exit();
}

try {
    // Keep reservation visible even if facility row was removed later.
    $sql = "SELECT sr.*,
                   f.name as facility_name,
                   f.description as facility_description,
                   f.icon
            FROM service_reservations sr
            LEFT JOIN facilities f ON sr.facility_id = f.id
            WHERE sr.id = ? AND sr.user_id = ?";

    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        throw new Exception('Unable to prepare query');
    }

    $stmt->bind_param('ii', $serviceId, $userId);
    $stmt->execute();
    $result = $stmt->get_result();

    if (!($result instanceof mysqli_result) || $result->num_rows === 0) {
        http_response_code(404);
        echo json_encode([
            'success' => false,
            'message' => 'Service reservation not found'
        ]);
        exit();
    }

    $service = $result->fetch_assoc();
    if (empty($service['facility_name'])) {
        $service['facility_name'] = 'Service';
    }

    echo json_encode([
        'success' => true,
        'service' => $service
    ]);
} catch (Throwable $e) {
    error_log('get-service-details error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Unable to load service details right now'
    ]);
}
?>
