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

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'يجب تسجيل الدخول']);
    exit;
}

$database = new Database();
$conn = $database->getConnection();
$user_id = $_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);
    
    $consultation_id = $data['consultation_id'] ?? 0;
    $booking_date = $data['booking_date'] ?? '';
    $booking_time = $data['booking_time'] ?? '';
    $notes = $data['notes'] ?? '';
    
    if (empty($consultation_id) || empty($booking_date) || empty($booking_time)) {
        echo json_encode(['success' => false, 'message' => 'البيانات غير مكتملة']);
        exit;
    }
    
    try {
        // Get user info
        $user_stmt = $conn->prepare("SELECT name, phone FROM users WHERE id = ?");
        $user_stmt->execute([$user_id]);
        $user = $user_stmt->fetch(PDO::FETCH_ASSOC);
        
        // Get consultation info
        $consult_stmt = $conn->prepare("SELECT price, discount_price FROM consultations WHERE id = ?");
        $consult_stmt->execute([$consultation_id]);
        $consultation = $consult_stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$consultation) {
            echo json_encode(['success' => false, 'message' => 'الاستشارة غير موجودة']);
            exit;
        }
        
        $total_price = $consultation['discount_price'] ?: $consultation['price'];
        
        // Insert booking
        $stmt = $conn->prepare("
            INSERT INTO consultation_bookings 
            (consultation_id, user_id, name, phone, booking_date, booking_time, notes, total_price, status, payment_status, created_at) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', 'pending', NOW())
        ");
        
        $stmt->execute([
            $consultation_id,
            $user_id,
            $user['name'],
            $user['phone'],
            $booking_date,
            $booking_time,
            $notes,
            $total_price
        ]);
        
        $booking_id = $conn->lastInsertId();
        
        echo json_encode([
            'success' => true, 
            'message' => 'تم تأكيد الحجز بنجاح!',
            'booking_id' => $booking_id
        ]);
        
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => 'حدث خطأ: ' . $e->getMessage()]);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'طريقة غير مسموحة']);
}
