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

$captain_id = $_SESSION['captain_id'];

// Get current orders with coordinates
$current_orders = $conn->query("
    SELECT o.*, c.name as customer_name, c.phone as customer_phone, 
           c.address as customer_address, c.latitude, c.longitude,
           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, user-scalable=no">
    <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;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        *{margin:0;padding:0;box-sizing:border-box;}
        body{font-family:'Tajawal',sans-serif;background:#f5f7fb;padding-bottom:20px;}
        .navbar{background:linear-gradient(135deg,#F57C00,#E65100);color:white;position:sticky;top:0;z-index:1000;padding:12px 16px;}
        .order-card{background:white;border-radius:16px;padding:16px;margin-bottom:16px;box-shadow:0 2px 8px rgba(0,0,0,0.08);border-right:4px solid #F57C00;}
        .order-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;padding-bottom:8px;border-bottom:1px solid #e9ecef;}
        .order-id{font-weight:800;color:#F57C00;}
        .coords-box{background:#f8f9fa;border-radius:10px;padding:10px 12px;margin:10px 0;font-family:monospace;font-size:12px;direction:ltr;text-align:left;border:1px solid #e9ecef;}
        .coords-text{font-weight:600;color:#2c3e50;}
        .copy-coords-btn{background:#F57C00;color:white;border:none;padding:4px 12px;border-radius:20px;font-size:11px;margin-right:10px;transition:all 0.2s;}
        .copy-coords-btn:active{transform:scale(0.95);}
        .info-row{display:flex;align-items:center;gap:10px;margin-bottom:8px;font-size:0.85rem;}
        .info-row i{width:22px;color:#F57C00;}
        .total-box{background:linear-gradient(135deg,#10b981,#34d399);color:white;border-radius:12px;padding:12px;margin:10px 0;}
        .btn-google-maps{background:#4285F4;color:white;border:none;padding:10px 16px;border-radius:10px;font-size:14px;display:inline-flex;align-items:center;gap:8px;transition:all 0.2s;text-decoration:none;}
        .btn-google-maps:hover{background:#3367D6;transform:translateY(-2px);color:white;}
        .action-buttons{display:flex;gap:8px;margin-top:12px;flex-wrap:wrap;}
        .btn-mobile{flex:1;padding:10px;border:none;border-radius:10px;font-size:0.8rem;font-weight:600;display:inline-flex;align-items:center;justify-content:center;gap:6px;cursor:pointer;transition:all 0.2s;text-decoration:none;}
        .btn-mobile:active{transform:scale(0.97);}
        .toast-container{position:fixed;top:70px;left:15px;right:15px;z-index:1500;pointer-events:none;}
        .toast-msg{background:white;border-radius:40px;padding:12px 20px;margin-bottom:10px;box-shadow:0 4px 12px rgba(0,0,0,0.15);display:flex;align-items:center;gap:10px;border-right:4px solid;animation:slideDown 0.3s ease;}
        .toast-msg.success{border-right-color:#28a745;}
        .toast-msg.info{border-right-color:#F57C00;}
        @keyframes slideDown{from{opacity:0;transform:translateY(-20px);}to{opacity:1;transform:translateY(0);}}
        @media(max-width:768px){.container{padding-left:12px;padding-right:12px;}.order-card{padding:14px;}.btn-google-maps{padding:8px 12px;font-size:13px;}.action-buttons{flex-direction:column;}}
    </style>
</head>
<body>
    <nav class="navbar">
        <div class="container-fluid">
            <span class="navbar-brand text-white">
                <i class="bi bi-list-check"></i> الطلبات الحالية
            </span>
            <div>
                <a href="dashboard.php" class="text-white me-3">
                    <i class="bi bi-house-door fs-5"></i>
                </a>
                <a href="profile.php" class="text-white">
                    <i class="bi bi-person-circle fs-5"></i>
                </a>
            </div>
        </div>
    </nav>

    <div class="container mt-3">
        <?php if (isset($_SESSION['message'])): ?>
            <div class="alert alert-<?php echo $_SESSION['message_type']; ?> alert-dismissible fade show" role="alert">
                <i class="bi bi-<?php echo $_SESSION['message_type'] == 'success' ? 'check-circle' : 'info-circle'; ?> me-2"></i>
                <?php echo $_SESSION['message']; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                <?php unset($_SESSION['message']); unset($_SESSION['message_type']); ?>
            </div>
        <?php endif; ?>

        <?php if ($current_orders->num_rows > 0): ?>
            <?php while ($order = $current_orders->fetch_assoc()): 
                $has_coords = !empty($order['latitude']) && !empty($order['longitude']);
                $has_discount = !empty($order['applied_discount_amount']) && $order['applied_discount_amount'] > 0;
                $google_maps_url = $has_coords 
                    ? "https://www.google.com/maps/dir/?api=1&destination=" . $order['latitude'] . "," . $order['longitude']
                    : "https://www.google.com/maps/search/?api=1&query=" . urlencode($order['customer_address']);
            ?>
                <div class="order-card">
                    <div class="order-header">
                        <span class="order-id">طلب #<?php echo $order['id']; ?></span>
                        <span class="badge bg-<?php 
                            $status_badge = ['pending' => 'warning', 'accepted' => 'info', 'on_the_way' => 'primary'];
                            echo $status_badge[$order['status']];
                        ?>">
                            <?php 
                            $status_text = ['pending' => 'قيد الانتظار', 'accepted' => 'تم القبول', 'on_the_way' => 'في الطريق'];
                            echo $status_text[$order['status']];
                            ?>
                        </span>
                    </div>
                    
                    <div class="info-row">
                        <i class="bi bi-person"></i>
                        <span><?php echo $order['customer_name']; ?></span>
                    </div>
                    <div class="info-row">
                        <i class="bi bi-telephone"></i>
                        <a href="tel:<?php echo $order['customer_phone']; ?>" class="text-decoration-none"><?php echo $order['customer_phone']; ?></a>
                    </div>
                    <div class="info-row">
                        <i class="bi bi-geo-alt"></i>
                        <span><?php echo mb_substr($order['customer_address'], 0, 50); ?></span>
                    </div>
                    
                    <!-- عرض الإحداثيات ونسخها -->
                    <?php if ($has_coords): ?>
                    <div class="coords-box">
                        <i class="bi bi-pin-map-fill text-primary"></i>
                        <span class="coords-text" id="coords-<?php echo $order['id']; ?>">
                            <?php echo number_format($order['latitude'], 6); ?>, <?php echo number_format($order['longitude'], 6); ?>
                        </span>
                        <button class="copy-coords-btn" onclick="copyCoordinates(<?php echo $order['latitude']; ?>, <?php echo $order['longitude']; ?>, <?php echo $order['id']; ?>)">
                            <i class="bi bi-clipboard"></i> نسخ
                        </button>
                    </div>
                    <?php else: ?>
                    <div class="coords-box text-muted">
                        <i class="bi bi-geo-alt"></i> لا توجد إحداثيات دقيقة للعميل
                    </div>
                    <?php endif; ?>
                    
                    <?php if ($has_discount): ?>
                    <div class="alert alert-success py-2 px-3 mb-2">
                        <i class="bi bi-tag"></i> خصم: <?php echo number_format($order['applied_discount_amount'], 2); ?> ريال
                    </div>
                    <?php endif; ?>
                    
                    <div class="total-box">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <small class="opacity-75">المجموع الكلي</small>
                                <div class="fw-bold fs-5"><?php echo number_format($order['total'], 2); ?> ريال</div>
                            </div>
                            <?php if ($has_discount): ?>
                                <small><s><?php echo number_format($order['total'] + $order['applied_discount_amount'], 2); ?> ريال</s></small>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <div class="action-buttons">
                        <?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 w-100">
                                    <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 w-100">
                                    <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 w-100">
                                    <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">
                            <i class="bi bi-list"></i> تفاصيل الطلب
                        </a>
                        
                        <a href="<?php echo $google_maps_url; ?>" target="_blank" class="btn btn-google-maps btn-mobile">
                            <i class="bi bi-google"></i> خرائط Google
                        </a>
                    </div>
                </div>
            <?php endwhile; ?>
        <?php else: ?>
            <div class="empty-state text-center py-5">
                <i class="bi bi-inbox fs-1 text-muted"></i>
                <h5 class="text-muted mt-3">لا توجد طلبات حالية</h5>
                <p class="text-muted">انتظر حتى يتم تعيين طلبات جديدة لك</p>
                <a href="dashboard.php" class="btn btn-primary mt-2">
                    <i class="bi bi-arrow-return-left"></i> العودة للرئيسية
                </a>
            </div>
        <?php endif; ?>
    </div>

    <div class="toast-container" id="toastContainer"></div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function confirmAction(actionName) {
            return confirm(`هل أنت متأكد من ${actionName}؟`);
        }
        
        function copyCoordinates(lat, lng, orderId) {
            const coords = `${lat}, ${lng}`;
            navigator.clipboard.writeText(coords).then(() => {
                showToast('✅ تم نسخ الإحداثيات: ' + coords, 'success');
                const btn = document.querySelector(`#coords-${orderId}`)?.parentElement?.querySelector('.copy-coords-btn');
                if(btn) {
                    const originalText = btn.innerHTML;
                    btn.innerHTML = '<i class="bi bi-check"></i> تم النسخ';
                    setTimeout(() => { btn.innerHTML = originalText; }, 1500);
                }
            }).catch(() => {
                alert('اضغط Ctrl+C لنسخ: ' + coords);
            });
        }
        
        function showToast(message, type) {
            const container = document.getElementById('toastContainer');
            const toast = document.createElement('div');
            toast.className = `toast-msg ${type}`;
            toast.innerHTML = `<i class="bi bi-${type === 'success' ? 'check-circle-fill' : 'info-circle-fill'}"></i><span>${message}</span>`;
            container.appendChild(toast);
            setTimeout(() => {
                toast.style.opacity = '0';
                setTimeout(() => toast.remove(), 200);
            }, 3000);
        }
        
        // Auto refresh every 30 seconds
        setInterval(() => {
            location.reload();
        }, 30000);
    </script>
</body>
</html>