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

$captain_id = $_SESSION['captain_id'];

// Get completed orders with coordinates
$completed_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
    LIMIT 100
");

// Get total earnings
$total_earnings = $conn->query("
    SELECT COALESCE(SUM(total), 0) as total FROM orders 
    WHERE captain_id = '$captain_id' AND status = 'delivered'
")->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,#10b981,#059669);color:white;padding:12px 16px;}
        .stats-bar{background:white;border-radius:16px;padding:16px;margin:16px;box-shadow:0 2px 8px rgba(0,0,0,0.05);}
        .stat-number{font-size:1.8rem;font-weight:800;color:#10b981;}
        .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 #10b981;}
        .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:#10b981;}
        .info-row{display:flex;align-items:center;gap:10px;margin-bottom:8px;font-size:0.85rem;}
        .info-row i{width:22px;color:#10b981;}
        .coords-box{background:#f8f9fa;border-radius:10px;padding:8px 12px;margin:10px 0;font-family:monospace;font-size:12px;direction:ltr;text-align:left;}
        .copy-coords-btn{background:#10b981;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);}
        .total-amount{font-weight:700;color:#10b981;font-size:1.1rem;}
        .btn-google-maps{background:#4285F4;color:white;border:none;padding:8px 15px;border-radius:10px;font-size:13px;display:inline-flex;align-items:center;gap:6px;transition:all 0.2s;text-decoration:none;}
        .btn-google-maps:hover{background:#3367D6;transform:translateY(-2px);color:white;}
        .empty-state{text-align:center;padding:60px 20px;background:white;border-radius:20px;}
        .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:#10b981;}
        @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;}}
    </style>
</head>
<body>
    <nav class="navbar">
        <div class="container-fluid">
            <span class="navbar-brand text-white">
                <i class="bi bi-check-circle"></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">
        <!-- Statistics Bar -->
        <div class="stats-bar">
            <div class="row text-center">
                <div class="col-6">
                    <div class="stat-number"><?php echo $completed_orders->num_rows; ?></div>
                    <small class="text-muted">إجمالي الطلبات</small>
                </div>
                <div class="col-6">
                    <div class="stat-number"><?php echo number_format($total_earnings, 2); ?> ريال</div>
                    <small class="text-muted">إجمالي الأرباح</small>
                </div>
            </div>
        </div>

        <?php if ($completed_orders->num_rows > 0): ?>
            <?php while ($order = $completed_orders->fetch_assoc()): 
                $has_coords = !empty($order['latitude']) && !empty($order['longitude']);
                $google_maps_url = $has_coords 
                    ? "https://www.google.com/maps/search/?api=1&query=" . $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">
                        <h5 class="mb-0">طلب #<?php echo $order['id']; ?></h5>
                        <span class="badge bg-success">تم التوصيل</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, 60); ?></span>
                    </div>
                    
                    <?php if ($has_coords): ?>
                    <div class="coords-box">
                        <i class="bi bi-pin-map-fill text-primary"></i>
                        <span 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 endif; ?>
                    
                    <div class="row mt-2">
                        <div class="col-6">
                            <small class="text-muted">المجموع</small>
                            <div class="total-amount"><?php echo number_format($order['total'], 2); ?> ريال</div>
                        </div>
                        <div class="col-6 text-end">
                            <small class="text-muted">التاريخ</small>
                            <div><?php echo date('Y-m-d', strtotime($order['created_at'])); ?></div>
                        </div>
                    </div>
                    
                    <div class="mt-3 d-flex gap-2">
                        <a href="order_details.php?id=<?php echo $order['id']; ?>" class="btn btn-info btn-sm flex-grow-1">
                            <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="empty-state">
                <i class="bi bi-inbox" style="font-size: 3rem; color: #dee2e6;"></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 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);
        }
    </script>
</body>
</html>