<?php
include 'config.php';
checkCaptainAuth();

// Get captain's current orders
$captain_id = $_SESSION['captain_id'];
$current_orders = $conn->query("
    SELECT o.*, c.name as customer_name, c.phone as customer_phone, c.address as customer_address
    FROM orders o 
    JOIN customers c ON o.customer_id = c.id 
    WHERE o.captain_id = '$captain_id' AND o.status != 'delivered'
    ORDER BY o.created_at DESC
");

// Get completed orders count
$completed_orders = $conn->query("
    SELECT COUNT(*) as total FROM orders 
    WHERE captain_id = '$captain_id' AND status = 'delivered'
")->fetch_assoc()['total'];

// Get today's earnings
$today_earnings = $conn->query("
    SELECT COALESCE(SUM(total), 0) as total FROM orders 
    WHERE captain_id = '$captain_id' AND status = 'delivered' AND DATE(created_at) = CURDATE()
")->fetch_assoc()['total'];
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>لوحة التحكم - Max Captain</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.rtl.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        body {
            font-family: 'Tajawal', sans-serif;
            background-color: #f8f9fa;
        }
        .navbar {
            background: #F57C00;
            color: white;
        }
        .stat-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            border-right: 4px solid #F57C00;
            margin-bottom: 20px;
        }
        .order-card {
            background: white;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 15px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            border-right: 4px solid #F57C00;
        }
        .bottom-nav {
            position: fixed;
            bottom: 0;
            right: 0;
            left: 0;
            background: white;
            box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
            padding: 10px;
        }
        .nav-item {
            text-align: center;
        }
        .nav-link {
            color: #666;
        }
        .nav-link.active {
            color: #F57C00;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg">
        <div class="container-fluid">
            <span class="navbar-brand text-white">
                <i class="bi bi-person-badge"></i> مرحباً، <?php echo $_SESSION['captain_name']; ?>
            </span>
        </div>
    </nav>

    <div class="container mt-4" style="padding-bottom: 80px;">
        <h2 class="mb-4">الطلبات الحالية</h2>
        
        <!-- Statistics -->
        <div class="row">
            <div class="col-md-4">
                <div class="stat-card">
                    <div class="text-center">
                        <h3 class="text-primary"><?php echo $current_orders->num_rows; ?></h3>
                        <p class="mb-0">طلبات حالية</p>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stat-card">
                    <div class="text-center">
                        <h3 class="text-success"><?php echo $completed_orders; ?></h3>
                        <p class="mb-0">طلبات منجزة</p>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stat-card">
                    <div class="text-center">
                        <h3 class="text-warning"><?php echo number_format($today_earnings, 2); ?> ريال</h3>
                        <p class="mb-0">أرباح اليوم</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Current Orders -->
        <?php if ($current_orders->num_rows > 0): ?>
            <?php while ($order = $current_orders->fetch_assoc()): ?>
                <div class="order-card">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <h5>طلب #<?php echo $order['id']; ?></h5>
                        <span class="badge bg-<?php 
                            $status_badge = [
                                'pending' => 'warning',
                                'accepted' => 'info',
                                'on_the_way' => 'primary',
                                'delivered' => 'success'
                            ];
                            echo $status_badge[$order['status']];
                        ?>">
                            <?php 
                            $status_text = [
                                'pending' => 'قيد الانتظار',
                                'accepted' => 'تم القبول',
                                'on_the_way' => 'في الطريق',
                                'delivered' => 'تم التوصيل'
                            ];
                            echo $status_text[$order['status']];
                            ?>
                        </span>
                    </div>
                    
                    <div class="mb-2">
                        <strong><i class="bi bi-person"></i> العميل:</strong> 
                        <?php echo $order['customer_name']; ?>
                    </div>
                    <div class="mb-2">
                        <strong><i class="bi bi-telephone"></i> الهاتف:</strong> 
                        <?php echo $order['customer_phone']; ?>
                    </div>
                    <div class="mb-2">
                        <strong><i class="bi bi-geo-alt"></i> العنوان:</strong> 
                        <?php echo $order['customer_address']; ?>
                    </div>
                    <div class="mb-3">
                        <strong><i class="bi bi-currency-dollar"></i> المجموع:</strong> 
                        <?php echo $order['total']; ?>ريال
                    </div>
                    
                    <div class="d-flex gap-2">
                        <?php if ($order['status'] == 'pending'): ?>
                            <form method="POST" action="update_order.php" class="d-inline">
                                <input type="hidden" name="order_id" value="<?php echo $order['id']; ?>">
                                <input type="hidden" name="status" value="accepted">
                                <button type="submit" class="btn btn-success btn-sm">قبول الطلب</button>
                            </form>
                        <?php elseif ($order['status'] == 'accepted'): ?>
                            <form method="POST" action="update_order.php" class="d-inline">
                                <input type="hidden" name="order_id" value="<?php echo $order['id']; ?>">
                                <input type="hidden" name="status" value="on_the_way">
                                <button type="submit" class="btn btn-primary btn-sm">بدأ التوصيل</button>
                            </form>
                        <?php elseif ($order['status'] == 'on_the_way'): ?>
                            <form method="POST" action="update_order.php" class="d-inline">
                                <input type="hidden" name="order_id" value="<?php echo $order['id']; ?>">
                                <input type="hidden" name="status" value="delivered">
                                <button type="submit" class="btn btn-success btn-sm">تم التوصيل</button>
                            </form>
                        <?php endif; ?>
                        
                        <a href="order_details.php?id=<?php echo $order['id']; ?>" class="btn btn-info btn-sm">تفاصيل</a>
                       <a href="https://maps.google.com/?q=<?php echo urlencode($order['customer_address']); ?>" 
                           target="_blank" class="btn btn-warning btn-sm">
                            <i class="bi bi-map"></i> خرائط
                        </a>

</a>
                    </div>
                </div>
            <?php endwhile; ?>
        <?php else: ?>
            <div class="alert alert-info text-center">
                <i class="bi bi-info-circle"></i> لا توجد طلبات حالية
            </div>
        <?php endif; ?>
    </div>

    <!-- Bottom Navigation -->
  

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<!-- Bottom Navigation -->
<nav class="bottom-nav">
    <div class="row text-center">
        <div class="col-3">
            <a href="dashboard.php" class="nav-link">
                <i class="bi bi-house-door fs-4"></i>
                <div>الرئيسية</div>
            </a>
        </div>
        <div class="col-3">
            <a href="orders.php" class="nav-link">
                <i class="bi bi-list-check fs-4"></i>
                <div>الطلبات</div>
            </a>
        </div>
        <div class="col-3">
            <a href="completed_orders.php" class="nav-link">
                <i class="bi bi-check-circle fs-4"></i>
                <div>المنجزة</div>
            </a>
        </div>
        <div class="col-3">
            <a href="profile.php" class="nav-link">
                <i class="bi bi-person fs-4"></i>
                <div>الحساب</div>
            </a><?php
/**
 * Captain Dashboard - تعرض الطلبات الخاصة بالكابتن فقط مع تحديث تلقائي
 */

require_once 'config.php';
checkCaptainAuth();

$captain_id = $_SESSION['captain_id'];
$captain_name = $_SESSION['captain_name'];

// جلب الطلبات الحالية للكابتن (غير المكتملة)
$current_orders = $conn->query("
    SELECT o.*, c.name as customer_name, c.phone as customer_phone, c.address as customer_address
    FROM orders o 
    JOIN customers c ON o.customer_id = c.id 
    WHERE o.captain_id = '$captain_id' AND o.status != 'delivered'
    ORDER BY 
        CASE o.status
            WHEN 'accepted' THEN 1
            WHEN 'on_the_way' THEN 2
            ELSE 3
        END,
        o.created_at ASC
");

// جلب آخر 5 طلبات مكتملة
$completed_orders = $conn->query("
    SELECT o.*, c.name as customer_name
    FROM orders o 
    JOIN customers c ON o.customer_id = c.id 
    WHERE o.captain_id = '$captain_id' AND o.status = 'delivered'
    ORDER BY o.updated_at DESC
    LIMIT 5
");

// إحصائيات اليوم
$today_stats = $conn->query("
    SELECT 
        COUNT(*) as total_delivered,
        COALESCE(SUM(total), 0) as total_earnings
    FROM orders 
    WHERE captain_id = '$captain_id' 
        AND status = 'delivered' 
        AND DATE(updated_at) = CURDATE()
")->fetch_assoc();

// إحصائيات الشهر
$month_stats = $conn->query("
    SELECT 
        COUNT(*) as total_delivered,
        COALESCE(SUM(total), 0) as total_earnings
    FROM orders 
    WHERE captain_id = '$captain_id' 
        AND status = 'delivered' 
        AND MONTH(updated_at) = MONTH(CURDATE())
        AND YEAR(updated_at) = YEAR(CURDATE())
")->fetch_assoc();

// إجمالي جميع الطلبات المكتملة
$total_stats = $conn->query("
    SELECT 
        COUNT(*) as total_delivered,
        COALESCE(SUM(total), 0) as total_earnings
    FROM orders 
    WHERE captain_id = '$captain_id' AND status = 'delivered'
")->fetch_assoc();
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=yes">
    <title>لوحة تحكم الكابتن - Max</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.rtl.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Tajawal', sans-serif;
            background: #f8fafc;
            min-height: 100vh;
            padding-bottom: 80px;
        }

        /* الهيدر */
        .captain-header {
            background: linear-gradient(135deg, #F57C00 0%, #FF9800 100%);
            color: white;
            padding: 20px;
            box-shadow: 0 4px 15px rgba(245,124,0,0.3);
        }

        .captain-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .captain-avatar {
            width: 60px;
            height: 60px;
            background: rgba(255,255,255,0.2);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 2rem;
            border: 3px solid white;
        }

        .captain-name {
            font-size: 1.3rem;
            font-weight: 800;
            margin-bottom: 5px;
        }

        .captain-status {
            background: rgba(255,255,255,0.2);
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.8rem;
            display: inline-block;
        }

        /* بطاقات الإحصائيات */
        .stats-container {
            padding: 20px;
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 15px;
            margin-top: -20px;
        }

        .stat-card {
            background: white;
            border-radius: 16px;
            padding: 15px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.05);
            text-align: center;
            border-bottom: 4px solid #F57C00;
        }

        .stat-value {
            font-size: 1.8rem;
            font-weight: 800;
            color: #F57C00;
            line-height: 1.2;
        }

        .stat-label {
            color: #64748b;
            font-size: 0.8rem;
            font-weight: 500;
        }

        .stat-icon {
            font-size: 1.5rem;
            color: #F57C00;
            margin-bottom: 5px;
        }

        /* تبويبات */
        .tabs-container {
            padding: 0 20px;
            margin-bottom: 20px;
        }

        .custom-tabs {
            display: flex;
            gap: 10px;
            background: white;
            padding: 5px;
            border-radius: 50px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }

        .tab-btn {
            flex: 1;
            padding: 12px;
            border: none;
            background: transparent;
            border-radius: 50px;
            font-weight: 600;
            color: #64748b;
            transition: all 0.3s;
            cursor: pointer;
        }

        .tab-btn.active {
            background: #F57C00;
            color: white;
        }

        .tab-btn i {
            margin-left: 5px;
        }

        /* بطاقات الطلبات */
        .orders-container {
            padding: 0 20px;
        }

        .order-card {
            background: white;
            border-radius: 20px;
            padding: 20px;
            margin-bottom: 15px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.05);
            border-right: 5px solid;
            transition: all 0.3s ease;
            animation: slideIn 0.3s ease;
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .order-card.accepted {
            border-right-color: #3b82f6;
        }

        .order-card.on_the_way {
            border-right-color: #F57C00;
        }

        .order-card.delivered {
            border-right-color: #10b981;
            opacity: 0.9;
        }

        .order-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .order-id {
            font-weight: 800;
            font-size: 1.1rem;
            color: #1e293b;
        }

        .order-time {
            color: #64748b;
            font-size: 0.8rem;
        }

        .customer-info {
            margin-bottom: 15px;
        }

        .info-row {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 8px;
            color: #475569;
        }

        .info-row i {
            width: 20px;
            color: #F57C00;
        }

        .order-total {
            background: #f8fafc;
            padding: 10px 15px;
            border-radius: 12px;
            margin: 15px 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-weight: 700;
        }

        .total-price {
            color: #F57C00;
            font-size: 1.2rem;
        }

        .order-actions {
            display: flex;
            gap: 10px;
            margin-top: 15px;
        }

        .action-btn {
            flex: 1;
            padding: 12px;
            border: none;
            border-radius: 12px;
            font-weight: 700;
            font-size: 0.9rem;
            cursor: pointer;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 5px;
        }

        .action-btn.accept {
            background: #3b82f6;
            color: white;
        }

        .action-btn.accept:hover {
            background: #2563eb;
            transform: translateY(-2px);
        }

        .action-btn.start {
            background: #F57C00;
            color: white;
        }

        .action-btn.start:hover {
            background: #e65100;
            transform: translateY(-2px);
        }

        .action-btn.complete {
            background: #10b981;
            color: white;
        }

        .action-btn.complete:hover {
            background: #059669;
            transform: translateY(-2px);
        }

        .action-btn.map {
            background: #f1f5f9;
            color: #475569;
        }

        .action-btn.map:hover {
            background: #e2e8f0;
        }

        .action-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
            transform: none;
        }

        /* حالة عدم وجود طلبات */
        .empty-state {
            text-align: center;
            padding: 50px 20px;
        }

        .empty-state i {
            font-size: 5rem;
            color: #cbd5e1;
            margin-bottom: 20px;
        }

        .empty-state h5 {
            color: #64748b;
            margin-bottom: 10px;
        }

        .empty-state p {
            color: #94a3b8;
        }

        /* القائمة السفلية */
        .bottom-nav {
            position: fixed;
            bottom: 0;
            right: 0;
            left: 0;
            background: white;
            box-shadow: 0 -5px 20px rgba(0,0,0,0.05);
            padding: 10px;
            border-radius: 30px 30px 0 0;
            z-index: 1000;
        }

        .nav-items {
            display: flex;
            justify-content: space-around;
            align-items: center;
        }

        .nav-item {
            text-align: center;
            color: #94a3b8;
            transition: all 0.3s;
            cursor: pointer;
            padding: 5px 15px;
            border-radius: 30px;
        }

        .nav-item.active {
            background: #FFF3E0;
            color: #F57C00;
        }

        .nav-item i {
            font-size: 1.3rem;
            display: block;
            margin-bottom: 3px;
        }

        .nav-item span {
            font-size: 0.7rem;
            font-weight: 600;
        }

        /* الإشعارات */
        .notification {
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: white;
            padding: 15px 25px;
            border-radius: 50px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
            display: flex;
            align-items: center;
            gap: 10px;
            z-index: 9999;
            animation: slideDown 0.3s ease;
            border-right: 4px solid;
            font-weight: 600;
        }

        .notification.success {
            border-right-color: #10b981;
            color: #065f46;
        }

        .notification.error {
            border-right-color: #ef4444;
            color: #991b1b;
        }

        .notification.info {
            border-right-color: #3b82f6;
            color: #1e40af;
        }

        @keyframes slideDown {
            from {
                opacity: 0;
                transform: translate(-50%, -20px);
            }
            to {
                opacity: 1;
                transform: translate(-50%, 0);
            }
        }

        .notification.fade-out {
            opacity: 0;
            transform: translate(-50%, -20px);
            transition: all 0.3s;
        }

        /* تحميل */
        .loading-spinner {
            text-align: center;
            padding: 40px;
        }

        .spinner {
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #F57C00;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 15px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <!-- الهيدر -->
    <div class="captain-header">
        <div class="captain-info">
            <div class="captain-avatar">
                <i class="bi bi-person-badge"></i>
            </div>
            <div>
                <div class="captain-name"><?php echo htmlspecialchars($captain_name); ?></div>
                <span class="captain-status">
                    <i class="bi bi-circle-fill text-success me-1" style="font-size: 0.5rem;"></i>
                    متصل
                </span>
            </div>
        </div>
    </div>

    <!-- بطاقات الإحصائيات -->
    <div class="stats-container">
        <div class="stat-card">
            <div class="stat-icon"><i class="bi bi-calendar-check"></i></div>
            <div class="stat-value"><?php echo $today_stats['total_delivered']; ?></div>
            <div class="stat-label">توصيل اليوم</div>
        </div>
        <div class="stat-card">
            <div class="stat-icon"><i class="bi bi-cash-stack"></i></div>
            <div class="stat-value"><?php echo number_format($today_stats['total_earnings']); ?></div>
            <div class="stat-label">أرباح اليوم</div>
        </div>
        <div class="stat-card">
            <div class="stat-icon"><i class="bi bi-trophy"></i></div>
            <div class="stat-value"><?php echo $total_stats['total_delivered']; ?></div>
            <div class="stat-label">إجمالي التوصيل</div>
        </div>
    </div>

    <!-- تبويبات -->
    <div class="tabs-container">
        <div class="custom-tabs">
            <button class="tab-btn active" onclick="switchTab('current')">
                <i class="bi bi-clock-history"></i> الطلبات الحالية
            </button>
            <button class="tab-btn" onclick="switchTab('completed')">
                <i class="bi bi-check-circle"></i> المكتملة
            </button>
        </div>
    </div>

    <!-- حاوية الطلبات -->
    <div class="orders-container" id="ordersContainer">
        <!-- سيتم تعبئتها عبر JavaScript -->
    </div>

    <!-- القائمة السفلية -->
    <div class="bottom-nav">
        <div class="nav-items">
            <div class="nav-item active" onclick="window.location.href='dashboard.php'">
                <i class="bi bi-house-door"></i>
                <span>الرئيسية</span>
            </div>
            <div class="nav-item" onclick="window.location.href='orders_history.php'">
                <i class="bi bi-list-check"></i>
                <span>سجل الطلبات</span>
            </div>
            <div class="nav-item" onclick="window.location.href='earnings.php'">
                <i class="bi bi-cash"></i>
                <span>الأرباح</span>
            </div>
            <div class="nav-item" onclick="window.location.href='profile.php'">
                <i class="bi bi-person"></i>
                <span>حسابي</span>
            </div>
        </div>
    </div>

    <!-- صوت الإشعارات -->
    <audio id="notificationSound" preload="auto">
        <source src="assets/sounds/notification.mp3" type="audio/mpeg">
    </audio>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    // ============================================
    // نظام الكابتن - جميع الدوال
    // ============================================

    let currentTab = 'current';
    let lastUpdate = new Date().toISOString();

    /**
     * تحميل الطلبات حسب التبويب
     */
    function loadOrders() {
        const container = document.getElementById('ordersContainer');
        container.innerHTML = `
            <div class="loading-spinner">
                <div class="spinner"></div>
                <p class="text-muted">جاري تحميل الطلبات...</p>
            </div>
        `;

        fetch(`get_captain_orders.php?tab=${currentTab}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    displayOrders(data.orders);
                } else {
                    showNotification('حدث خطأ في تحميل الطلبات', 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                container.innerHTML = `
                    <div class="empty-state">
                        <i class="bi bi-exclamation-triangle"></i>
                        <h5>خطأ في الاتصال</h5>
                        <p>يرجى المحاولة مرة أخرى</p>
                    </div>
                `;
            });
    }

    /**
     * عرض الطلبات
     */
    function displayOrders(orders) {
        const container = document.getElementById('ordersContainer');
        
        if (!orders || orders.length === 0) {
            if (currentTab === 'current') {
                container.innerHTML = `
                    <div class="empty-state">
                        <i class="bi bi-inbox"></i>
                        <h5>لا توجد طلبات حالية</h5>
                        <p>ستظهر الطلبات الجديدة هنا</p>
                    </div>
                `;
            } else {
                container.innerHTML = `
                    <div class="empty-state">
                        <i class="bi bi-check-circle"></i>
                        <h5>لا توجد طلبات مكتملة</h5>
                        <p>الطلبات التي تكملها ستظهر هنا</p>
                    </div>
                `;
            }
            return;
        }

        let html = '';
        
        orders.forEach(order => {
            const statusClass = order.status;
            const statusText = order.status === 'accepted' ? 'تم القبول' : 
                              order.status === 'on_the_way' ? 'في الطريق' : 'تم التوصيل';
            const orderTime = new Date(order.created_at).toLocaleString('ar-EG');
            
            html += `
                <div class="order-card ${statusClass}" id="order-${order.id}">
                    <div class="order-header">
                        <span class="order-id">طلب #${order.id}</span>
                        <span class="order-time">${orderTime}</span>
                    </div>
                    
                    <div class="customer-info">
                        <div class="info-row">
                            <i class="bi bi-person-circle"></i>
                            <span>${escapeHtml(order.customer_name)}</span>
                        </div>
                        <div class="info-row">
                            <i class="bi bi-telephone"></i>
                            <span dir="ltr">${escapeHtml(order.customer_phone)}</span>
                        </div>
                        <div class="info-row">
                            <i class="bi bi-geo-alt"></i>
                            <span>${escapeHtml(order.customer_address || 'لا يوجد عنوان')}</span>
                        </div>
                    </div>
                    
                    <div class="order-total">
                        <span>المجموع الكلي</span>
                        <span class="total-price">${formatMoney(order.total)}</span>
                    </div>
            `;
            
            // أزرار الإجراءات حسب الحالة
            if (order.status === 'accepted') {
                html += `
                    <div class="order-actions">
                        <button class="action-btn start" onclick="updateOrderStatus(${order.id}, 'on_the_way')">
                            <i class="bi bi-truck"></i> بدء التوصيل
                        </button>
                        <button class="action-btn map" onclick="openMap('${escapeHtml(order.customer_address)}')">
                            <i class="bi bi-map"></i> خرائط
                        </button>
                    </div>
                `;
            } else if (order.status === 'on_the_way') {
                html += `
                    <div class="order-actions">
                        <button class="action-btn complete" onclick="updateOrderStatus(${order.id}, 'delivered')">
                            <i class="bi bi-check-circle"></i> تم التوصيل
                        </button>
                        <button class="action-btn map" onclick="openMap('${escapeHtml(order.customer_address)}')">
                            <i class="bi bi-map"></i> خرائط
                        </button>
                    </div>
                `;
            } else if (order.status === 'delivered') {
                html += `
                    <div class="order-actions">
                        <button class="action-btn" style="background: #10b981; color: white;" disabled>
                            <i class="bi bi-check2-all"></i> مكتمل
                        </button>
                    </div>
                `;
            }
            
            html += `</div>`;
        });
        
        container.innerHTML = html;
    }

    /**
     * تحديث حالة الطلب
     */
    function updateOrderStatus(orderId, newStatus) {
        let confirmMessage = '';
        let actionText = '';
        
        if (newStatus === 'on_the_way') {
            confirmMessage = 'هل أنت متأكد من بدء التوصيل؟';
            actionText = 'بدأ التوصيل';
        } else if (newStatus === 'delivered') {
            confirmMessage = 'هل أنت متأكد من إتمام التوصيل؟';
            actionText = 'تم التوصيل';
        }
        
        if (!confirm(confirmMessage)) return;
        
        fetch('update_order_status.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ 
                order_id: orderId, 
                status: newStatus 
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification(`تم ${actionText} بنجاح`, 'success');
                playNotificationSound();
                loadOrders(); // إعادة تحميل الطلبات
            } else {
                showNotification(data.message || 'حدث خطأ', 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification('حدث خطأ في الاتصال', 'error');
        });
    }

    /**
     * تبديل التبويب
     */
    function switchTab(tab) {
        currentTab = tab;
        
        // تحديث شكل التبويبات
        document.querySelectorAll('.tab-btn').forEach(btn => {
            btn.classList.remove('active');
        });
        event.target.classList.add('active');
        
        // تحميل الطلبات
        loadOrders();
    }

    /**
     * فتح الخريطة
     */
    function openMap(address) {
        if (!address) {
            showNotification('لا يوجد عنوان للعميل', 'error');
            return;
        }
        window.open(`https://maps.google.com/?q=${encodeURIComponent(address)}`, '_blank');
    }

    /**
     * التحديث التلقائي كل 5 ثواني
     */
    function startAutoRefresh() {
        setInterval(() => {
            if (currentTab === 'current') {
                fetch(`check_order_updates.php?last_update=${encodeURIComponent(lastUpdate)}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.updated) {
                            loadOrders();
                            if (data.message) {
                                showNotification(data.message, 'info');
                                playNotificationSound();
                            }
                        }
                        lastUpdate = data.server_time;
                    })
                    .catch(error => console.error('Auto refresh error:', error));
            }
        }, 5000);
    }

    /**
     * دوال مساعدة
     */
    function formatMoney(amount) {
        return Number(amount).toLocaleString('ar-EG') + ' ريال';
    }

    function escapeHtml(text) {
        if (!text) return '';
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    function showNotification(message, type = 'info') {
        const notification = document.createElement('div');
        notification.className = `notification ${type}`;
        
        let icon = 'info-circle';
        if (type === 'success') icon = 'check-circle';
        if (type === 'error') icon = 'exclamation-circle';
        
        notification.innerHTML = `
            <i class="bi bi-${icon} fs-4"></i>
            <span>${message}</span>
        `;
        
        document.body.appendChild(notification);
        
        setTimeout(() => {
            notification.classList.add('fade-out');
            setTimeout(() => notification.remove(), 300);
        }, 3000);
    }

    function playNotificationSound() {
        const audio = document.getElementById('notificationSound');
        if (audio) {
            audio.currentTime = 0;
            audio.play().catch(() => {});
        }
    }

    // التهيئة
    document.addEventListener('DOMContentLoaded', function() {
        loadOrders();
        startAutoRefresh();
    });
    </script>
</body>
</html>
        </div>
    </div>
</nav>
</body>
</html>