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

// Get captain's current orders with coordinates
$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, c.latitude, c.longitude
    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, 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;}
        .stat-card{background:white;border-radius:16px;padding:20px;box-shadow:0 2px 10px rgba(0,0,0,0.08);border-right:4px solid #F57C00;margin-bottom:20px;transition:transform 0.2s;}
        .stat-card:hover{transform:translateY(-2px);}
        .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);}
        .btn-google-maps{background:#4285F4;color:white;border:none;padding:8px 15px;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;}
        .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;}}
    </style>
</head>
<body>
    <nav class="navbar">
        <div class="container-fluid">
            <span class="navbar-brand text-white">
                <i class="bi bi-person-badge"></i> مرحباً، <?php echo $_SESSION['captain_name']; ?>
            </span>
            <div>
                <a href="profile.php" class="text-white me-3">
                    <i class="bi bi-person-circle fs-5"></i>
                </a>
            </div>
        </div>
    </nav>

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

        <!-- Current Orders -->
        <?php if ($current_orders->num_rows > 0): ?>
            <?php while ($order = $current_orders->fetch_assoc()): 
                $has_coords = !empty($order['latitude']) && !empty($order['longitude']);
                $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" data-order-id="<?php echo $order['id']; ?>">
                    <div class="order-header">
                        <h5 class="mb-0">طلب #<?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> 
                        <a href="tel:<?php echo $order['customer_phone']; ?>" class="text-decoration-none"><?php echo $order['customer_phone']; ?></a>
                    </div>
                    <div class="mb-2">
                        <strong><i class="bi bi-geo-alt"></i> العنوان:</strong> 
                        <?php echo mb_substr($order['customer_address'], 0, 60); ?>
                    </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; ?>
                    
                    <div class="mb-3">
                        <strong><i class="bi bi-currency-dollar"></i> المجموع:</strong> 
                        <?php echo number_format($order['total'], 2); ?> ريال
                    </div>
                    
                    <div class="d-flex gap-2 flex-wrap">
                        <?php if ($order['status'] == 'pending'): ?>
                            <form method="POST" action="update_order.php" class="d-inline" 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-sm">
                                    <i class="bi bi-check-circle"></i> قبول الطلب
                                </button>
                            </form>
                        <?php elseif ($order['status'] == 'accepted'): ?>
                            <form method="POST" action="update_order.php" class="d-inline" 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-sm">
                                    <i class="bi bi-truck"></i> بدأ التوصيل
                                </button>
                            </form>
                        <?php elseif ($order['status'] == 'on_the_way'): ?>
                            <form method="POST" action="update_order.php" class="d-inline" 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-sm">
                                    <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-sm">
                            <i class="bi bi-list"></i> تفاصيل
                        </a>
                        
                        <a href="<?php echo $google_maps_url; ?>" target="_blank" class="btn btn-google-maps btn-sm">
                            <i class="bi bi-google"></i> خرائط Google
                        </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>

    <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>
        // Toast notification
        function showToast(message, type = 'success') {
            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);
        }
        
        // Copy coordinates function
        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);
            });
        }
        
        // Confirm action
        function confirmAction(action) {
            return confirm(`هل أنت متأكد من ${action}؟`);
        }
        
        // Auto refresh every 30 seconds
        setInterval(() => {
            location.reload();
        }, 30000);
        
        // عرض تنبيه إذا كانت الإحداثيات موجودة
        document.addEventListener('DOMContentLoaded', function() {
            const coordsBoxes = document.querySelectorAll('.coords-box');
            if(coordsBoxes.length > 0) {
                console.log('📍 تم تحميل الإحداثيات بنجاح');
            }
        });
    </script>
</body>
</html>