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

if (!isset($_GET['id'])) {
    header('Location: orders.php');
    exit();
}

$order_id = $conn->real_escape_string($_GET['id']);
$captain_id = $_SESSION['captain_id'];

// Get order details with coordinates
$order_details = $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, d.discount_type, d.discount_value, 
           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.id = '$order_id' AND o.captain_id = '$captain_id'
")->fetch_assoc();

if (!$order_details) {
    header('Location: orders.php');
    exit();
}

$has_coordinates = !empty($order_details['latitude']) && !empty($order_details['longitude']);
$customer_lat = $order_details['latitude'] ?? null;
$customer_lng = $order_details['longitude'] ?? null;

// Create Google Maps URL
if ($has_coordinates) {
    $google_maps_directions = "https://www.google.com/maps/dir/?api=1&destination=" . $customer_lat . "," . $customer_lng;
    $google_maps_view = "https://www.google.com/maps/search/?api=1&query=" . $customer_lat . "," . $customer_lng;
} else {
    $google_maps_directions = "https://www.google.com/maps/dir/?api=1&destination=" . urlencode($order_details['customer_address']);
    $google_maps_view = "https://www.google.com/maps/search/?api=1&query=" . urlencode($order_details['customer_address']);
}

$has_discount = !empty($order_details['applied_discount_amount']) && $order_details['applied_discount_amount'] > 0;

// Get order items
$order_items = $conn->query("
    SELECT oi.*, m.name as meal_name, m.price as meal_price,
           mp.name as portion_name, mp.price as portion_price
    FROM order_items oi 
    JOIN meals m ON oi.meal_id = m.id 
    LEFT JOIN meal_portions mp ON oi.portion_id = mp.id
    WHERE oi.order_id = '$order_id'
");

// Calculate totals
$subtotal = 0;
$items_count = 0;
$order_items_data = [];
while ($item = $order_items->fetch_assoc()) {
    $item_price = !empty($item['portion_price']) ? $item['portion_price'] : $item['meal_price'];
    $item_total = $item_price * $item['quantity'];
    $subtotal += $item_total;
    $items_count++;
    
    $order_items_data[] = [
        'meal_name' => $item['meal_name'],
        'portion_name' => $item['portion_name'],
        'quantity' => $item['quantity'],
        'price' => $item_price,
        'total' => $item_total
    ];
}

$delivery_fee = isset($order_details['delivery_fee']) ? (float)$order_details['delivery_fee'] : 0;
$discount_amount = $has_discount ? (float)$order_details['applied_discount_amount'] : 0;
$final_total = (float)$order_details['total'];
$notes = !empty($order_details['notes']) ? $order_details['notes'] : 'لا توجد ملاحظات';
?>

<!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>تفاصيل الطلب #<?php echo $order_details['id']; ?> - 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;padding:12px 16px;}
        .main-card{background:white;border-radius:20px;padding:20px;margin-bottom:20px;box-shadow:0 2px 10px rgba(0,0,0,0.08);}
        .coordinates-card{background:linear-gradient(135deg,#f0f9ff,#e6f3ff);border-radius:12px;padding:15px;margin:15px 0;border-right:4px solid #4285F4;}
        .coordinates-text{font-family:monospace;font-size:14px;direction:ltr;text-align:left;background:#fff;padding:10px;border-radius:8px;border:1px solid #dee2e6;font-weight:600;}
        .btn-google-maps{background:#4285F4;color:white;border:none;padding:12px 20px;border-radius:12px;font-weight:600;transition:all 0.2s;display:inline-flex;align-items:center;gap:8px;text-decoration:none;}
        .btn-google-maps:hover{background:#3367D6;transform:translateY(-2px);color:white;}
        .total-summary{background:linear-gradient(135deg,#10b981,#34d399);color:white;border-radius:16px;padding:20px;margin:20px 0;}
        .copy-btn{background:#F57C00;color:white;border:none;padding:6px 16px;border-radius:30px;font-size:12px;cursor:pointer;transition:all 0.2s;}
        .copy-btn:active{transform:scale(0.95);}
        .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;}
        @keyframes slideDown{from{opacity:0;transform:translateY(-20px);}to{opacity:1;transform:translateY(0);}}
        @media(max-width:768px){.main-card{padding:15px;}.btn-google-maps{width:100%;}}
    </style>
</head>
<body>
    <nav class="navbar">
        <div class="container-fluid">
            <div class="d-flex align-items-center w-100">
                <a href="orders.php" class="text-white me-3" style="font-size:1.3rem;">
                    <i class="bi bi-arrow-right"></i>
                </a>
                <span class="fw-bold text-white">
                    <i class="bi bi-file-text me-2"></i>
                    تفاصيل الطلب #<?php echo $order_details['id']; ?>
                </span>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <!-- Order Info -->
        <div class="main-card">
            <div class="d-flex justify-content-between align-items-center mb-3 pb-2 border-bottom">
                <div>
                    <span class="fw-bold fs-5">طلب #<?php echo $order_details['id']; ?></span>
                    <?php if ($has_discount && !empty($order_details['discount_name'])): ?>
                        <span class="badge bg-success ms-2">
                            <i class="bi bi-percent"></i> <?php echo htmlspecialchars($order_details['discount_name']); ?>
                        </span>
                    <?php endif; ?>
                </div>
                <div>
                    <span class="badge bg-<?php 
                        $status_badge = ['pending' => 'warning', 'accepted' => 'info', 'on_the_way' => 'primary', 'delivered' => 'success'];
                        echo $status_badge[$order_details['status']];
                    ?> fs-6">
                        <?php 
                        $status_text = ['pending' => 'قيد الانتظار', 'accepted' => 'تم القبول', 'on_the_way' => 'في الطريق', 'delivered' => 'تم التوصيل'];
                        echo $status_text[$order_details['status']];
                        ?>
                    </span>
                </div>
            </div>
            
            <div class="row">
                <div class="col-md-6">
                    <p><strong>تاريخ الطلب:</strong> <?php echo date('Y-m-d H:i', strtotime($order_details['created_at'])); ?></p>
                </div>
                <div class="col-md-6">
                    <p><strong>عدد العناصر:</strong> <?php echo $items_count; ?> عنصر</p>
                </div>
            </div>
            
            <?php if ($notes != 'لا توجد ملاحظات'): ?>
            <div class="bg-warning bg-opacity-10 p-3 rounded-3 mt-2">
                <h6><i class="bi bi-chat-left-text me-2"></i>ملاحظات العميل:</h6>
                <p class="mb-0"><?php echo nl2br(htmlspecialchars($notes)); ?></p>
            </div>
            <?php endif; ?>
        </div>

        <!-- Customer Info -->
        <div class="main-card">
            <h5 class="mb-3"><i class="bi bi-person-circle me-2"></i>معلومات العميل</h5>
            <div class="row">
                <div class="col-md-6 mb-2">
                    <strong>الاسم:</strong> <?php echo $order_details['customer_name']; ?>
                </div>
                <div class="col-md-6 mb-2">
                    <strong>الهاتف:</strong> 
                    <a href="tel:<?php echo $order_details['customer_phone']; ?>"><?php echo $order_details['customer_phone']; ?></a>
                </div>
                <div class="col-12 mb-2">
                    <strong>العنوان:</strong> <?php echo $order_details['customer_address']; ?>
                </div>
            </div>
            
            <div class="d-flex gap-2 mt-3">
                <a href="tel:<?php echo $order_details['customer_phone']; ?>" class="btn btn-outline-primary">
                    <i class="bi bi-telephone"></i> اتصال
                </a>
                <a href="https://wa.me/<?php echo $order_details['customer_phone']; ?>" target="_blank" class="btn btn-outline-success">
                    <i class="bi bi-whatsapp"></i> واتساب
                </a>
            </div>
        </div>
        
        <!-- Location & Maps -->
        <div class="main-card">
            <h5 class="mb-3"><i class="bi bi-geo-alt"></i> موقع التوصيل</h5>
            
            <?php if ($has_coordinates): ?>
            <div class="coordinates-card">
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <strong><i class="bi bi-pin-map-fill text-primary"></i> الإحداثيات الدقيقة:</strong>
                    <button class="copy-btn" onclick="copyCoordinates()">
                        <i class="bi bi-clipboard"></i> نسخ الإحداثيات
                    </button>
                </div>
                <div class="coordinates-text" id="coordinatesText">
                    📍 <?php echo number_format($customer_lat, 8); ?>, <?php echo number_format($customer_lng, 8); ?>
                </div>
                <div class="mt-2 small text-muted">
                    <i class="bi bi-info-circle"></i> هذه الإحداثيات تم تحديدها بواسطة العميل عند إنشاء الطلب
                </div>
            </div>
            <?php else: ?>
            <div class="alert alert-warning">
                <i class="bi bi-exclamation-triangle"></i>
                لم يقم العميل بتحديد إحداثيات دقيقة. سيتم استخدام العنوان النصي.
            </div>
            <?php endif; ?>
            
            <div class="mt-3">
                <a href="<?php echo $google_maps_directions; ?>" target="_blank" class="btn btn-google-maps w-100">
                    <i class="bi bi-google"></i> التوجيه عبر Google Maps
                </a>
            </div>
        </div>
        
        <!-- Order Items -->
        <div class="main-card">
            <h5 class="mb-3"><i class="bi bi-basket"></i> عناصر الطلب (<?php echo $items_count; ?>)</h5>
            <div class="table-responsive">
                <table class="table table-sm">
                    <thead>
                        <tr>
                            <th>الوجبة</th>
                            <th>القسم</th>
                            <th>الكمية</th>
                            <th>السعر</th>
                            <th>المجموع</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($order_items_data as $item): ?>
                        <tr>
                            <td><?php echo $item['meal_name']; ?></td>
                            <td><?php echo $item['portion_name'] ?? 'كامل'; ?></td>
                            <td><?php echo $item['quantity']; ?></td>
                            <td><?php echo number_format($item['price'], 2); ?> ريال</td>
                            <td><?php echo number_format($item['total'], 2); ?> ريال</td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            
            <hr>
            
            <div class="total-summary">
                <div class="d-flex justify-content-between mb-2">
                    <span>مجموع العناصر:</span>
                    <strong><?php echo number_format($subtotal, 2); ?> ريال</strong>
                </div>
                <div class="d-flex justify-content-between mb-2">
                    <span>رسوم التوصيل:</span>
                    <strong><?php echo number_format($delivery_fee, 2); ?> ريال</strong>
                </div>
                <?php if ($discount_amount > 0): ?>
                <div class="d-flex justify-content-between mb-2 text-warning">
                    <span>التخفيض:</span>
                    <strong>-<?php echo number_format($discount_amount, 2); ?> ريال</strong>
                </div>
                <?php endif; ?>
                <hr class="my-2" style="border-color:rgba(255,255,255,0.3);">
                <div class="d-flex justify-content-between">
                    <span class="fs-5 fw-bold">الإجمالي الكلي:</span>
                    <span class="fs-4 fw-bold"><?php echo number_format($final_total, 2); ?> ريال</span>
                </div>
            </div>
        </div>
        
        <!-- Actions -->
        <?php if ($order_details['status'] != 'delivered'): ?>
        <div class="main-card">
            <h5 class="mb-3"><i class="bi bi-gear"></i> تحديث حالة الطلب</h5>
            <div class="d-flex gap-2 flex-wrap">
                <?php if ($order_details['status'] == 'pending'): ?>
                    <form method="POST" action="update_order.php" class="flex-grow-1" onsubmit="return confirmAction('قبول الطلب')">
                        <input type="hidden" name="order_id" value="<?php echo $order_details['id']; ?>">
                        <input type="hidden" name="status" value="accepted">
                        <button type="submit" class="btn btn-success w-100">
                            <i class="bi bi-check-circle"></i> قبول الطلب
                        </button>
                    </form>
                <?php elseif ($order_details['status'] == 'accepted'): ?>
                    <form method="POST" action="update_order.php" class="flex-grow-1" onsubmit="return confirmAction('بدء التوصيل')">
                        <input type="hidden" name="order_id" value="<?php echo $order_details['id']; ?>">
                        <input type="hidden" name="status" value="on_the_way">
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="bi bi-truck"></i> بدأ التوصيل
                        </button>
                    </form>
                <?php elseif ($order_details['status'] == 'on_the_way'): ?>
                    <form method="POST" action="update_order.php" class="flex-grow-1" onsubmit="return confirmAction('تأكيد التسليم')">
                        <input type="hidden" name="order_id" value="<?php echo $order_details['id']; ?>">
                        <input type="hidden" name="status" value="delivered">
                        <button type="submit" class="btn btn-success w-100">
                            <i class="bi bi-check2-circle"></i> تأكيد التسليم
                        </button>
                    </form>
                <?php endif; ?>
                
                <a href="orders.php" class="btn btn-outline-secondary flex-grow-1">
                    <i class="bi bi-arrow-return-left"></i> العودة
                </a>
            </div>
        </div>
        <?php else: ?>
        <div class="main-card">
            <div class="alert alert-success text-center">
                <i class="bi bi-check-circle-fill fs-3"></i>
                <h5 class="mt-2">تم تسليم الطلب بنجاح!</h5>
                <p class="mb-0">تم تسليم الطلب للعميل</p>
            </div>
        </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() {
            const coordsText = document.getElementById('coordinatesText');
            if(coordsText) {
                let coords = coordsText.innerText.replace('📍 ', '');
                navigator.clipboard.writeText(coords).then(() => {
                    showToast('✅ تم نسخ الإحداثيات: ' + coords, 'success');
                    const btn = document.querySelector('.copy-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>