<?php
session_start();
header('Content-Type: application/json');
require_once '../../config/database.php';

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    echo json_encode(['success' => false, 'message' => 'غير مصرح']);
    exit;
}

$id = $_GET['id'] ?? 0;

$database = new Database();
$conn = $database->getConnection();

try {
    $stmt = $conn->prepare("
        SELECT cb.*, c.title as consultation_title, c.price, c.discount_price, 
               u.name as user_name, u.phone as user_phone, u.email as user_email
        FROM consultation_bookings cb
        LEFT JOIN consultations c ON cb.consultation_id = c.id
        LEFT JOIN users u ON cb.user_id = u.id
        WHERE cb.id = ?
    ");
    $stmt->execute([$id]);
    $booking = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($booking) {
        // Format dates
        $booking['booking_date'] = date('Y-m-d', strtotime($booking['booking_date']));
        $booking['booking_time'] = date('h:i A', strtotime($booking['booking_time']));
        $booking['created_at'] = date('Y-m-d h:i A', strtotime($booking['created_at']));
        
        echo json_encode(['success' => true, 'booking' => $booking]);
    } else {
        echo json_encode(['success' => false, 'message' => 'الحجز غير موجود']);
    }
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'حدث خطأ: ' . $e->getMessage()]);
}
