<?php
session_start();
require_once '../../config/database.php';

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header('Location: ../login.php');
    exit;
}

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

// Get all consultation bookings
try {
    $stmt = $conn->query("
        SELECT cb.*, c.title as consultation_title, c.price, c.discount_price, u.name as user_name, u.phone as user_phone
        FROM consultation_bookings cb
        LEFT JOIN consultations c ON cb.consultation_id = c.id
        LEFT JOIN users u ON cb.user_id = u.id
        ORDER BY cb.created_at DESC
    ");
    $bookings = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $bookings = [];
}

// Statistics
$total_bookings = count($bookings);
$pending_bookings = count(array_filter($bookings, fn($b) => $b['status'] === 'pending'));
$confirmed_bookings = count(array_filter($bookings, fn($b) => $b['status'] === 'confirmed'));
$completed_bookings = count(array_filter($bookings, fn($b) => $b['status'] === 'completed'));
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>حجوزات الاستشارات - Roz Skin</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<link rel="stylesheet" href="../assets/css/admin-layout.css">
<link rel="stylesheet" href="../assets/css/admin-improvements.css">
<style>
body { font-family: 'Tajawal', sans-serif; }
</style>
</head>
<body class="bg-gray-50 min-h-screen">

<?php include '../includes/sidebar.php'; ?>

<div style="margin-right: 280px; padding: 24px;">
    
    <header class="bg-white shadow-sm border-b border-gray-200 rounded-lg mb-6 p-6">
        <div class="flex items-center justify-between">
            <div>
                <h1 class="text-3xl font-bold text-gray-900">📅 حجوزات الاستشارات</h1>
                <p class="text-sm text-gray-500 mt-1">إدارة ومتابعة حجوزات الاستشارات والمكالمات</p>
            </div>
            <a href="index.php" class="bg-gray-200 text-gray-700 px-6 py-3 rounded-lg hover:bg-gray-300 transition">
                <i class="fas fa-arrow-right mr-2"></i>
                رجوع للاستشارات
            </a>
        </div>
    </header>

    <!-- Statistics -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
        <div class="bg-white rounded-lg shadow p-6">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-500 text-sm">إجمالي الحجوزات</p>
                    <p class="text-3xl font-bold text-gray-900 mt-2"><?php echo $total_bookings; ?></p>
                </div>
                <div class="bg-blue-100 p-4 rounded-full">
                    <i class="fas fa-calendar-check text-blue-600 text-2xl"></i>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-lg shadow p-6">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-500 text-sm">قيد الانتظار</p>
                    <p class="text-3xl font-bold text-yellow-600 mt-2"><?php echo $pending_bookings; ?></p>
                </div>
                <div class="bg-yellow-100 p-4 rounded-full">
                    <i class="fas fa-clock text-yellow-600 text-2xl"></i>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-lg shadow p-6">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-500 text-sm">مؤكدة</p>
                    <p class="text-3xl font-bold text-green-600 mt-2"><?php echo $confirmed_bookings; ?></p>
                </div>
                <div class="bg-green-100 p-4 rounded-full">
                    <i class="fas fa-check-circle text-green-600 text-2xl"></i>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-lg shadow p-6">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-500 text-sm">مكتملة</p>
                    <p class="text-3xl font-bold text-purple-600 mt-2"><?php echo $completed_bookings; ?></p>
                </div>
                <div class="bg-purple-100 p-4 rounded-full">
                    <i class="fas fa-check-double text-purple-600 text-2xl"></i>
                </div>
            </div>
        </div>
    </div>

    <!-- Bookings Table -->
    <?php if (empty($bookings)): ?>
        <div class="bg-white rounded-lg shadow p-12 text-center">
            <div class="text-6xl mb-4">📅</div>
            <h3 class="text-xl font-bold text-gray-700 mb-2">لا توجد حجوزات حالياً</h3>
            <p class="text-gray-500">سيتم عرض الحجوزات هنا عندما يقوم العملاء بالحجز</p>
        </div>
    <?php else: ?>
        <div class="bg-white rounded-lg shadow overflow-hidden">
            <table class="w-full">
                <thead class="bg-gray-50 border-b">
                    <tr>
                        <th class="px-6 py-4 text-right text-sm font-bold text-gray-700">رقم الحجز</th>
                        <th class="px-6 py-4 text-right text-sm font-bold text-gray-700">الاستشارة</th>
                        <th class="px-6 py-4 text-right text-sm font-bold text-gray-700">العميل</th>
                        <th class="px-6 py-4 text-right text-sm font-bold text-gray-700">التاريخ والوقت</th>
                        <th class="px-6 py-4 text-right text-sm font-bold text-gray-700">السعر</th>
                        <th class="px-6 py-4 text-right text-sm font-bold text-gray-700">الحالة</th>
                        <th class="px-6 py-4 text-right text-sm font-bold text-gray-700">إجراءات</th>
                    </tr>
                </thead>
                <tbody class="divide-y">
                    <?php foreach ($bookings as $booking): 
                        $status_colors = [
                            'pending' => 'bg-yellow-100 text-yellow-800',
                            'confirmed' => 'bg-green-100 text-green-800',
                            'completed' => 'bg-purple-100 text-purple-800',
                            'cancelled' => 'bg-red-100 text-red-800'
                        ];
                        $status_names = [
                            'pending' => 'قيد الانتظار',
                            'confirmed' => 'مؤكد',
                            'completed' => 'مكتمل',
                            'cancelled' => 'ملغي'
                        ];
                    ?>
                    <tr class="hover:bg-gray-50">
                        <td class="px-6 py-4 text-sm font-bold text-gray-900">#<?php echo $booking['id']; ?></td>
                        <td class="px-6 py-4 text-sm text-gray-900"><?php echo htmlspecialchars($booking['consultation_title']); ?></td>
                        <td class="px-6 py-4">
                            <div class="text-sm font-bold text-gray-900"><?php echo htmlspecialchars($booking['name']); ?></div>
                            <div class="text-xs text-gray-500"><?php echo htmlspecialchars($booking['phone']); ?></div>
                        </td>
                        <td class="px-6 py-4">
                            <div class="text-sm text-gray-900"><?php echo date('Y-m-d', strtotime($booking['booking_date'])); ?></div>
                            <div class="text-xs text-gray-500"><?php echo date('h:i A', strtotime($booking['booking_time'])); ?></div>
                        </td>
                        <td class="px-6 py-4 text-sm font-bold text-gray-900"><?php echo number_format($booking['total_price'], 0); ?> ج.م</td>
                        <td class="px-6 py-4">
                            <span class="px-3 py-1 rounded-full text-xs font-bold <?php echo $status_colors[$booking['status']]; ?>">
                                <?php echo $status_names[$booking['status']]; ?>
                            </span>
                        </td>
                        <td class="px-6 py-4">
                            <button onclick="viewBooking(<?php echo $booking['id']; ?>)" class="text-blue-600 hover:text-blue-800 mr-3" title="عرض التفاصيل">
                                <i class="fas fa-eye"></i>
                            </button>
                            <?php if ($booking['status'] === 'pending'): ?>
                            <button onclick="confirmBooking(<?php echo $booking['id']; ?>)" class="text-green-600 hover:text-green-800 mr-3" title="تأكيد">
                                <i class="fas fa-check"></i>
                            </button>
                            <?php endif; ?>
                            <?php if ($booking['status'] !== 'cancelled' && $booking['status'] !== 'completed'): ?>
                            <button onclick="cancelBooking(<?php echo $booking['id']; ?>)" class="text-red-600 hover:text-red-800" title="إلغاء">
                                <i class="fas fa-times"></i>
                            </button>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>

<!-- Booking Details Modal -->
<div id="bookingDetailsModal" style="display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.6); backdrop-filter: blur(8px); z-index: 99999; align-items: center; justify-content: center;">
    <div style="background: white; border-radius: 20px; max-width: 600px; width: 90%; max-height: 90vh; overflow-y: auto; box-shadow: 0 20px 60px rgba(0,0,0,0.3); position: relative; padding: 32px;">
        <button onclick="closeBookingDetails()" style="position: absolute; top: 16px; left: 16px; background: rgba(0,0,0,0.05); border: none; width: 36px; height: 36px; border-radius: 50%; cursor: pointer; font-size: 24px; color: #666;">×</button>
        
        <div id="bookingDetailsContent">
            <!-- Content will be loaded here -->
        </div>
    </div>
</div>

<script>
function viewBooking(id) {
    fetch('get-booking-details.php?id=' + id)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const booking = data.booking;
                const statusColors = {
                    'pending': 'bg-yellow-100 text-yellow-800',
                    'confirmed': 'bg-green-100 text-green-800',
                    'completed': 'bg-purple-100 text-purple-800',
                    'cancelled': 'bg-red-100 text-red-800'
                };
                const statusNames = {
                    'pending': 'قيد الانتظار',
                    'confirmed': 'مؤكد',
                    'completed': 'مكتمل',
                    'cancelled': 'ملغي'
                };
                
                document.getElementById('bookingDetailsContent').innerHTML = `
                    <div class="text-center mb-6">
                        <div class="inline-block bg-gradient-to-r from-blue-500 to-blue-600 text-white px-4 py-2 rounded-full text-sm font-bold mb-4">
                            حجز #${booking.id}
                        </div>
                        <h2 class="text-2xl font-bold text-gray-900">${booking.consultation_title}</h2>
                    </div>
                    
                    <div class="space-y-4">
                        <div class="bg-gray-50 p-4 rounded-lg">
                            <div class="text-sm text-gray-500 mb-1">العميل</div>
                            <div class="text-lg font-bold text-gray-900">${booking.name}</div>
                            <div class="text-sm text-gray-600">${booking.phone}</div>
                            ${booking.email ? `<div class="text-sm text-gray-600">${booking.email}</div>` : ''}
                        </div>
                        
                        <div class="grid grid-cols-2 gap-4">
                            <div class="bg-gray-50 p-4 rounded-lg">
                                <div class="text-sm text-gray-500 mb-1">التاريخ</div>
                                <div class="text-lg font-bold text-gray-900">${booking.booking_date}</div>
                            </div>
                            <div class="bg-gray-50 p-4 rounded-lg">
                                <div class="text-sm text-gray-500 mb-1">الوقت</div>
                                <div class="text-lg font-bold text-gray-900">${booking.booking_time}</div>
                            </div>
                        </div>
                        
                        <div class="bg-gray-50 p-4 rounded-lg">
                            <div class="text-sm text-gray-500 mb-1">السعر</div>
                            <div class="text-2xl font-bold text-green-600">${parseFloat(booking.total_price).toLocaleString()} ج.م</div>
                        </div>
                        
                        ${booking.notes ? `
                        <div class="bg-gray-50 p-4 rounded-lg">
                            <div class="text-sm text-gray-500 mb-1">ملاحظات</div>
                            <div class="text-gray-900">${booking.notes}</div>
                        </div>
                        ` : ''}
                        
                        <div class="bg-gray-50 p-4 rounded-lg">
                            <div class="text-sm text-gray-500 mb-2">الحالة</div>
                            <span class="px-4 py-2 rounded-full text-sm font-bold ${statusColors[booking.status]}">
                                ${statusNames[booking.status]}
                            </span>
                        </div>
                        
                        <div class="bg-gray-50 p-4 rounded-lg">
                            <div class="text-sm text-gray-500 mb-1">تاريخ الحجز</div>
                            <div class="text-sm text-gray-900">${booking.created_at}</div>
                        </div>
                    </div>
                `;
                
                document.getElementById('bookingDetailsModal').style.display = 'flex';
            } else {
                alert('❌ ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('❌ حدث خطأ');
        });
}

function closeBookingDetails() {
    document.getElementById('bookingDetailsModal').style.display = 'none';
}

// Close on background click
document.getElementById('bookingDetailsModal').addEventListener('click', function(e) {
    if (e.target === this) closeBookingDetails();
});

function confirmBooking(id) {
    if (!confirm('هل تريد تأكيد هذا الحجز؟')) return;
    
    fetch('update-booking-status.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id: id, status: 'confirmed' })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('✅ تم تأكيد الحجز بنجاح');
            location.reload();
        } else {
            alert('❌ ' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('❌ حدث خطأ');
    });
}

function cancelBooking(id) {
    if (!confirm('هل تريد إلغاء هذا الحجز؟')) return;
    
    fetch('update-booking-status.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id: id, status: 'cancelled' })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('✅ تم إلغاء الحجز');
            location.reload();
        } else {
            alert('❌ ' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('❌ حدث خطأ');
    });
}
</script>

</body>
</html>
