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

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

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

try {
    $database = new Database();
    $conn = $database->getConnection();
    
    $user_id = $_SESSION['user_id'];
    $service_id = $_POST['service_id'] ?? 0;
    $booking_date = $_POST['booking_date'] ?? '';
    $booking_time = $_POST['booking_time'] ?? '';
    $branch_id = $_POST['branch_id'] ?? null;
    $notes = $_POST['notes'] ?? '';
    
    // Validate required fields
    if (empty($service_id) || empty($booking_date) || empty($booking_time)) {
        echo json_encode(['success' => false, 'message' => 'الرجاء ملء جميع الحقول المطلوبة']);
        exit;
    }
    
    // Get user info
    $stmt = $conn->prepare("SELECT name, phone FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    $customer_name = $user['name'] ?? '';
    $customer_phone = $user['phone'] ?? '';
    
    // Check if bookings table exists, if not create it
    try {
        $conn->query("SELECT 1 FROM bookings LIMIT 1");
    } catch (PDOException $e) {
        // Create bookings table with customer info fields
        $sql = "CREATE TABLE IF NOT EXISTS bookings (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_id INT NULL,
            service_id INT NOT NULL,
            branch_id INT NULL,
            customer_name VARCHAR(255) NOT NULL,
            customer_phone VARCHAR(50) NOT NULL,
            booking_date DATE NOT NULL,
            booking_time TIME NOT NULL,
            status VARCHAR(20) DEFAULT 'pending',
            notes TEXT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            FOREIGN KEY (service_id) REFERENCES beauty_services(id) ON DELETE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
        $conn->exec($sql);
    }
    
    // Check if customer_name and customer_phone columns exist
    try {
        $conn->query("SELECT customer_name, customer_phone FROM bookings LIMIT 1");
    } catch (PDOException $e) {
        // Add columns if they don't exist
        $conn->exec("ALTER TABLE bookings ADD COLUMN customer_name VARCHAR(255) NULL AFTER user_id");
        $conn->exec("ALTER TABLE bookings ADD COLUMN customer_phone VARCHAR(50) NULL AFTER customer_name");
        $conn->exec("ALTER TABLE bookings MODIFY COLUMN user_id INT NULL");
    }
    
    // Get service info from beauty_services table
    $stmt = $conn->prepare("SELECT name, price FROM beauty_services WHERE id = ?");
    $stmt->execute([$service_id]);
    $service = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$service) {
        echo json_encode(['success' => false, 'message' => 'الخدمة غير موجودة']);
        exit;
    }
    
    // Insert booking
    $stmt = $conn->prepare("
        INSERT INTO bookings (user_id, service_id, branch_id, customer_name, customer_phone, booking_date, booking_time, notes, status)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending')
    ");
    
    $stmt->execute([
        $user_id,
        $service_id,
        $branch_id,
        $customer_name,
        $customer_phone,
        $booking_date,
        $booking_time,
        $notes
    ]);
    
    $booking_id = $conn->lastInsertId();
    
    // Generate booking code
    $booking_code = 'BK-' . date('Ymd') . '-' . str_pad($booking_id, 4, '0', STR_PAD_LEFT);
    
    // Update booking with code
    $stmt = $conn->prepare("UPDATE bookings SET notes = CONCAT(?, '\n', COALESCE(notes, '')) WHERE id = ?");
    $stmt->execute(["رقم الحجز: $booking_code", $booking_id]);
    
    echo json_encode([
        'success' => true,
        'message' => 'تم الحجز بنجاح! رقم الحجز: ' . $booking_code,
        'booking_id' => $booking_id,
        'booking_code' => $booking_code
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'حدث خطأ: ' . $e->getMessage()
    ]);
}
?>
