<?php
/**
 * orders_new.php - صفحة الطلبات بتصميم عصري (بدون قائمة جانبية)
 * @version 2.0.0
 */

session_start();
require_once 'config.php';

// التحقق من تسجيل الدخول
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit();
}

$admin_name = $_SESSION['admin_name'] ?? 'Admin';

// ============================================
// معالجة تحديث الطلب
// ============================================

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_order'])) {
    $id = (int)$_POST['id'];
    $status = $conn->real_escape_string($_POST['status']);
    $captain_id = !empty($_POST['captain_id']) ? (int)$_POST['captain_id'] : 'NULL';
    
    $sql = "UPDATE orders SET status='$status', captain_id=" . ($captain_id !== 'NULL' ? $captain_id : "NULL") . " WHERE id=$id";
    
    if ($conn->query($sql)) {
        $_SESSION['success'] = 'تم تحديث الطلب بنجاح';
    } else {
        $_SESSION['error'] = 'حدث خطأ في تحديث الطلب';
    }
    
    header('Location: new_orders.php' . (isset($_GET['view']) ? '?view=' . $_GET['view'] : ''));
    exit();
}

// ============================================
// API للتحديث التلقائي
// ============================================

if (isset($_GET['api'])) {
    header('Content-Type: application/json');
    
    if ($_GET['api'] == 'get_orders') {
        $last_id = isset($_GET['last_id']) ? (int)$_GET['last_id'] : 0;
        
        $query = "
            SELECT o.*, 
                   c.name as customer_name, 
                   c.phone as customer_phone,
                   cp.name as captain_name
            FROM orders o 
            JOIN customers c ON o.customer_id = c.id 
            LEFT JOIN captains cp ON o.captain_id = cp.id
            WHERE o.id > $last_id
            ORDER BY o.id DESC
            LIMIT 20
        ";
        
        $result = $conn->query($query);
        $orders = [];
        $max_id = 0;
        
        while ($row = $result->fetch_assoc()) {
            $orders[] = [
                'id' => $row['id'],
                'customer_name' => $row['customer_name'],
                'customer_phone' => $row['customer_phone'],
                'total' => number_format($row['total'], 2),
                'status' => $row['status'],
                'status_text' => [
                    'pending' => 'قيد الانتظار',
                    'accepted' => 'تم القبول',
                    'on_the_way' => 'في الطريق',
                    'delivered' => 'تم التوصيل'
                ][$row['status']],
                'status_color' => [
                    'pending' => '#f59e0b',
                    'accepted' => '#3b82f6',
                    'on_the_way' => '#8b5cf6',
                    'delivered' => '#10b981'
                ][$row['status']],
                'captain_name' => $row['captain_name'] ?: 'غير معين',
                'created_at' => date('Y-m-d H:i', strtotime($row['created_at']))
            ];
            
            if ($row['id'] > $max_id) {
                $max_id = $row['id'];
            }
        }
        
        echo json_encode([
            'success' => true,
            'orders' => $orders,
            'max_id' => $max_id,
            'count' => count($orders)
        ]);
        exit();
    }
    
    if ($_GET['api'] == 'get_stats') {
        $stats = $conn->query("
            SELECT 
                COUNT(*) as total,
                COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending,
                COUNT(CASE WHEN status = 'accepted' THEN 1 END) as accepted,
                COUNT(CASE WHEN status = 'on_the_way' THEN 1 END) as on_the_way,
                COUNT(CASE WHEN status = 'delivered' THEN 1 END) as delivered
            FROM orders
        ")->fetch_assoc();
        
        echo json_encode([
            'success' => true,
            'stats' => $stats
        ]);
        exit();
    }
}

// ============================================
// جلب البيانات للعرض
// ============================================

// إحصائيات
$stats = $conn->query("
    SELECT 
        COUNT(*) as total,
        COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending,
        COUNT(CASE WHEN status = 'accepted' THEN 1 END) as accepted,
        COUNT(CASE WHEN status = 'on_the_way' THEN 1 END) as on_the_way,
        COUNT(CASE WHEN status = 'delivered' THEN 1 END) as delivered
    FROM orders
")->fetch_assoc();

// آخر 50 طلب
$orders = $conn->query("
    SELECT o.*, 
           c.name as customer_name, 
           c.phone as customer_phone,
           cp.name as captain_name
    FROM orders o 
    JOIN customers c ON o.customer_id = c.id 
    LEFT JOIN captains cp ON o.captain_id = cp.id
    ORDER BY o.id DESC
    LIMIT 50
");

$orders_list = [];
while ($row = $orders->fetch_assoc()) {
    $orders_list[] = $row;
}

$max_order_id = !empty($orders_list) ? $orders_list[0]['id'] : 0;

// عرض تفاصيل طلب محدد
$order_details = null;
$order_items = null;

if (isset($_GET['view'])) {
    $order_id = (int)$_GET['view'];
    
    $order_details = $conn->query("
        SELECT o.*, c.name as customer_name, c.phone as customer_phone, 
               c.address as customer_address, cp.name as captain_name,
               cp.phone as captain_phone
        FROM orders o 
        JOIN customers c ON o.customer_id = c.id 
        LEFT JOIN captains cp ON o.captain_id = cp.id
        WHERE o.id = $order_id
    ")->fetch_assoc();
    
    if ($order_details) {
        $order_items = $conn->query("
            SELECT oi.*, m.name as meal_name, mp.name as portion_name
            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
        ");
    }
}

// جلب الكباتن للقوائم المنسدلة
$captains = $conn->query("SELECT id, name FROM captains WHERE status='active' ORDER BY name");
$captains_list = [];
while ($cap = $captains->fetch_assoc()) {
    $captains_list[] = $cap;
}

// رسائل النجاح والخطأ
$success_message = $_SESSION['success'] ?? '';
$error_message = $_SESSION['error'] ?? '';
unset($_SESSION['success'], $_SESSION['error']);
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>الطلبات - Max Dashboard</title>
    
    <!-- Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    
    <!-- Icons -->
    <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: 'Inter', sans-serif;
            background: #f5f7fb;
            color: #1e293b;
            line-height: 1.5;
        }
        
        /* App Bar - تصميم بسيط */
        .app-bar {
            background: white;
            padding: 1rem 2rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.05);
            display: flex;
            align-items: center;
            justify-content: space-between;
            position: sticky;
            top: 0;
            z-index: 10;
        }
        
        .app-title {
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }
        
        .app-title i {
            font-size: 1.5rem;
            color: #F57C00;
            background: #fff3e0;
            padding: 0.5rem;
            border-radius: 12px;
        }
        
        .app-title h1 {
            font-size: 1.25rem;
            font-weight: 600;
        }
        
        .app-title span {
            color: #64748b;
            font-size: 0.875rem;
            font-weight: 400;
            margin-right: 0.5rem;
        }
        
        .user-menu {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            background: #f8fafc;
            padding: 0.5rem 1rem;
            border-radius: 30px;
        }
        
        .user-menu i {
            color: #F57C00;
            font-size: 1.25rem;
        }
        
        .user-menu span {
            font-weight: 500;
            font-size: 0.9rem;
        }
        
        /* رسائل التنبيه */
        .alert {
            margin: 1rem 2rem;
            padding: 1rem 1.5rem;
            border-radius: 16px;
            display: flex;
            align-items: center;
            gap: 0.75rem;
            animation: slideDown 0.3s;
        }
        
        .alert-success {
            background: #d1fae5;
            color: #065f46;
            border: 1px solid #a7f3d0;
        }
        
        .alert-error {
            background: #fee2e2;
            color: #991b1b;
            border: 1px solid #fecaca;
        }
        
        @keyframes slideDown {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        /* Stats Cards - تصميم حديث */
        .stats-container {
            display: grid;
            grid-template-columns: repeat(5, 1fr);
            gap: 1rem;
            padding: 2rem 2rem 1rem;
        }
        
        .stat-card {
            background: white;
            border-radius: 20px;
            padding: 1.25rem;
            box-shadow: 0 4px 20px rgba(0,0,0,0.02);
            border: 1px solid rgba(0,0,0,0.02);
            transition: transform 0.2s;
        }
        
        .stat-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 30px rgba(0,0,0,0.05);
        }
        
        .stat-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 0.75rem;
        }
        
        .stat-header span {
            color: #64748b;
            font-size: 0.8rem;
            font-weight: 500;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .stat-header i {
            font-size: 1.2rem;
            opacity: 0.7;
        }
        
        .stat-number {
            font-size: 2rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.25rem;
        }
        
        .stat-trend {
            font-size: 0.75rem;
            color: #10b981;
        }
        
        /* Auto Refresh Bar */
        .refresh-bar {
            padding: 0 2rem 1.5rem;
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-wrap: wrap;
            gap: 1rem;
        }
        
        .refresh-info {
            display: flex;
            align-items: center;
            gap: 1rem;
            flex-wrap: wrap;
        }
        
        .refresh-indicator {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            background: #f1f5f9;
            padding: 0.5rem 1rem;
            border-radius: 30px;
        }
        
        .pulse {
            width: 8px;
            height: 8px;
            background: #10b981;
            border-radius: 50%;
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0% { transform: scale(1); opacity: 1; }
            50% { transform: scale(1.5); opacity: 0.5; }
            100% { transform: scale(1); opacity: 1; }
        }
        
        .refresh-toggle {
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .switch {
            position: relative;
            display: inline-block;
            width: 44px;
            height: 24px;
        }
        
        .switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }
        
        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #e2e8f0;
            transition: .2s;
            border-radius: 24px;
        }
        
        .slider:before {
            position: absolute;
            content: "";
            height: 20px;
            width: 20px;
            left: 2px;
            bottom: 2px;
            background-color: white;
            transition: .2s;
            border-radius: 50%;
        }
        
        input:checked + .slider {
            background-color: #F57C00;
        }
        
        input:checked + .slider:before {
            transform: translateX(20px);
        }
        
        /* رسالة جاري البحث */
        .searching-message {
            background: rgba(245, 124, 0, 0.1);
            border: 1px solid #F57C00;
            color: #F57C00;
            padding: 0.75rem 1.5rem;
            border-radius: 30px;
            display: none;
            align-items: center;
            gap: 0.75rem;
            font-size: 0.9rem;
            animation: fadeIn 0.3s;
        }
        
        .searching-message.show {
            display: flex;
        }
        
        .searching-message i {
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }
        
        .new-orders-badge {
            background: #F57C00;
            color: white;
            padding: 0.5rem 1.5rem;
            border-radius: 30px;
            font-size: 0.9rem;
            cursor: pointer;
            display: none;
            box-shadow: 0 4px 15px rgba(245,124,0,0.3);
            animation: bounce 1s;
        }
        
        .new-orders-badge.show {
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        @keyframes bounce {
            0%, 100% { transform: translateY(0); }
            50% { transform: translateY(-5px); }
        }
        
        /* Orders Grid - تصميم بطاقات مختلف */
        .orders-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
            gap: 1rem;
            padding: 0 2rem 2rem;
        }
        
        .order-card {
            background: white;
            border-radius: 24px;
            padding: 1.25rem;
            box-shadow: 0 4px 20px rgba(0,0,0,0.02);
            border: 1px solid rgba(0,0,0,0.02);
            transition: all 0.2s;
            position: relative;
            overflow: hidden;
        }
        
        .order-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 30px rgba(0,0,0,0.05);
        }
        
        .order-card.new {
            animation: slideIn 0.3s;
        }
        
        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .order-status-bar {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
        }
        
        .status-pending { background: #f59e0b; }
        .status-accepted { background: #3b82f6; }
        .status-on_the_way { background: #8b5cf6; }
        .status-delivered { background: #10b981; }
        
        .order-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1rem;
        }
        
        .order-id {
            font-weight: 700;
            color: #F57C00;
            background: #fff3e0;
            padding: 0.25rem 0.75rem;
            border-radius: 30px;
            font-size: 0.8rem;
        }
        
        .order-time {
            color: #94a3b8;
            font-size: 0.75rem;
        }
        
        .customer-info {
            margin-bottom: 1rem;
        }
        
        .customer-name {
            font-weight: 600;
            font-size: 1.1rem;
            margin-bottom: 0.25rem;
        }
        
        .customer-phone {
            color: #64748b;
            font-size: 0.9rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .order-details {
            background: #f8fafc;
            border-radius: 16px;
            padding: 1rem;
            margin: 1rem 0;
        }
        
        .detail-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 0.5rem;
        }
        
        .detail-row:last-child {
            margin-bottom: 0;
        }
        
        .detail-label {
            color: #64748b;
            font-size: 0.85rem;
        }
        
        .detail-value {
            font-weight: 600;
        }
        
        .captain-info {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            color: #64748b;
            font-size: 0.85rem;
            margin-top: 0.5rem;
        }
        
        .order-actions {
            display: flex;
            gap: 0.5rem;
            margin-top: 1rem;
        }
        
        .btn {
            flex: 1;
            padding: 0.6rem;
            border: none;
            border-radius: 12px;
            font-weight: 500;
            font-size: 0.85rem;
            cursor: pointer;
            transition: 0.2s;
            text-decoration: none;
            text-align: center;
        }
        
        .btn-primary {
            background: #F57C00;
            color: white;
        }
        
        .btn-primary:hover {
            background: #E65100;
        }
        
        .btn-outline {
            background: white;
            border: 1px solid #e2e8f0;
            color: #1e293b;
        }
        
        .btn-outline:hover {
            background: #f8fafc;
        }
        
        /* Detail View */
        .back-link {
            margin: 1rem 2rem;
        }
        
        .back-link a {
            color: #64748b;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            transition: color 0.2s;
        }
        
        .back-link a:hover {
            color: #F57C00;
        }
        
        .order-detail-view {
            padding: 0 2rem 2rem;
        }
        
        .detail-header {
            background: white;
            border-radius: 24px;
            padding: 2rem;
            margin-bottom: 1rem;
            border: 1px solid rgba(0,0,0,0.02);
        }
        
        .detail-grid {
            display: grid;
            grid-template-columns: 2fr 1fr;
            gap: 1rem;
        }
        
        .detail-section {
            background: white;
            border-radius: 24px;
            padding: 1.5rem;
            border: 1px solid rgba(0,0,0,0.02);
        }
        
        .section-title {
            font-weight: 600;
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
            color: #F57C00;
        }
        
        .product-item {
            display: flex;
            justify-content: space-between;
            padding: 0.75rem 0;
            border-bottom: 1px solid #f1f5f9;
        }
        
        .product-item:last-child {
            border-bottom: none;
        }
        
        .product-name {
            font-weight: 500;
        }
        
        .product-quantity {
            color: #64748b;
            font-size: 0.85rem;
        }
        
        .product-price {
            font-weight: 600;
        }
        
        .totals {
            margin-top: 1rem;
            padding-top: 1rem;
            border-top: 2px solid #f1f5f9;
        }
        
        .total-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 0.5rem;
        }
        
        .grand-total {
            font-size: 1.2rem;
            font-weight: 700;
            color: #F57C00;
            margin-top: 0.5rem;
            padding-top: 0.5rem;
            border-top: 2px solid #f1f5f9;
        }
        
        .info-item {
            margin-bottom: 1rem;
        }
        
        .info-label {
            color: #64748b;
            font-size: 0.85rem;
            margin-bottom: 0.25rem;
        }
        
        .info-value {
            font-weight: 500;
        }
        
        .form-group {
            margin-bottom: 1rem;
        }
        
        .form-label {
            display: block;
            color: #64748b;
            font-size: 0.85rem;
            margin-bottom: 0.5rem;
        }
        
        .form-select {
            width: 100%;
            padding: 0.75rem;
            border: 1px solid #e2e8f0;
            border-radius: 12px;
            background: white;
            font-family: 'Inter', sans-serif;
            font-size: 0.9rem;
        }
        
        .form-select:focus {
            outline: none;
            border-color: #F57C00;
        }
        
        /* Responsive */
        @media (max-width: 1024px) {
            .stats-container {
                grid-template-columns: repeat(3, 1fr);
            }
        }
        
        @media (max-width: 768px) {
            .app-bar {
                padding: 1rem;
                flex-direction: column;
                align-items: flex-start;
                gap: 1rem;
            }
            
            .stats-container {
                grid-template-columns: repeat(2, 1fr);
                padding: 1rem;
                gap: 0.5rem;
            }
            
            .refresh-bar {
                flex-direction: column;
                align-items: flex-start;
                padding: 0 1rem 1rem;
            }
            
            .refresh-info {
                width: 100%;
                justify-content: space-between;
            }
            
            .orders-grid {
                grid-template-columns: 1fr;
                padding: 0 1rem 1rem;
            }
            
            .detail-grid {
                grid-template-columns: 1fr;
            }
            
            .order-detail-view {
                padding: 0 1rem 1rem;
            }
            
            .back-link {
                margin: 1rem;
            }
        }
        
        @media (max-width: 480px) {
            .stats-container {
                grid-template-columns: 1fr;
            }
            
            .stat-card {
                padding: 1rem;
            }
            
            .stat-number {
                font-size: 1.5rem;
            }
        }
    </style>
</head>
<body>
    <!-- App Bar بسيط -->
    <div class="app-bar">
        <div class="app-title">
            <i class="bi bi-cart"></i>
            <h1>الطلبات <span>آخر 50 طلب</span></h1>
        </div>
        <div class="user-menu">
            <i class="bi bi-person-circle"></i>
            <span><?php echo htmlspecialchars($admin_name); ?></span>
        </div>
    </div>

    <!-- رسائل التنبيه -->
    <?php if ($success_message): ?>
    <div class="alert alert-success">
        <i class="bi bi-check-circle-fill"></i>
        <?php echo htmlspecialchars($success_message); ?>
    </div>
    <?php endif; ?>
    
    <?php if ($error_message): ?>
    <div class="alert alert-error">
        <i class="bi bi-exclamation-triangle-fill"></i>
        <?php echo htmlspecialchars($error_message); ?>
    </div>
    <?php endif; ?>

    <?php if (isset($_GET['view']) && $order_details): ?>
    <!-- ===== عرض تفاصيل الطلب ===== -->
    <div class="back-link">
        <a href="new_orders.php">
            <i class="bi bi-arrow-right"></i> عودة للقائمة
        </a>
    </div>
    
    <div class="order-detail-view">
        <div class="detail-header">
            <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 1rem;">
                <h2 style="font-size: 1.5rem;">طلب #<?php echo $order_details['id']; ?></h2>
                <span class="order-id" style="font-size: 1rem; padding: 0.5rem 1rem;">
                    <?php 
                    $status_text = [
                        'pending' => 'قيد الانتظار',
                        'accepted' => 'تم القبول',
                        'on_the_way' => 'في الطريق',
                        'delivered' => 'تم التوصيل'
                    ][$order_details['status']];
                    echo $status_text;
                    ?>
                </span>
            </div>
        </div>
        
        <div class="detail-grid">
            <!-- المنتجات -->
            <div class="detail-section">
                <div class="section-title">
                    <i class="bi bi-receipt"></i>
                    المنتجات
                </div>
                <?php 
                $subtotal = 0;
                if ($order_items && $order_items->num_rows > 0): 
                    while ($item = $order_items->fetch_assoc()): 
                        $total = $item['price'] * $item['quantity'];
                        $subtotal += $total;
                ?>
                <div class="product-item">
                    <div>
                        <div class="product-name"><?php echo htmlspecialchars($item['meal_name']); ?></div>
                        <?php if ($item['portion_name']): ?>
                            <div class="product-quantity"><?php echo htmlspecialchars($item['portion_name']); ?></div>
                        <?php endif; ?>
                    </div>
                    <div style="text-align: left;">
                        <div class="product-price"><?php echo number_format($total, 2); ?> ريال</div>
                        <div class="product-quantity">الكمية: <?php echo $item['quantity']; ?></div>
                    </div>
                </div>
                <?php 
                    endwhile; 
                endif; 
                ?>
                
                <div class="totals">
                    <div class="total-row">
                        <span>المجموع الفرعي</span>
                        <span><?php echo number_format($subtotal, 2); ?> ريال</span>
                    </div>
                    <div class="total-row">
                        <span>رسوم التوصيل</span>
                        <span><?php echo number_format($order_details['delivery_fee'] ?? 0, 2); ?> ريال</span>
                    </div>
                    <?php if ($order_details['discount_amount'] > 0): ?>
                    <div class="total-row" style="color: #10b981;">
                        <span>التخفيض</span>
                        <span>-<?php echo number_format($order_details['discount_amount'], 2); ?> ريال</span>
                    </div>
                    <?php endif; ?>
                    <div class="grand-total">
                        <span>الإجمالي</span>
                        <span><?php echo number_format($order_details['total'], 2); ?> ريال</span>
                    </div>
                </div>
            </div>
            
            <!-- معلومات العميل والتوصيل -->
            <div>
                <div class="detail-section" style="margin-bottom: 1rem;">
                    <div class="section-title">
                        <i class="bi bi-person"></i>
                        معلومات العميل
                    </div>
                    <div class="info-item">
                        <div class="info-label">الاسم</div>
                        <div class="info-value"><?php echo htmlspecialchars($order_details['customer_name']); ?></div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">رقم الهاتف</div>
                        <div class="info-value">
                            <a href="tel:<?php echo $order_details['customer_phone']; ?>" style="color: #F57C00; text-decoration: none;">
                                <?php echo htmlspecialchars($order_details['customer_phone']); ?>
                            </a>
                        </div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">العنوان</div>
                        <div class="info-value"><?php echo htmlspecialchars($order_details['customer_address'] ?? 'لا يوجد عنوان'); ?></div>
                    </div>
                </div>
                
                <div class="detail-section" style="margin-bottom: 1rem;">
                    <div class="section-title">
                        <i class="bi bi-truck"></i>
                        معلومات التوصيل
                    </div>
                    <div class="info-item">
                        <div class="info-label">الحالة</div>
                        <div class="info-value">
                            <span class="order-id" style="background: <?php 
                                echo $order_details['status'] == 'pending' ? '#fef3c7' : 
                                    ($order_details['status'] == 'accepted' ? '#dbeafe' : 
                                    ($order_details['status'] == 'on_the_way' ? '#ede9fe' : '#d1fae5')); 
                            ?>; color: <?php 
                                echo $order_details['status'] == 'pending' ? '#92400e' : 
                                    ($order_details['status'] == 'accepted' ? '#1e40af' : 
                                    ($order_details['status'] == 'on_the_way' ? '#5b21b6' : '#065f46')); 
                            ?>;">
                                <?php echo $status_text; ?>
                            </span>
                        </div>
                    </div>
                    <?php if ($order_details['captain_name']): ?>
                    <div class="info-item">
                        <div class="info-label">الكابتن</div>
                        <div class="info-value"><?php echo htmlspecialchars($order_details['captain_name']); ?></div>
                    </div>
                    <?php endif; ?>
                    <div class="info-item">
                        <div class="info-label">وقت الطلب</div>
                        <div class="info-value"><?php echo date('Y-m-d H:i', strtotime($order_details['created_at'])); ?></div>
                    </div>
                </div>
                
                <!-- تحديث الطلب -->
                <div class="detail-section">
                    <div class="section-title">
                        <i class="bi bi-pencil"></i>
                        تحديث الطلب
                    </div>
                    <form method="POST">
                        <input type="hidden" name="id" value="<?php echo $order_details['id']; ?>">
                        
                        <div class="form-group">
                            <label class="form-label">حالة الطلب</label>
                            <select name="status" class="form-select">
                                <option value="pending" <?php echo $order_details['status'] == 'pending' ? 'selected' : ''; ?>>قيد الانتظار</option>
                                <option value="accepted" <?php echo $order_details['status'] == 'accepted' ? 'selected' : ''; ?>>تم القبول</option>
                                <option value="on_the_way" <?php echo $order_details['status'] == 'on_the_way' ? 'selected' : ''; ?>>في الطريق</option>
                                <option value="delivered" <?php echo $order_details['status'] == 'delivered' ? 'selected' : ''; ?>>تم التوصيل</option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">تعيين كابتن</label>
                            <select name="captain_id" class="form-select">
                                <option value="">بدون كابتن</option>
                                <?php foreach ($captains_list as $cap): ?>
                                <option value="<?php echo $cap['id']; ?>" <?php echo $order_details['captain_id'] == $cap['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($cap['name']); ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <button type="submit" name="update_order" class="btn btn-primary" style="width: 100%; padding: 0.75rem;">
                            تحديث الطلب
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>
    
    <?php else: ?>
    <!-- ===== عرض قائمة الطلبات ===== -->
    
    <!-- إحصائيات -->
    <div class="stats-container">
        <div class="stat-card">
            <div class="stat-header">
                <span>إجمالي الطلبات</span>
                <i class="bi bi-cart" style="color: #F57C00;"></i>
            </div>
            <div class="stat-number" id="stat-total"><?php echo $stats['total']; ?></div>
            <div class="stat-trend">جميع الطلبات</div>
        </div>
        
        <div class="stat-card">
            <div class="stat-header">
                <span>قيد الانتظار</span>
                <i class="bi bi-hourglass" style="color: #f59e0b;"></i>
            </div>
            <div class="stat-number" id="stat-pending"><?php echo $stats['pending']; ?></div>
        </div>
        
        <div class="stat-card">
            <div class="stat-header">
                <span>تم القبول</span>
                <i class="bi bi-check-circle" style="color: #3b82f6;"></i>
            </div>
            <div class="stat-number" id="stat-accepted"><?php echo $stats['accepted']; ?></div>
        </div>
        
        <div class="stat-card">
            <div class="stat-header">
                <span>في الطريق</span>
                <i class="bi bi-truck" style="color: #8b5cf6;"></i>
            </div>
            <div class="stat-number" id="stat-onway"><?php echo $stats['on_the_way']; ?></div>
        </div>
        
        <div class="stat-card">
            <div class="stat-header">
                <span>تم التوصيل</span>
                <i class="bi bi-check-all" style="color: #10b981;"></i>
            </div>
            <div class="stat-number" id="stat-delivered"><?php echo $stats['delivered']; ?></div>
        </div>
    </div>
    
    <!-- شريط التحديث التلقائي -->
    <div class="refresh-bar">
        <div class="refresh-info">
            <div class="refresh-indicator">
                <span class="pulse" id="refreshIndicator"></span>
                <span id="lastUpdate">الآن</span>
            </div>
            <div class="refresh-toggle">
                <span style="font-size: 0.85rem; color: #64748b;">تحديث تلقائي</span>
                <label class="switch">
                    <input type="checkbox" id="autoRefreshToggle" checked>
                    <span class="slider"></span>
                </label>
            </div>
            
            <!-- رسالة جاري البحث -->
            <div class="searching-message" id="searchingMessage">
                <i class="bi bi-arrow-repeat"></i>
                <span>جاري البحث عن الطلبات الجديدة...</span>
            </div>
        </div>
        
        <div class="new-orders-badge" id="newOrdersBadge" onclick="loadNewOrders()">
            <i class="bi bi-arrow-down-circle"></i>
            <span id="newOrdersCount">0</span> طلبات جديدة
        </div>
    </div>
    
    <!-- بطاقات الطلبات -->
    <div class="orders-grid" id="ordersGrid">
        <?php if (empty($orders_list)): ?>
        <div style="grid-column: 1/-1; text-align: center; padding: 3rem; background: white; border-radius: 24px;">
            <i class="bi bi-inbox" style="font-size: 3rem; color: #cbd5e1;"></i>
            <h3 style="margin-top: 1rem; color: #64748b;">لا توجد طلبات</h3>
        </div>
        <?php else: ?>
            <?php foreach ($orders_list as $order): 
                $status_colors = [
                    'pending' => '#f59e0b',
                    'accepted' => '#3b82f6',
                    'on_the_way' => '#8b5cf6',
                    'delivered' => '#10b981'
                ];
                $status_text = [
                    'pending' => 'قيد الانتظار',
                    'accepted' => 'تم القبول',
                    'on_the_way' => 'في الطريق',
                    'delivered' => 'تم التوصيل'
                ];
            ?>
            <div class="order-card" data-order-id="<?php echo $order['id']; ?>">
                <div class="order-status-bar status-<?php echo $order['status']; ?>"></div>
                
                <div class="order-header">
                    <span class="order-id">#<?php echo $order['id']; ?></span>
                    <span class="order-time"><?php echo date('H:i', strtotime($order['created_at'])); ?></span>
                </div>
                
                <div class="customer-info">
                    <div class="customer-name"><?php echo htmlspecialchars($order['customer_name']); ?></div>
                    <div class="customer-phone">
                        <i class="bi bi-telephone"></i>
                        <?php echo htmlspecialchars($order['customer_phone']); ?>
                    </div>
                </div>
                
                <div class="order-details">
                    <div class="detail-row">
                        <span class="detail-label">المبلغ</span>
                        <span class="detail-value"><?php echo number_format($order['total'], 2); ?> ريال</span>
                    </div>
                    <div class="detail-row">
                        <span class="detail-label">الحالة</span>
                        <span class="detail-value" style="color: <?php echo $status_colors[$order['status']]; ?>;">
                            <?php echo $status_text[$order['status']]; ?>
                        </span>
                    </div>
                </div>
                
                <div class="captain-info">
                    <i class="bi bi-person-badge"></i>
                    <?php echo htmlspecialchars($order['captain_name'] ?: 'غير معين'); ?>
                </div>
                
                <div class="order-actions">
                    <a href="?view=<?php echo $order['id']; ?>" class="btn btn-primary">عرض التفاصيل</a>
                </div>
            </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
    <?php endif; ?>
    
    <script>
    // ============================================
    // نظام التحديث التلقائي مع رسالة البحث
    // ============================================
    
    let autoRefreshEnabled = true;
    let refreshInterval;
    let lastOrderId = <?php echo $max_order_id; ?>;
    let isSearching = false;
    
    document.addEventListener('DOMContentLoaded', function() {
        startAutoRefresh();
        setupEventListeners();
        updateLastUpdateTime();
        setInterval(updateLastUpdateTime, 60000);
    });
    
    function startAutoRefresh() {
        if (refreshInterval) clearInterval(refreshInterval);
        // تحديث كل 20 ثانية (20000 مللي ثانية)
        refreshInterval = setInterval(checkForNewOrders, 20000);
    }
    
    function stopAutoRefresh() {
        if (refreshInterval) {
            clearInterval(refreshInterval);
            refreshInterval = null;
        }
    }
    
    function showSearchingMessage() {
        isSearching = true;
        const message = document.getElementById('searchingMessage');
        if (message) {
            message.classList.add('show');
        }
    }
    
    function hideSearchingMessage() {
        isSearching = false;
        const message = document.getElementById('searchingMessage');
        if (message) {
            message.classList.remove('show');
        }
    }
    
    function checkForNewOrders() {
        if (!autoRefreshEnabled || isSearching) return;
        
        // إظهار رسالة جاري البحث
        showSearchingMessage();
        
        fetch('orders_new.php?api=get_orders&last_id=' + lastOrderId)
            .then(response => response.json())
            .then(data => {
                // إخفاء رسالة البحث
                hideSearchingMessage();
                
                if (data.success) {
                    if (data.count > 0) {
                        showNewOrdersNotification(data.count);
                        if (data.max_id > lastOrderId) {
                            lastOrderId = data.max_id;
                        }
                    }
                    // تحديث وقت آخر تحديث
                    updateLastUpdateTime();
                }
            })
            .catch(error => {
                console.error('Error:', error);
                hideSearchingMessage();
            });
    }
    
    function loadNewOrders() {
        if (isSearching) return;
        
        showSearchingMessage();
        
        fetch('orders_new.php?api=get_orders')
            .then(response => response.json())
            .then(data => {
                hideSearchingMessage();
                
                if (data.success && data.orders.length > 0) {
                    updateOrdersDisplay(data.orders);
                    hideNewOrdersNotification();
                    updateStats();
                    if (data.max_id > lastOrderId) {
                        lastOrderId = data.max_id;
                    }
                }
            })
            .catch(error => {
                console.error('Error:', error);
                hideSearchingMessage();
            });
    }
    
    function updateOrdersDisplay(newOrders) {
        const grid = document.getElementById('ordersGrid');
        
        // إزالة رسالة "لا توجد طلبات" إذا كانت موجودة
        const emptyMessage = grid.querySelector('div[style*="grid-column: 1/-1"]');
        if (emptyMessage) {
            emptyMessage.remove();
        }
        
        newOrders.forEach(order => {
            const card = createOrderCard(order);
            grid.insertAdjacentHTML('afterbegin', card);
        });
    }
    
    function createOrderCard(order) {
        const statusColors = {
            'pending': '#f59e0b',
            'accepted': '#3b82f6',
            'on_the_way': '#8b5cf6',
            'delivered': '#10b981'
        };
        
        return `
            <div class="order-card new" data-order-id="${order.id}">
                <div class="order-status-bar status-${order.status}"></div>
                <div class="order-header">
                    <span class="order-id">#${order.id}</span>
                    <span class="order-time">${order.created_at.split(' ')[1]}</span>
                </div>
                <div class="customer-info">
                    <div class="customer-name">${order.customer_name}</div>
                    <div class="customer-phone">
                        <i class="bi bi-telephone"></i> ${order.customer_phone}
                    </div>
                </div>
                <div class="order-details">
                    <div class="detail-row">
                        <span class="detail-label">المبلغ</span>
                        <span class="detail-value">${order.total} ريال</span>
                    </div>
                    <div class="detail-row">
                        <span class="detail-label">الحالة</span>
                        <span class="detail-value" style="color: ${order.status_color};">${order.status_text}</span>
                    </div>
                </div>
                <div class="captain-info">
                    <i class="bi bi-person-badge"></i> ${order.captain_name}
                </div>
                <div class="order-actions">
                    <a href="?view=${order.id}" class="btn btn-primary">عرض التفاصيل</a>
                </div>
            </div>
        `;
    }
    
    function updateStats() {
        fetch('orders_new.php?api=get_stats')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    document.getElementById('stat-total').textContent = data.stats.total;
                    document.getElementById('stat-pending').textContent = data.stats.pending;
                    document.getElementById('stat-accepted').textContent = data.stats.accepted;
                    document.getElementById('stat-onway').textContent = data.stats.on_the_way;
                    document.getElementById('stat-delivered').textContent = data.stats.delivered;
                }
            })
            .catch(error => console.error('Error:', error));
    }
    
    function showNewOrdersNotification(count) {
        const badge = document.getElementById('newOrdersBadge');
        const countSpan = document.getElementById('newOrdersCount');
        if (badge && countSpan) {
            countSpan.textContent = count;
            badge.classList.add('show');
        }
    }
    
    function hideNewOrdersNotification() {
        const badge = document.getElementById('newOrdersBadge');
        if (badge) {
            badge.classList.remove('show');
        }
    }
    
    function updateLastUpdateTime() {
        const now = new Date();
        const timeStr = now.toLocaleTimeString('ar-SA', { 
            hour: '2-digit', 
            minute: '2-digit',
            second: '2-digit'
        });
        document.getElementById('lastUpdate').textContent = 'آخر تحديث: ' + timeStr;
    }
    
    function setupEventListeners() {
        const toggle = document.getElementById('autoRefreshToggle');
        if (toggle) {
            toggle.addEventListener('change', function() {
                autoRefreshEnabled = this.checked;
                const indicator = document.getElementById('refreshIndicator');
                if (indicator) {
                    indicator.style.animation = autoRefreshEnabled ? 'pulse 2s infinite' : 'none';
                    indicator.style.opacity = autoRefreshEnabled ? '1' : '0.3';
                }
                if (autoRefreshEnabled) {
                    startAutoRefresh();
                } else {
                    stopAutoRefresh();
                }
            });
        }
    }
    </script>
</body>
</html>