<?php
session_start();

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

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

try {
    $database = new Database();
    $db = $database->getConnection();
    
    // Get filter parameters
    $filter_status = $_GET['status'] ?? '';
    $filter_date = $_GET['date'] ?? '';
    $search = $_GET['search'] ?? '';
    
    $query = "SELECT bb.*, bs.name as service_name, bs.price as service_price, u.name as customer_name 
              FROM beauty_bookings bb
              LEFT JOIN beauty_services bs ON bb.service_id = bs.id
              LEFT JOIN users u ON bb.user_id = u.id
              WHERE 1=1";
    
    $params = [];
    
    if ($filter_status) {
        $query .= " AND bb.status = ?";
        $params[] = $filter_status;
    }
    
    if ($filter_date) {
        $query .= " AND bb.appointment_date = ?";
        $params[] = $filter_date;
    }
    
    if ($search) {
        $query .= " AND (bb.name LIKE ? OR bb.phone LIKE ? OR bb.email LIKE ?)";
        $search_param = "%$search%";
        $params[] = $search_param;
        $params[] = $search_param;
        $params[] = $search_param;
    }
    
    $query .= " ORDER BY bb.appointment_date DESC, bb.appointment_time DESC";
    
    $stmt = $db->prepare($query);
    $stmt->execute($params);
    $all_bookings = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Statistics
    $total_bookings = count($all_bookings);
    $pending_bookings = count(array_filter($all_bookings, fn($b) => $b['status'] === 'pending'));
    $confirmed_bookings = count(array_filter($all_bookings, fn($b) => $b['status'] === 'confirmed'));
    $completed_bookings = count(array_filter($all_bookings, fn($b) => $b['status'] === 'completed'));
    
} catch (Exception $e) {
    $error = "خطأ: " . $e->getMessage();
    $all_bookings = [];
}

$status_ar = [
    'pending' => 'في الانتظار',
    'confirmed' => 'مؤكد',
    'completed' => 'مكتمل',
    'cancelled' => 'ملغي'
];

$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
    try {
        $booking_id = $_POST['booking_id'];
        $status = $_POST['status'];
        
        $query = "UPDATE beauty_bookings SET status = ? WHERE id = ?";
        $stmt = $db->prepare($query);
        $stmt->execute([$status, $booking_id]);
        
        header("Location: index.php?updated=1");
        exit;
    } catch (Exception $e) {
        $message = "خطأ في التحديث: " . $e->getMessage();
    }
}

if (isset($_GET['updated'])) {
    $message = 'تم تحديث حالة الحجز بنجاح!';
}
?>
<!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">
    <style>
        body { font-family: 'Tajawal', sans-serif; }
    </style>
</head>
<body class="bg-gray-50">
    <div class="min-h-screen">
        <header class="bg-white shadow-sm border-b border-gray-200 sticky top-0 z-20">
            <div class="flex items-center justify-between px-6 py-4">
                <div class="flex items-center space-x-4 space-x-reverse">
                    <a href="../dashboard.php" class="text-gray-600 hover:text-gray-900">
                        <i class="fas fa-arrow-right text-xl"></i>
                    </a>
                    <div>
                        <h1 class="text-2xl font-bold text-gray-900">إدارة حجوزات البيوتي</h1>
                        <p class="text-sm text-gray-500">عرض وإدارة جميع الحجوزات</p>
                    </div>
                </div>
                <div class="flex items-center space-x-3 space-x-reverse">
                    <button onclick="window.print()" class="bg-gray-100 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-200">
                        <i class="fas fa-print ml-2"></i>طباعة
                    </button>
                </div>
            </div>
        </header>

        <div class="p-6">
            <?php if (isset($error)): ?>
                <div class="bg-red-50 border-r-4 border-red-400 p-4 mb-6">
                    <p class="text-sm text-red-700"><?php echo $error; ?></p>
                </div>
            <?php endif; ?>

            <?php if ($message): ?>
                <div class="bg-green-50 border-r-4 border-green-400 p-4 mb-6">
                    <p class="text-sm text-green-700"><?php echo $message; ?></p>
                </div>
            <?php endif; ?>

            <!-- Statistics Cards -->
            <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-600">إجمالي الحجوزات</p>
                            <p class="text-3xl font-bold text-gray-900"><?php echo $total_bookings; ?></p>
                        </div>
                        <div class="bg-violet-50 p-3 rounded-lg">
                            <i class="fas fa-calendar-alt text-violet-600 text-2xl"></i>
                        </div>
                    </div>
                </div>

                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-600">في الانتظار</p>
                            <p class="text-3xl font-bold text-yellow-600"><?php echo $pending_bookings; ?></p>
                        </div>
                        <div class="bg-yellow-50 p-3 rounded-lg">
                            <i class="fas fa-clock text-yellow-600 text-2xl"></i>
                        </div>
                    </div>
                </div>

                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-600">مؤكدة</p>
                            <p class="text-3xl font-bold text-blue-600"><?php echo $confirmed_bookings; ?></p>
                        </div>
                        <div class="bg-blue-50 p-3 rounded-lg">
                            <i class="fas fa-check-circle text-blue-600 text-2xl"></i>
                        </div>
                    </div>
                </div>

                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-600">مكتملة</p>
                            <p class="text-3xl font-bold text-green-600"><?php echo $completed_bookings; ?></p>
                        </div>
                        <div class="bg-green-50 p-3 rounded-lg">
                            <i class="fas fa-check-double text-green-600 text-2xl"></i>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Search and Filter -->
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4 mb-6">
                <form method="GET" class="flex flex-wrap items-center gap-4">
                    <div class="flex-1 min-w-[200px]">
                        <input type="text" name="search" value="<?php echo htmlspecialchars($search); ?>" 
                               placeholder="بحث بالاسم أو الهاتف أو البريد..."
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-violet-500">
                    </div>
                    <div>
                        <select name="status" class="px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-violet-500">
                            <option value="">جميع الحالات</option>
                            <?php foreach ($status_ar as $key => $value): ?>
                                <option value="<?php echo $key; ?>" <?php echo $filter_status === $key ? 'selected' : ''; ?>><?php echo $value; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <input type="date" name="date" value="<?php echo htmlspecialchars($filter_date); ?>"
                               class="px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-violet-500">
                    </div>
                    <button type="submit" class="bg-violet-600 text-white px-6 py-2 rounded-lg hover:bg-violet-700">
                        <i class="fas fa-search ml-2"></i>بحث
                    </button>
                    <?php if ($search || $filter_status || $filter_date): ?>
                        <a href="index.php" class="bg-gray-100 text-gray-700 px-6 py-2 rounded-lg hover:bg-gray-200">
                            <i class="fas fa-times ml-2"></i>إلغاء
                        </a>
                    <?php endif; ?>
                </form>
            </div>

            <div class="bg-white rounded-lg shadow-sm border border-gray-200">
                <div class="px-6 py-5 border-b border-gray-200">
                    <h3 class="text-xl font-semibold text-gray-900">
                        جميع الحجوزات (<?php echo count($all_bookings); ?>)
                    </h3>
                </div>
                
                <div class="overflow-x-auto">
                    <?php if (!empty($all_bookings)): ?>
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">#</th>
                                    <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">العميل</th>
                                    <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">الهاتف</th>
                                    <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">البريد</th>
                                    <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">الخدمة</th>
                                    <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">التاريخ</th>
                                    <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">الوقت</th>
                                    <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">الحالة</th>
                                    <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">الإجراءات</th>
                                </tr>
                            </thead>
                            <tbody class="bg-white divide-y divide-gray-200">
                                <?php foreach ($all_bookings as $booking): ?>
                                    <tr class="hover:bg-gray-50 cursor-pointer" onclick="viewBookingDetails(<?php echo htmlspecialchars(json_encode($booking)); ?>)">
                                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                                            #<?php echo $booking['id']; ?>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                            <div class="font-medium"><?php echo htmlspecialchars($booking['name']); ?></div>
                                            <?php if ($booking['customer_name']): ?>
                                                <div class="text-xs text-gray-500">(<?php echo htmlspecialchars($booking['customer_name']); ?>)</div>
                                            <?php endif; ?>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                            <?php if (!empty($booking['phone'])): ?>
                                                <a href="tel:<?php echo htmlspecialchars($booking['phone']); ?>" 
                                                   class="text-blue-600 hover:text-blue-800 flex items-center"
                                                   onclick="event.stopPropagation()">
                                                    <i class="fas fa-phone ml-1"></i>
                                                    <?php echo htmlspecialchars($booking['phone']); ?>
                                                </a>
                                            <?php else: ?>
                                                <span class="text-gray-400">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                            <?php if (!empty($booking['email'])): ?>
                                                <a href="mailto:<?php echo htmlspecialchars($booking['email']); ?>" 
                                                   class="text-blue-600 hover:text-blue-800 flex items-center"
                                                   onclick="event.stopPropagation()">
                                                    <i class="fas fa-envelope ml-1"></i>
                                                    <?php echo htmlspecialchars($booking['email']); ?>
                                                </a>
                                            <?php else: ?>
                                                <span class="text-gray-400">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                            <div class="font-medium"><?php echo htmlspecialchars($booking['service_name'] ?? 'غير محدد'); ?></div>
                                            <?php if (!empty($booking['service_price'])): ?>
                                                <div class="text-xs text-green-600"><?php echo number_format($booking['service_price'], 0); ?> ج.م</div>
                                            <?php endif; ?>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                            <?php echo isset($booking['appointment_date']) ? date('Y-m-d', strtotime($booking['appointment_date'])) : 'غير محدد'; ?>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                                            <i class="fas fa-clock text-gray-400 ml-1"></i>
                                            <?php echo $booking['appointment_time'] ?? 'غير محدد'; ?>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap">
                                            <?php
                                                $status_classes = [
                                                    'pending' => 'bg-yellow-100 text-yellow-800',
                                                    'confirmed' => 'bg-blue-100 text-blue-800',
                                                    'completed' => 'bg-green-100 text-green-800',
                                                    'cancelled' => 'bg-red-100 text-red-800'
                                                ];
                                                $status_class = $status_classes[$booking['status']] ?? 'bg-gray-100 text-gray-800';
                                            ?>
                                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium <?php echo $status_class; ?>">
                                                <?php echo $status_ar[$booking['status']] ?? $booking['status']; ?>
                                            </span>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm" onclick="event.stopPropagation()">
                                            <form method="POST" class="inline-block">
                                                <input type="hidden" name="booking_id" value="<?php echo $booking['id']; ?>">
                                                <select name="status" class="text-sm border-gray-300 rounded-md" onchange="this.form.submit()">
                                                    <?php foreach ($status_ar as $key => $value): ?>
                                                        <option value="<?php echo $key; ?>" <?php echo $booking['status'] === $key ? 'selected' : ''; ?>>
                                                            <?php echo $value; ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                                <input type="hidden" name="update_status" value="1">
                                            </form>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php else: ?>
                        <div class="p-12 text-center">
                            <div class="w-24 h-24 bg-violet-100 rounded-full flex items-center justify-center mx-auto mb-4">
                                <i class="fas fa-calendar-alt text-4xl text-violet-400"></i>
                            </div>
                            <h3 class="text-xl font-semibold text-gray-700 mb-2">لا توجد حجوزات</h3>
                            <p class="text-gray-500">لم يتم إجراء أي حجوزات بعد</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Booking Details Modal -->
    <div id="detailsModal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
        <div class="bg-white rounded-lg max-w-2xl w-full max-h-[90vh] overflow-y-auto">
            <div class="sticky top-0 bg-white border-b px-6 py-4 flex items-center justify-between">
                <h2 class="text-2xl font-bold text-gray-900">تفاصيل الحجز</h2>
                <button onclick="closeModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times text-2xl"></i>
                </button>
            </div>
            
            <div class="p-6">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <!-- Customer Info -->
                    <div class="bg-gray-50 rounded-lg p-4">
                        <h3 class="font-semibold text-gray-900 mb-3 flex items-center">
                            <i class="fas fa-user text-blue-600 ml-2"></i>معلومات العميل
                        </h3>
                        <div class="space-y-2 text-sm">
                            <div class="flex justify-between">
                                <span class="text-gray-600">الاسم:</span>
                                <span class="font-medium text-gray-900" id="modal-name"></span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-gray-600">الهاتف:</span>
                                <span class="font-medium text-gray-900" id="modal-phone"></span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-gray-600">البريد:</span>
                                <span class="font-medium text-gray-900" id="modal-email"></span>
                            </div>
                        </div>
                    </div>

                    <!-- Booking Info -->
                    <div class="bg-gray-50 rounded-lg p-4">
                        <h3 class="font-semibold text-gray-900 mb-3 flex items-center">
                            <i class="fas fa-calendar-alt text-violet-600 ml-2"></i>معلومات الحجز
                        </h3>
                        <div class="space-y-2 text-sm">
                            <div class="flex justify-between">
                                <span class="text-gray-600">رقم الحجز:</span>
                                <span class="font-medium text-gray-900" id="modal-id"></span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-gray-600">التاريخ:</span>
                                <span class="font-medium text-gray-900" id="modal-date"></span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-gray-600">الوقت:</span>
                                <span class="font-medium text-gray-900" id="modal-time"></span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-gray-600">الحالة:</span>
                                <span class="font-medium" id="modal-status"></span>
                            </div>
                        </div>
                    </div>

                    <!-- Service Info -->
                    <div class="bg-gray-50 rounded-lg p-4 md:col-span-2">
                        <h3 class="font-semibold text-gray-900 mb-3 flex items-center">
                            <i class="fas fa-spa text-pink-600 ml-2"></i>الخدمة
                        </h3>
                        <div class="space-y-2 text-sm">
                            <div class="flex justify-between">
                                <span class="text-gray-600">اسم الخدمة:</span>
                                <span class="font-medium text-gray-900" id="modal-service"></span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-gray-600">السعر:</span>
                                <span class="font-medium text-green-600" id="modal-price"></span>
                            </div>
                        </div>
                    </div>

                    <!-- Notes -->
                    <div class="bg-yellow-50 rounded-lg p-4 md:col-span-2" id="notes-section">
                        <h3 class="font-semibold text-gray-900 mb-3 flex items-center">
                            <i class="fas fa-sticky-note text-yellow-600 ml-2"></i>ملاحظات العميل
                        </h3>
                        <p class="text-sm text-gray-700" id="modal-notes"></p>
                    </div>

                    <!-- Timestamps -->
                    <div class="text-xs text-gray-500 md:col-span-2 pt-4 border-t">
                        <div class="flex justify-between">
                            <span>تاريخ الإنشاء: <span id="modal-created"></span></span>
                            <span>آخر تحديث: <span id="modal-updated"></span></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        function viewBookingDetails(booking) {
            document.getElementById('modal-id').textContent = '#' + booking.id;
            document.getElementById('modal-name').textContent = booking.name || 'غير محدد';
            document.getElementById('modal-phone').textContent = booking.phone || 'غير محدد';
            document.getElementById('modal-email').textContent = booking.email || 'غير محدد';
            document.getElementById('modal-date').textContent = booking.appointment_date || 'غير محدد';
            document.getElementById('modal-time').textContent = booking.appointment_time || 'غير محدد';
            document.getElementById('modal-service').textContent = booking.service_name || 'غير محدد';
            document.getElementById('modal-price').textContent = booking.service_price ? (parseFloat(booking.service_price).toLocaleString() + ' ج.م') : 'غير محدد';
            document.getElementById('modal-created').textContent = booking.created_at || 'غير محدد';
            document.getElementById('modal-updated').textContent = booking.updated_at || 'غير محدد';
            
            // Status with color
            const statusAr = {
                'pending': 'في الانتظار',
                'confirmed': 'مؤكد',
                'completed': 'مكتمل',
                'cancelled': 'ملغي'
            };
            const statusColors = {
                'pending': 'text-yellow-600',
                'confirmed': 'text-blue-600',
                'completed': 'text-green-600',
                'cancelled': 'text-red-600'
            };
            const statusEl = document.getElementById('modal-status');
            statusEl.textContent = statusAr[booking.status] || booking.status;
            statusEl.className = 'font-medium ' + (statusColors[booking.status] || 'text-gray-600');
            
            // Notes
            const notesSection = document.getElementById('notes-section');
            const notesEl = document.getElementById('modal-notes');
            if (booking.notes && booking.notes.trim()) {
                notesEl.textContent = booking.notes;
                notesSection.classList.remove('hidden');
            } else {
                notesSection.classList.add('hidden');
            }
            
            document.getElementById('detailsModal').classList.remove('hidden');
        }

        function closeModal() {
            document.getElementById('detailsModal').classList.add('hidden');
        }

        // Close modal on outside click
        document.getElementById('detailsModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeModal();
            }
        });
    </script>
</body>
</html>
