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

$captain_id = $_SESSION['captain_id'];

// Get current orders with discount information
$current_orders = $conn->query("
    SELECT o.*, c.name as customer_name, c.phone as customer_phone, c.address as customer_address,
           d.discount_name, o.discount_amount as applied_discount_amount
    FROM orders o 
    JOIN customers c ON o.customer_id = c.id 
    LEFT JOIN direct_discounts d ON o.discount_id = d.id
    WHERE o.captain_id = '$captain_id' AND o.status != 'delivered'
    ORDER BY o.created_at DESC
");
?>

<!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=no, viewport-fit=cover">
    <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>
        :root {
            --primary-color: #F57C00;
            --secondary-color: #FF9800;
            --success-color: #28a745;
            --info-color: #17a2b8;
            --warning-color: #ffc107;
            --danger-color: #dc3545;
        }
        
        * {
            box-sizing: border-box;
            -webkit-tap-highlight-color: transparent;
        }
        
        body {
            font-family: 'Tajawal', sans-serif;
            background-color: #f8f9fa;
            margin: 0;
            padding: 0;
            overflow-x: hidden;
            -webkit-text-size-adjust: 100%;
            -webkit-font-smoothing: antialiased;
        }
        
        .navbar {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            color: white;
            padding: 12px 0;
            position: sticky;
            top: 0;
            z-index: 1000;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .container {
            padding-left: 15px;
            padding-right: 15px;
            max-width: 100%;
        }
        
        .order-card {
            background: white;
            border-radius: 12px;
            padding: 16px;
            margin-bottom: 16px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
            border-right: 4px solid var(--primary-color);
            position: relative;
            width: 100%;
            overflow: hidden;
        }
        
        .bottom-nav {
            position: fixed;
            bottom: 0;
            right: 0;
            left: 0;
            background: white;
            box-shadow: 0 -4px 15px rgba(0,0,0,0.1);
            padding: 10px 15px;
            z-index: 1000;
            backdrop-filter: blur(10px);
            background: rgba(255, 255, 255, 0.95);
        }
        
        .nav-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 5px;
            width: 100%;
        }
        
        .nav-item {
            text-align: center;
        }
        
        .nav-link {
            color: #666;
            text-decoration: none;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 8px 0;
            border-radius: 8px;
            transition: all 0.3s ease;
        }
        
        .nav-link.active {
            color: var(--primary-color);
            background: rgba(245, 124, 0, 0.1);
        }
        
        .nav-icon {
            font-size: 1.4rem;
            margin-bottom: 4px;
        }
        
        .nav-label {
            font-size: 11px;
            font-weight: 500;
        }
        
        .discount-badge {
            background: linear-gradient(135deg, var(--success-color), #20c997);
            color: white;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 4px;
            margin-left: 8px;
            white-space: nowrap;
        }
        
        .customer-info {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 12px;
            margin: 12px 0;
            border: 1px solid #e9ecef;
        }
        
        .total-box {
            background: linear-gradient(135deg, var(--success-color), #8BC34A);
            color: white;
            border-radius: 10px;
            padding: 12px;
            margin: 10px 0;
        }
        
        .action-buttons {
            display: flex;
            flex-direction: column;
            gap: 8px;
            margin-top: 16px;
            width: 100%;
        }
        
        .btn-mobile {
            border-radius: 10px;
            padding: 12px 16px;
            font-weight: 600;
            font-size: 14px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            min-height: 48px;
            width: 100%;
            border: none;
            transition: all 0.2s ease;
        }
        
        .btn-mobile:active {
            transform: scale(0.98);
        }
        
        .empty-state {
            text-align: center;
            padding: 40px 20px;
        }
        
        .empty-icon {
            font-size: 3.5rem;
            color: #adb5bd;
            margin-bottom: 16px;
            opacity: 0.6;
        }
        
        .status-indicator {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            display: inline-block;
            margin-left: 6px;
        }
        
        .status-pending { background-color: var(--warning-color); }
        .status-accepted { background-color: var(--info-color); }
        .status-on_the_way { background-color: #0d6efd; }
        
        .order-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 8px;
            margin-bottom: 12px;
            padding-bottom: 10px;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .order-id {
            font-size: 16px;
            font-weight: 700;
            color: #333;
            flex: 1;
            min-width: 120px;
        }
        
        .time-badge {
            background: #e9ecef;
            color: #6c757d;
            padding: 4px 8px;
            border-radius: 20px;
            font-size: 11px;
            white-space: nowrap;
        }
        
        /* تحسين النصوص للهواتف */
        h4, h5, h6 {
            margin-top: 0;
            line-height: 1.3;
        }
        
        p, span, div {
            line-height: 1.5;
        }
        
        /* تحسينات للأزرار على الهواتف */
        @media (max-width: 768px) {
            .container {
                padding-left: 12px;
                padding-right: 12px;
            }
            
            .order-card {
                padding: 14px;
                margin-bottom: 14px;
                border-radius: 10px;
            }
            
            .btn-mobile {
                padding: 14px 16px;
                font-size: 15px;
            }
            
            .action-buttons {
                gap: 10px;
            }
            
            .bottom-nav {
                padding: 10px 12px;
            }
            
            .nav-icon {
                font-size: 1.3rem;
            }
            
            .nav-label {
                font-size: 10px;
            }
        }
        
        /* هواتف صغيرة جداً */
        @media (max-width: 360px) {
            .order-card {
                padding: 12px;
            }
            
            .btn-mobile {
                padding: 12px;
                font-size: 14px;
            }
            
            .container {
                padding-left: 10px;
                padding-right: 10px;
            }
            
            .order-id {
                font-size: 15px;
            }
        }
        
        /* منع التمرير الأفقي */
        html, body {
            max-width: 100%;
            overflow-x: hidden;
        }
        
        /* تحسينات للمحتوى الطويل */
        .text-truncate-mobile {
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        /* تأثيرات اللمس */
        .touch-feedback:active {
            background-color: rgba(0,0,0,0.05);
        }
        
        /* تحسين أداء الصفحة */
        .will-change-transform {
            will-change: transform;
        }
        
        /* تخصيص شريط التمرير */
        ::-webkit-scrollbar {
            width: 4px;
        }
        
        ::-webkit-scrollbar-track {
            background: #f1f1f1;
        }
        
        ::-webkit-scrollbar-thumb {
            background: var(--primary-color);
            border-radius: 2px;
        }
        
        /* إخفاء شريط التمرير في بعض المتصفحات */
        .hide-scrollbar {
            -ms-overflow-style: none;
            scrollbar-width: none;
        }
        
        .hide-scrollbar::-webkit-scrollbar {
            display: none;
        }
        
        /* تحسينات للوضع الليلي */
        @media (prefers-color-scheme: dark) {
            body {
                background-color: #121212;
                color: #e0e0e0;
            }
            
            .order-card {
                background-color: #1e1e1e;
                border-right-color: var(--primary-color);
                color: #e0e0e0;
            }
            
            .customer-info {
                background-color: #2d2d2d;
                border-color: #3d3d3d;
            }
            
            .time-badge {
                background-color: #2d2d2d;
                color: #b0b0b0;
            }
        }
        
        /* تحميل سريع */
        .fade-in {
            animation: fadeIn 0.3s ease-out;
        }
        
        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        /* تحسين الظلال */
        .shadow-mobile {
            box-shadow: 0 2px 6px rgba(0,0,0,0.08);
        }
    </style>
</head>
<body>
    <!-- شريط التنقل العلوي -->
    <nav class="navbar">
        <div class="container">
            <div class="d-flex align-items-center justify-content-center w-100">
                <span class="navbar-text text-white fw-bold fs-5">
                    <i class="bi bi-person-badge me-2"></i> الطلبات الحالية
                </span>
            </div>
        </div>
    </nav>

    <!-- المحتوى الرئيسي -->
    <main class="container mt-3 mb-5 pb-4">
        <?php if (isset($_SESSION['message'])): ?>
            <div class="alert alert-<?php echo $_SESSION['message_type']; ?> alert-dismissible fade show shadow-mobile" role="alert">
                <div class="d-flex align-items-center">
                    <i class="bi <?php echo $_SESSION['message_type'] == 'success' ? 'bi-check-circle-fill' : 'bi-info-circle-fill'; ?> me-2 fs-5"></i>
                    <div class="flex-grow-1"><?php echo $_SESSION['message']; ?></div>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                <?php unset($_SESSION['message']); unset($_SESSION['message_type']); ?>
            </div>
        <?php endif; ?>

        <?php if ($current_orders->num_rows > 0): ?>
            <div class="orders-list">
                <?php while ($order = $current_orders->fetch_assoc()): ?>
                    <?php 
                    $has_discount = !empty($order['applied_discount_amount']) && $order['applied_discount_amount'] > 0;
                    $total_before_discount = $order['total'] + $order['applied_discount_amount'];
                    ?>
                    
                    <div class="order-card fade-in will-change-transform touch-feedback" 
                         onclick="viewOrderDetails(<?php echo $order['id']; ?>)">
                        <div class="order-header">
                            <div class="d-flex align-items-center flex-wrap">
                                <span class="order-id">طلب #<?php echo $order['id']; ?></span>
                                <?php if ($has_discount && !empty($order['discount_name'])): ?>
                                    <span class="discount-badge">
                                        <i class="bi bi-percent"></i>
                                        <?php echo htmlspecialchars(mb_substr($order['discount_name'], 0, 15)); ?>
                                    </span>
                                <?php endif; ?>
                            </div>
                            <div class="d-flex align-items-center">
                                <span class="status-indicator status-<?php echo $order['status']; ?>"></span>
                                <span class="badge bg-<?php 
                                    $status_badge = [
                                        'pending' => 'warning',
                                        'accepted' => 'info',
                                        'on_the_way' => 'primary'
                                    ];
                                    echo $status_badge[$order['status']];
                                ?> me-2">
                                    <?php 
                                    $status_text = [
                                        'pending' => 'قيد الانتظار',
                                        'accepted' => 'تم القبول',
                                        'on_the_way' => 'في الطريق'
                                    ];
                                    echo $status_text[$order['status']];
                                    ?>
                                </span>
                                <span class="time-badge">
                                    <i class="bi bi-clock"></i> <?php echo date('H:i', strtotime($order['created_at'])); ?>
                                </span>
                            </div>
                        </div>
                        
                        <!-- معلومات العميل -->
                        <div class="customer-info">
                            <div class="row g-2">
                                <div class="col-12">
                                    <div class="d-flex align-items-center">
                                        <div class="bg-primary text-white rounded-circle d-flex align-items-center justify-content-center" 
                                             style="width: 36px; height: 36px; flex-shrink: 0;">
                                            <i class="bi bi-person"></i>
                                        </div>
                                        <div class="ms-3 flex-grow-1">
                                            <small class="text-muted d-block">العميل</small>
                                            <strong class="text-truncate-mobile"><?php echo $order['customer_name']; ?></strong>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="col-12 mt-2">
                                    <div class="d-flex align-items-center">
                                        <div class="bg-success text-white rounded-circle d-flex align-items-center justify-content-center" 
                                             style="width: 36px; height: 36px; flex-shrink: 0;">
                                            <i class="bi bi-telephone"></i>
                                        </div>
                                        <div class="ms-3 flex-grow-1">
                                            <small class="text-muted d-block">الهاتف</small>
                                            <strong>
                                                <a href="tel:<?php echo $order['customer_phone']; ?>" 
                                                   class="text-decoration-none text-dark"
                                                   onclick="event.stopPropagation()">
                                                    <?php echo $order['customer_phone']; ?>
                                                </a>
                                            </strong>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="col-12 mt-2">
                                    <div class="d-flex align-items-start">
                                        <div class="bg-warning text-white rounded-circle d-flex align-items-center justify-content-center mt-1" 
                                             style="width: 36px; height: 36px; flex-shrink: 0;">
                                            <i class="bi bi-geo-alt"></i>
                                        </div>
                                        <div class="ms-3 flex-grow-1">
                                            <small class="text-muted d-block">العنوان</small>
                                            <div class="text-truncate-mobile"><?php echo $order['customer_address']; ?></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- معلومات التخفيض -->
                        <?php if ($has_discount): ?>
                            <div class="alert alert-success alert-dismissible fade show py-2 px-3 mb-2" 
                                 onclick="event.stopPropagation()">
                                <div class="d-flex align-items-center">
                                    <i class="bi bi-tag-fill me-2"></i>
                                    <div class="flex-grow-1">
                                        <small class="d-block fw-bold">خصم مطبق</small>
                                        <small class="d-block">
                                            تم تطبيق خصم بقيمة <strong><?php echo number_format($order['applied_discount_amount'], 2); ?> ريال</strong>
                                        </small>
                                    </div>
                                    <button type="button" class="btn-close btn-close-sm" data-bs-dismiss="alert" 
                                            onclick="event.stopPropagation()"></button>
                                </div>
                            </div>
                        <?php endif; ?>
                        
                        <!-- إجمالي المبلغ -->
                        <div class="total-box" onclick="event.stopPropagation()">
                            <div class="d-flex justify-content-between align-items-center">
                                <div class="d-flex align-items-center">
                                    <i class="bi bi-wallet2 fs-5 me-3"></i>
                                    <div>
                                        <small class="d-block opacity-75">المجموع الكلي</small>
                                        <strong class="fs-5"><?php echo number_format($order['total'], 2); ?> ريال</strong>
                                    </div>
                                </div>
                                <?php if ($has_discount): ?>
                                    <div class="text-end">
                                        <small class="opacity-75 d-block">قبل الخصم</small>
                                        <s class="text-light opacity-75 fs-6"><?php echo number_format($total_before_discount, 2); ?> ريال</s>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <!-- أزرار الإجراءات -->
                        <div class="action-buttons" onclick="event.stopPropagation()">
                            <?php if ($order['status'] == 'pending'): ?>
                                <form method="POST" action="update_order.php" class="w-100" onsubmit="return confirmAction('قبول الطلب')">
                                    <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-mobile">
                                        <i class="bi bi-check-circle"></i> قبول الطلب
                                    </button>
                                </form>
                            <?php elseif ($order['status'] == 'accepted'): ?>
                                <form method="POST" action="update_order.php" class="w-100" onsubmit="return confirmAction('بدء التوصيل')">
                                    <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-mobile">
                                        <i class="bi bi-truck"></i> بدأ التوصيل
                                    </button>
                                </form>
                            <?php elseif ($order['status'] == 'on_the_way'): ?>
                                <form method="POST" action="update_order.php" class="w-100" onsubmit="return confirmAction('تأكيد التوصيل')">
                                    <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-mobile">
                                        <i class="bi bi-check2-circle"></i> تم التوصيل
                                    </button>
                                </form>
                            <?php endif; ?>
                            
                            <a href="order_details.php?id=<?php echo $order['id']; ?>" 
                               class="btn btn-info btn-mobile text-decoration-none">
                                <i class="bi bi-list"></i> التفاصيل والأقسام
                            </a>
                            
                            <div class="d-flex gap-2">
                                <a href="https://maps.google.com/?q=<?php echo urlencode($order['customer_address']); ?>" 
                                   target="_blank" class="btn btn-warning btn-mobile text-decoration-none flex-grow-1">
                                    <i class="bi bi-map"></i> خرائط
                                </a>
                                <a href="tel:<?php echo $order['customer_phone']; ?>" 
                                   class="btn btn-outline-primary btn-mobile text-decoration-none flex-grow-1">
                                    <i class="bi bi-telephone"></i> اتصال
                                </a>
                            </div>
                        </div>
                    </div>
                <?php endwhile; ?>
            </div>
        <?php else: ?>
            <div class="empty-state">
                <i class="bi bi-inbox empty-icon"></i>
                <h5 class="text-muted mb-3">لا توجد طلبات حالية</h5>
                <p class="text-muted mb-4">انتظر حتى يتم تعيين طلبات جديدة لك</p>
                <a href="dashboard.php" class="btn btn-primary btn-mobile">
                    <i class="bi bi-arrow-return-left me-2"></i> العودة للرئيسية
                </a>
            </div>
        <?php endif; ?>
    </main>

    <!-- شريط التنقل السفلي -->
  

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // دالة لعرض تفاصيل الطلب
        function viewOrderDetails(orderId) {
            window.location.href = 'captain_order_details.php?id=' + orderId;
        }
        
        // دالة لتأكيد الإجراء
        function confirmAction(actionName) {
            return confirm(`هل أنت متأكد من ${actionName}؟`);
        }
        
        // تحسين تجربة اللمس
        document.addEventListener('DOMContentLoaded', function() {
            // منع التمرير الأفقي
            document.body.addEventListener('touchmove', function(e) {
                if (e.touches.length === 1) {
                    const touch = e.touches[0];
                    const element = document.elementFromPoint(touch.clientX, touch.clientY);
                    
                    // السماح بالتمرير العمودي فقط
                    const scrollable = element && (element.scrollHeight > element.clientHeight);
                    if (!scrollable && element && element.tagName !== 'TEXTAREA' && element.tagName !== 'INPUT') {
                        e.preventDefault();
                    }
                }
            }, { passive: false });
            
            // تحسين أداء اللمس
            const touchElements = document.querySelectorAll('.btn-mobile, .order-card, .nav-link');
            touchElements.forEach(el => {
                el.style.touchAction = 'manipulation';
                el.style.WebkitTapHighlightColor = 'transparent';
            });
            
            // إضافة تأثير الضغط على الأزرار
            document.querySelectorAll('.btn-mobile').forEach(btn => {
                btn.addEventListener('touchstart', function() {
                    this.style.transform = 'scale(0.98)';
                });
                
                btn.addEventListener('touchend', function() {
                    this.style.transform = 'scale(1)';
                });
            });
            
            // تحديث الصفحة كل 30 ثانية
            setInterval(function() {
                window.location.reload();
            }, 30000);
            
            // تحسين العرض على الشاشات الصغيرة
            function adjustForScreenSize() {
                const screenWidth = window.innerWidth;
                const container = document.querySelector('.container');
                
                if (screenWidth < 400) {
                    container.style.paddingLeft = '8px';
                    container.style.paddingRight = '8px';
                }
            }
            
            // استدعاء الدالة عند التحميل وعند تغيير الحجم
            adjustForScreenSize();
            window.addEventListener('resize', adjustForScreenSize);
            
            // إضافة تأثير التحميل للصور
            const images = document.querySelectorAll('img');
            images.forEach(img => {
                img.addEventListener('load', function() {
                    this.style.opacity = '1';
                    this.style.transition = 'opacity 0.3s ease';
                });
                
                img.style.opacity = '0';
            });
            
            // تحسين أداء الصفحة
            if ('requestIdleCallback' in window) {
                window.requestIdleCallback(() => {
                    // تحميل لاحق للمحتوى غير الضروري
                });
            }
        });
        
        // منع التكبير بالدبل تاب
        let lastTouchEnd = 0;
        document.addEventListener('touchend', function(event) {
            const now = (new Date()).getTime();
            if (now - lastTouchEnd <= 300) {
                event.preventDefault();
            }
            lastTouchEnd = now;
        }, false);
        
        // تحسين العرض على iOS
        if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) {
            document.body.style.WebkitOverflowScrolling = 'touch';
            document.body.style.height = '100vh';
            document.body.style.overflow = 'hidden';
            
            // إصلاح شريط التمرير على iOS
            setTimeout(() => {
                window.scrollTo(0, 0);
            }, 100);
        }
    </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>
        </div>
    </div>
</nav>
</body>
</html>