<?php
include "session.php";
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if (!defined('BASE_URL')) {
}

header("Cache-Control: no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");

require_once __DIR__ . '/../db.php';

// ===== التحقق من وجود الأعمدة المطلوبة =====
try { $pdo->query("SELECT municipality FROM orders LIMIT 1"); }
catch (PDOException $e) { $pdo->exec("ALTER TABLE orders ADD COLUMN municipality VARCHAR(255) NULL AFTER address"); }

try { $pdo->query("SELECT delivery_price_modified FROM orders LIMIT 1"); }
catch (PDOException $e) { $pdo->exec("ALTER TABLE orders ADD COLUMN delivery_price_modified DECIMAL(10,2) NULL AFTER delivery_price_id"); }

try { $pdo->query("SELECT commune_id FROM orders LIMIT 1"); }
catch (PDOException $e) { $pdo->exec("ALTER TABLE orders ADD COLUMN commune_id INT NULL AFTER address, ADD INDEX (commune_id)"); }

try { $pdo->query("SELECT tracking_code FROM orders LIMIT 1"); }
catch (PDOException $e) { $pdo->exec("ALTER TABLE orders ADD COLUMN tracking_code VARCHAR(100) NULL"); }

try { $pdo->query("SELECT shipping_status FROM orders LIMIT 1"); }
catch (PDOException $e) { $pdo->exec("ALTER TABLE orders ADD COLUMN shipping_status VARCHAR(30) NULL"); }

try { $pdo->query("SELECT api_response FROM orders LIMIT 1"); }
catch (PDOException $e) { $pdo->exec("ALTER TABLE orders ADD COLUMN api_response TEXT NULL"); }

// ===== دالة Ecotrack API الجديدة (navexdelivery) =====
function ecotrack_create_parcel(string $token, array $order, string $commune = '', string $wilaya_name = ''): array
{
    $url = 'https://navexdelivery.ecotrack.dz/api/v1/create/order';

    // تحديد نوع التسليم: 1=للمنزل، 2=للمكتب
    $type_livraison = ($order['delivery_type'] === 'office') ? 2 : 1;

    // استخراج رقم الولاية كرقم صحيح
    $wilaya_code = str_pad((string)($order['wilaya_id'] ?? '01'), 2, '0', STR_PAD_LEFT);
    $wilaya_int  = (int)$wilaya_code;

    $payload = [
        'nom_client'  => $order['customer_name'],
        'telephone'   => $order['phone'],
        'adresse'     => $order['address'] ?: ($wilaya_name ?: 'غير محدد'),
        'code_wilaya' => $wilaya_int,
        'commune'     => $commune ?: ($order['municipality'] ?? ''),
        'montant'     => (string)(int)round(($order['total'] ?? 0)),
        'type'        => $type_livraison,
        'reference'   => 'NEO-' . $order['id'],
    ];

    // إضافة هاتف ثانوي إن وُجد
    if (!empty($order['phone2'])) {
        $payload['telephone2'] = $order['phone2'];
    }

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode($payload),
        CURLOPT_HTTPHEADER     => [
            'Content-Type: application/json',
            'Accept: application/json',
            'Authorization: Bearer ' . $token,   // ← Bearer وليس Token
        ],
        CURLOPT_TIMEOUT        => 20,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
    ]);

    $response  = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_err  = curl_error($ch);
    curl_close($ch);

    if ($curl_err) {
        return ['success' => false, 'tracking_code' => null, 'message' => 'خطأ اتصال: ' . $curl_err, 'raw' => null];
    }

    $result = json_decode($response, true);

    if (in_array($http_code, [200, 201])) {
        // محاولة استخراج رمز التتبع من الرد
        $tracking = $result['tracking']        ??
                    $result['reference']       ??
                    $result['id']              ??
                    $result['order_id']        ??
                    ('NEO-' . $order['id']);
        return [
            'success'       => true,
            'tracking_code' => (string)$tracking,
            'message'       => 'تم إرسال الطلب إلى Ecotrack بنجاح',
            'raw'           => $response,
        ];
    }

    $error_msg = 'خطأ Ecotrack ' . $http_code;
    if (!empty($result)) {
        $error_msg .= ': ' . (is_array($result) ? json_encode($result, JSON_UNESCAPED_UNICODE) : $result);
    }
    return ['success' => false, 'tracking_code' => null, 'message' => $error_msg, 'raw' => $response];
}

// ===== دوال مساعدة =====
function getDeliveryPrice($pdo, $order_id, $wilaya_id, $delivery_type, $delivery_company_id = null) {
    if (!$wilaya_id) return 0;
    $stmt = $pdo->prepare("SELECT delivery_price_modified FROM orders WHERE id = ?");
    $stmt->execute([$order_id]);
    $modifiedPrice = $stmt->fetchColumn();
    if ($modifiedPrice !== null) return floatval($modifiedPrice);
    $query = "SELECT price FROM delivery_prices WHERE wilaya_id = ? AND delivery_type = ?";
    $params = [$wilaya_id, $delivery_type];
    if ($delivery_company_id) { $query .= " AND delivery_company_id = ?"; $params[] = $delivery_company_id; }
    $query .= " LIMIT 1";
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $price = $stmt->fetchColumn();
    return $price ? floatval($price) : 0;
}

function getCommunesByWilaya($pdo, $wilaya_id) {
    $wilaya_code = str_pad($wilaya_id, 2, '0', STR_PAD_LEFT);
    $stmt = $pdo->prepare("SELECT id, commune_name_ascii as name, commune_name as arabic_name FROM algeria_cities WHERE wilaya_code = ? ORDER BY commune_name_ascii");
    $stmt->execute([$wilaya_code]);
    return $stmt->fetchAll();
}

function getCommuneName($pdo, $commune_id) {
    if (!$commune_id) return '--';
    $stmt = $pdo->prepare("SELECT commune_name_ascii FROM algeria_cities WHERE id = ?");
    $stmt->execute([$commune_id]);
    return $stmt->fetchColumn() ?: '--';
}

function getCommuneIdByName($pdo, $commune_name, $wilaya_id) {
    if (!$commune_name || !$wilaya_id) return null;
    $stmt = $pdo->prepare("SELECT id FROM algeria_cities WHERE wilaya_code = ? AND commune_name_ascii = ?");
    $wilaya_code = str_pad($wilaya_id, 2, '0', STR_PAD_LEFT);
    $stmt->execute([$wilaya_code, $commune_name]);
    $id = $stmt->fetchColumn();
    if ($id) return $id;
    $stmt = $pdo->prepare("SELECT id FROM algeria_cities WHERE wilaya_code = ? AND commune_name = ?");
    $stmt->execute([$wilaya_code, $commune_name]);
    return $stmt->fetchColumn();
}

function getProductAttributes($pdo, $product_id) {
    $stmt = $pdo->prepare("SELECT DISTINCT a.id, a.name, a.input_type, a.values_list FROM attributes a JOIN product_attributes pa ON a.id = pa.attribute_id WHERE pa.product_id = ? ORDER BY a.name");
    $stmt->execute([$product_id]);
    $attrs = $stmt->fetchAll();
    if (empty($attrs)) {
        $stmt = $pdo->prepare("SELECT DISTINCT a.id, a.name, a.input_type, a.values_list FROM attributes a JOIN variant_attributes va ON a.id = va.attribute_id JOIN product_variants pv ON va.variant_id = pv.id WHERE pv.product_id = ? ORDER BY a.name");
        $stmt->execute([$product_id]);
        $attrs = $stmt->fetchAll();
    }
    return $attrs;
}

// ===== دالة الإرسال لـ Ecotrack — تتحقق من الشركة أولاً =====
function sendOrderToEcotrack($pdo, $orderId) {
    $orderStmt = $pdo->prepare("
        SELECT o.*, w.name as wilaya_name, dc.api_token, dc.name as company_name
        FROM orders o
        LEFT JOIN wilayas w ON o.wilaya_id = w.id
        LEFT JOIN delivery_companies dc ON o.delivery_company_id = dc.id
        WHERE o.id = ?
    ");
    $orderStmt->execute([$orderId]);
    $orderData = $orderStmt->fetch();

    if (!$orderData) {
        return ['success' => false, 'message' => 'الطلب غير موجود'];
    }

    // إذا لم يكن للشركة توكن → لا ترسل، فقط سجّل الحالة
    if (empty($orderData['api_token'])) {
        return ['success' => false, 'message' => 'شركة التوصيل لا تدعم Ecotrack (لا يوجد رمز API)', 'no_token' => true];
    }

    $communeName = '';
    if ($orderData['commune_id']) {
        $communeName = getCommuneName($pdo, $orderData['commune_id']);
    } elseif (!empty($orderData['municipality'])) {
        $communeName = $orderData['municipality'];
    }

    // جلب أول منتج وحساب الإجمالي
    $itemStmt = $pdo->prepare("
        SELECT p.name as product_name, SUM(oi.quantity * oi.unit_price) as total
        FROM order_items oi
        LEFT JOIN product_variants pv ON oi.product_variant_id = pv.id
        LEFT JOIN products p ON pv.product_id = p.id
        WHERE oi.order_id = ?
        GROUP BY p.name LIMIT 1
    ");
    $itemStmt->execute([$orderId]);
    $itemData = $itemStmt->fetch();

    $orderData['product_name'] = $itemData['product_name'] ?? 'منتج';
    $orderData['total']        = $itemData['total'] ?? 0;

    // إضافة سعر التوصيل
    $delivPrice = getDeliveryPrice($pdo, $orderId, $orderData['wilaya_id'], $orderData['delivery_type'], $orderData['delivery_company_id']);
    $orderData['total'] += $delivPrice;

    $ecoResult = ecotrack_create_parcel($orderData['api_token'], $orderData, $communeName, $orderData['wilaya_name'] ?? '');

    if ($ecoResult['success']) {
        $pdo->prepare("UPDATE orders SET tracking_code = ?, shipping_status = 'shipped', api_response = ? WHERE id = ?")
            ->execute([$ecoResult['tracking_code'], $ecoResult['raw'], $orderId]);
    } else {
        $pdo->prepare("UPDATE orders SET api_response = ? WHERE id = ?")
            ->execute([$ecoResult['raw'], $orderId]);
    }

    return $ecoResult;
}

// ===== معالجة الإرسال الجماعي إلى Ecotrack =====
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_send_ecotrack'])) {
    $selectedIds = array_filter(array_map('intval', $_POST['selected_orders'] ?? []));
    if (!empty($selectedIds)) {
        $successCount = 0; $failCount = 0; $noTokenCount = 0; $failMessages = [];
        foreach ($selectedIds as $orderId) {
            $pdo->prepare("UPDATE orders SET status_id = 2, sent_date = NOW() WHERE id = ? AND status_id != 2")->execute([$orderId]);
            $result = sendOrderToEcotrack($pdo, $orderId);
            if ($result['success']) {
                $successCount++;
            } elseif (!empty($result['no_token'])) {
                $noTokenCount++;
            } else {
                $failCount++;
                $failMessages[] = "طلب #{$orderId}: " . $result['message'];
            }
        }
        $msg = '';
        if ($successCount > 0) $msg .= "✅ تم إرسال {$successCount} طلب إلى Ecotrack. ";
        if ($noTokenCount > 0) $msg .= "ℹ️ {$noTokenCount} طلب بدون توكن API (تم تغيير الحالة فقط). ";
        if ($failCount > 0)    { $_SESSION['error'] = "⚠️ فشل: {$failCount} — " . implode(' | ', $failMessages); }
        $_SESSION['message'] = trim($msg) ?: "تم تحديث الحالة";
    } else {
        $_SESSION['error'] = "لم تحدد أي طلب!";
    }
    $redirectUrl = "orders.php?filter=" . urlencode($_GET['filter'] ?? 'all');
    if (!empty($_GET['search'])) $redirectUrl .= "&search=" . urlencode($_GET['search']);
    header("Location: $redirectUrl"); exit();
}

// ===== معالجة تغيير الحالة الجماعي =====
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_change_status'])) {
    $selectedIds  = array_filter(array_map('intval', $_POST['selected_orders'] ?? []));
    $newStatus    = (int)($_POST['bulk_new_status'] ?? 0);
    $restoreStock = isset($_POST['restore_stock']) ? (int)$_POST['restore_stock'] : 0;

    if (!empty($selectedIds) && $newStatus) {
        foreach ($selectedIds as $orderId) {
            if ($newStatus == 4 && $restoreStock == 1) {
                $itemsStmt = $pdo->prepare("SELECT product_variant_id, quantity FROM order_items WHERE order_id = ?");
                $itemsStmt->execute([$orderId]);
                foreach ($itemsStmt->fetchAll() as $item) {
                    if ($item['product_variant_id']) {
                        $pdo->prepare("UPDATE product_variants SET stock = stock + ? WHERE id = ?")
                            ->execute([$item['quantity'], $item['product_variant_id']]);
                    }
                }
            }
            if ($newStatus == 2) {
                $pdo->prepare("UPDATE orders SET status_id = ?, sent_date = NOW() WHERE id = ?")->execute([$newStatus, $orderId]);
            } else {
                $pdo->prepare("UPDATE orders SET status_id = ? WHERE id = ?")->execute([$newStatus, $orderId]);
            }
        }
        $msg = "تم تغيير حالة " . count($selectedIds) . " طلب بنجاح";
        if ($newStatus == 4 && $restoreStock == 1) $msg .= " (تم إرجاع المخزون)";
        $_SESSION['message'] = $msg;
    }
    $redirectUrl = "orders.php?filter=" . urlencode($_GET['filter'] ?? 'all');
    if (!empty($_GET['search'])) $redirectUrl .= "&search=" . urlencode($_GET['search']);
    header("Location: $redirectUrl"); exit();
}

// ===== معالجة تغيير الحالة (مفردة مع Ecotrack) =====
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_order_status'])) {
    $orderId      = (int)($_POST['order_id'] ?? 0);
    $newStatus    = (int)($_POST['new_status'] ?? 0);
    $restoreStock = (int)($_POST['restore_stock'] ?? 0);

    if ($orderId && $newStatus) {
        try {
            $pdo->beginTransaction();

            if ($newStatus == 4 && $restoreStock == 1) {
                $itemsStmt = $pdo->prepare("SELECT product_variant_id, quantity FROM order_items WHERE order_id = ?");
                $itemsStmt->execute([$orderId]);
                foreach ($itemsStmt->fetchAll() as $item) {
                    if ($item['product_variant_id']) {
                        $pdo->prepare("UPDATE product_variants SET stock = stock + ? WHERE id = ?")
                            ->execute([$item['quantity'], $item['product_variant_id']]);
                    }
                }
            }

            if ($newStatus == 2) {
                $pdo->prepare("UPDATE orders SET status_id = ?, sent_date = NOW() WHERE id = ?")->execute([$newStatus, $orderId]);
            } else {
                $pdo->prepare("UPDATE orders SET status_id = ? WHERE id = ?")->execute([$newStatus, $orderId]);
            }

            $pdo->commit();

            // عند الإرسال → جرّب Ecotrack
            if ($newStatus == 2) {
                $result = sendOrderToEcotrack($pdo, $orderId);
                if ($result['success']) {
                    $_SESSION['message'] = "✅ تم تغيير الحالة وإرسال الطلب إلى Ecotrack — رمز التتبع: " . $result['tracking_code'];
                } elseif (!empty($result['no_token'])) {
                    $_SESSION['message'] = "✅ تم تغيير الحالة إلى مرسل (شركة التوصيل لا تدعم Ecotrack)";
                } else {
                    $_SESSION['message'] = "✅ تم تغيير الحالة إلى مرسل";
                    $_SESSION['error']   = "⚠️ فشل إرسال Ecotrack: " . $result['message'];
                }
            } else {
                $msg = "تم تغيير حالة الطلب بنجاح";
                if ($newStatus == 4 && $restoreStock == 1) $msg .= " (تم إرجاع المخزون ✅)";
                $_SESSION['message'] = $msg;
            }
        } catch (Exception $e) {
            $pdo->rollBack();
            $_SESSION['error'] = "خطأ: " . $e->getMessage();
        }
    }
    $redirectUrl = "orders.php?filter=" . urlencode($_GET['filter'] ?? 'all');
    if (!empty($_GET['search'])) $redirectUrl .= "&search=" . urlencode($_GET['search']);
    header("Location: $redirectUrl"); exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_delivery_price'])) {
    $orderId = (int)($_POST['order_id'] ?? 0);
    $newDeliveryPrice = $_POST['new_delivery_price'] !== '' ? floatval($_POST['new_delivery_price']) : 0;
    if ($orderId) {
        try {
            $pdo->beginTransaction();
            $pdo->prepare("UPDATE orders SET delivery_price_modified = ? WHERE id = ?")->execute([$newDeliveryPrice, $orderId]);
            $pdo->commit();
            $_SESSION['message'] = "تم تعديل سعر التوصيل بنجاح";
        } catch (Exception $e) { $pdo->rollBack(); $_SESSION['error'] = "خطأ: " . $e->getMessage(); }
    }
    $redirectUrl = "orders.php?filter=" . urlencode($_GET['filter'] ?? 'all');
    if (!empty($_GET['search'])) $redirectUrl .= "&search=" . urlencode($_GET['search']);
    header("Location: $redirectUrl"); exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_order_item'])) {
    $itemId = (int)($_POST['item_id'] ?? 0);
    $orderId = (int)($_POST['order_id'] ?? 0);
    $newPrice = floatval($_POST['new_price'] ?? 0);
    $newQuantity = intval($_POST['new_quantity'] ?? 1);
    $selectedAttributes = $_POST['selected_attributes'] ?? '[]';
    if ($itemId > 0 && $orderId > 0 && $newPrice > 0 && $newQuantity > 0) {
        try {
            $pdo->beginTransaction();
            $stmt = $pdo->prepare("SELECT oi.product_variant_id, oi.quantity as old_quantity, o.status_id FROM order_items oi JOIN orders o ON oi.order_id = o.id WHERE oi.id = ?");
            $stmt->execute([$itemId]);
            $oldItem = $stmt->fetch();
            if ($oldItem) {
                if ($oldItem['status_id'] == 1) {
                    $pdo->prepare("UPDATE product_variants SET stock = stock + ? WHERE id = ?")->execute([$oldItem['old_quantity'], $oldItem['product_variant_id']]);
                    $pdo->prepare("UPDATE product_variants SET stock = stock - ? WHERE id = ?")->execute([$newQuantity, $oldItem['product_variant_id']]);
                }
                $pdo->prepare("UPDATE order_items SET unit_price = ?, quantity = ?, selected_attribute_value = ? WHERE id = ?")->execute([$newPrice, $newQuantity, $selectedAttributes, $itemId]);
                $pdo->commit();
                $_SESSION['message'] = "تم تعديل المنتج بنجاح";
            } else { $pdo->rollBack(); $_SESSION['error'] = "المنتج غير موجود"; }
        } catch (Exception $e) { $pdo->rollBack(); $_SESSION['error'] = "خطأ: " . $e->getMessage(); }
    }
    $redirectUrl = "orders.php?filter=" . urlencode($_GET['filter'] ?? 'all');
    if (!empty($_GET['search'])) $redirectUrl .= "&search=" . urlencode($_GET['search']);
    header("Location: $redirectUrl"); exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_single_item'])) {
    $itemId = (int)($_POST['item_id'] ?? 0);
    $restoreStock = (int)($_POST['restore_stock'] ?? 0);
    if ($itemId > 0) {
        try {
            $pdo->beginTransaction();
            $stmt = $pdo->prepare("SELECT oi.product_variant_id, oi.quantity, o.status_id FROM order_items oi JOIN orders o ON oi.order_id = o.id WHERE oi.id = ?");
            $stmt->execute([$itemId]);
            $itemDetails = $stmt->fetch();
            if ($itemDetails) {
                if ($restoreStock == 1 && $itemDetails['product_variant_id']) {
                    $pdo->prepare("UPDATE product_variants SET stock = stock + ? WHERE id = ?")
                        ->execute([$itemDetails['quantity'], $itemDetails['product_variant_id']]);
                }
                $pdo->prepare("DELETE FROM order_items WHERE id = ?")->execute([$itemId]);
            }
            $pdo->commit();
            $msg = "تم حذف المنتج من الطلب";
            if ($restoreStock == 1) $msg .= " (تم إرجاع المخزون ✅)";
            $_SESSION['message'] = $msg;
        } catch (Exception $e) { $pdo->rollBack(); $_SESSION['error'] = "خطأ: " . $e->getMessage(); }
    }
    $redirectUrl = "orders.php?filter=" . urlencode($_GET['filter'] ?? 'all');
    if (!empty($_GET['search'])) $redirectUrl .= "&search=" . urlencode($_GET['search']);
    header("Location: $redirectUrl"); exit();
}

// ===== حذف طلب كامل مع خيار إرجاع المخزون =====
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_single_order'])) {
    $orderId      = (int)($_POST['order_id'] ?? 0);
    $restoreStock = (int)($_POST['restore_stock'] ?? 0);
    if ($orderId > 0) {
        try {
            $pdo->beginTransaction();
            if ($restoreStock == 1) {
                $itemsStmt = $pdo->prepare("SELECT product_variant_id, quantity FROM order_items WHERE order_id = ?");
                $itemsStmt->execute([$orderId]);
                foreach ($itemsStmt->fetchAll() as $item) {
                    if ($item['product_variant_id']) {
                        $pdo->prepare("UPDATE product_variants SET stock = stock + ? WHERE id = ?")
                            ->execute([$item['quantity'], $item['product_variant_id']]);
                    }
                }
            }
            $pdo->prepare("DELETE FROM order_items WHERE order_id = ?")->execute([$orderId]);
            $pdo->prepare("DELETE FROM orders WHERE id = ?")->execute([$orderId]);
            $pdo->commit();
            $msg = "تم حذف الطلب #$orderId بنجاح";
            if ($restoreStock == 1) $msg .= " (تم إرجاع المخزون ✅)";
            $_SESSION['message'] = $msg;
        } catch (Exception $e) { $pdo->rollBack(); $_SESSION['error'] = "خطأ: " . $e->getMessage(); }
    }
    $redirectUrl = "orders.php?filter=" . urlencode($_GET['filter'] ?? 'all');
    if (!empty($_GET['search'])) $redirectUrl .= "&search=" . urlencode($_GET['search']);
    header("Location: $redirectUrl"); exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_order'])) {
    $orderId = (int)($_POST['order_id'] ?? 0);
    $customer_name = $_POST['customer_name'] ?? '';
    $phone = $_POST['phone'] ?? '';
    $phone2 = $_POST['phone2'] ?? '';
    $address = $_POST['address'] ?? '';
    $wilaya_id = (int)($_POST['wilaya_id'] ?? 0);
    $delivery_type = $_POST['delivery_type'] ?? 'home';
    $delivery_company_id = (int)($_POST['delivery_company_id'] ?? 0);
    $commune_id = null; $municipality_text = null;
    $commune_value = $_POST['municipality'] ?? '';
    if (!empty($commune_value)) {
        if (is_numeric($commune_value)) { $commune_id = (int)$commune_value; }
        else { $commune_id = getCommuneIdByName($pdo, $commune_value, $wilaya_id); if (!$commune_id) $municipality_text = $commune_value; }
    }
    try {
        $pdo->beginTransaction();
        if ($commune_id) {
            $pdo->prepare("UPDATE orders SET customer_name=?, phone=?, phone2=?, address=?, commune_id=?, municipality=?, wilaya_id=?, delivery_type=?, delivery_company_id=? WHERE id=?")
                ->execute([$customer_name, $phone, $phone2, $address, $commune_id, $municipality_text, $wilaya_id, $delivery_type, $delivery_company_id, $orderId]);
        } else {
            $municipality_text = $commune_value ?? '';
            $pdo->prepare("UPDATE orders SET customer_name=?, phone=?, phone2=?, address=?, municipality=?, wilaya_id=?, delivery_type=?, delivery_company_id=? WHERE id=?")
                ->execute([$customer_name, $phone, $phone2, $address, $municipality_text, $wilaya_id, $delivery_type, $delivery_company_id, $orderId]);
        }
        $pdo->commit();
        $_SESSION['message'] = "تم تحديث الطلب بنجاح";
    } catch (Exception $e) { $pdo->rollBack(); $_SESSION['error'] = "خطأ: " . $e->getMessage(); }
    header("Location: orders.php?filter=" . urlencode($filter ?? 'all')); exit();
}

// ===== جلب الطلبات =====
$filter = $_GET['filter'] ?? 'all';
$searchQuery = trim($_GET['search'] ?? '');

$query = "SELECT o.*, os.name as status_name, dc.name as delivery_company_name, dc.api_token,
          w.name as wilaya_name, o.commune_id
          FROM orders o
          LEFT JOIN order_statuses os ON o.status_id = os.id
          LEFT JOIN delivery_companies dc ON o.delivery_company_id = dc.id
          LEFT JOIN wilayas w ON o.wilaya_id = w.id
          WHERE 1=1";
$params = [];

if (!empty($searchQuery)) {
    $query .= " AND (o.customer_name LIKE :search OR o.phone LIKE :search OR o.phone2 LIKE :search OR w.name LIKE :search OR o.municipality LIKE :search)";
    $params[':search'] = '%' . $searchQuery . '%';
}

if ($filter !== 'all') {
    $statusMap = ['pending' => 1, 'sent' => 2, 'delivered' => 3];
    if (isset($statusMap[$filter])) $query .= " AND o.status_id = " . $statusMap[$filter];
}

$query .= " ORDER BY o.order_date DESC";
$stmt = $pdo->prepare($query);
foreach ($params as $key => $value) $stmt->bindValue($key, $value);
$stmt->execute();
$orders = $stmt->fetchAll();

$orderItems = []; $orderTotals = []; $productAttributes = [];
$orderVariantBadges = [];

foreach ($orders as $order) {
    $orderId = $order['id'];
    $stmt = $pdo->prepare("SELECT oi.*, p.name as product_name, p.id as product_id, pi.image_url as product_image, oi.selected_attribute_value, pv.id as variant_id
                           FROM order_items oi
                           LEFT JOIN product_variants pv ON oi.product_variant_id = pv.id
                           LEFT JOIN products p ON pv.product_id = p.id
                           LEFT JOIN product_images pi ON p.id = pi.product_id AND pi.is_primary = 1
                           WHERE oi.order_id = ?");
    $stmt->execute([$orderId]);
    $items = $stmt->fetchAll();
    $orderItems[$orderId] = $items;
    foreach ($items as $item) {
        if (!isset($productAttributes[$item['product_id']])) {
            $productAttributes[$item['product_id']] = getProductAttributes($pdo, $item['product_id']);
        }
    }
    $total = 0;
    foreach ($items as $item) $total += $item['quantity'] * $item['unit_price'];
    $orderTotals[$orderId] = $total;

    $badges = [];
    foreach ($items as $item) {
        if (!empty($item['selected_attribute_value']) && $item['selected_attribute_value'] !== '[]') {
            try {
                $attrs = json_decode($item['selected_attribute_value'], true);
                if (is_array($attrs)) {
                    foreach ($attrs as $attrName => $attrVal) {
                        if (!empty($attrVal)) $badges[] = ['name' => $attrName, 'value' => $attrVal];
                    }
                }
            } catch(Exception $e) {}
        }
    }
    $orderVariantBadges[$orderId] = $badges;
}

$deliveryCompanies = $pdo->query("SELECT * FROM delivery_companies")->fetchAll();
$wilayas = $pdo->query("SELECT * FROM wilayas ORDER BY name")->fetchAll();

$deliveryPrices = [];
foreach ($orders as $order) {
    $deliveryPrices[$order['id']] = $order['wilaya_id'] ? getDeliveryPrice($pdo, $order['id'], $order['wilaya_id'], $order['delivery_type'], $order['delivery_company_id']) : 0;
}

$allCommunes = [];
foreach ($wilayas as $wilaya) { $allCommunes[$wilaya['id']] = getCommunesByWilaya($pdo, $wilaya['id']); }

$communeNames = [];
foreach ($orders as $order) {
    if ($order['commune_id']) $communeNames[$order['id']] = getCommuneName($pdo, $order['commune_id']);
    else $communeNames[$order['id']] = $order['municipality'] ?? '--';
}

$today = date('Y-m-d');
$stats = ['total' => count($orders), 'pending' => 0, 'sent' => 0, 'delivered' => 0, 'cancelled' => 0, 'revenue' => 0, 'today' => 0];
foreach ($orders as $o) {
    if ($o['status_id'] == 1)      $stats['pending']++;
    elseif ($o['status_id'] == 2)  $stats['sent']++;
    elseif ($o['status_id'] == 3)  $stats['delivered']++;
    elseif ($o['status_id'] == 4)  $stats['cancelled']++;
    $stats['revenue'] += ($orderTotals[$o['id']] ?? 0) + ($deliveryPrices[$o['id']] ?? 0);
    if (substr($o['order_date'], 0, 10) === $today) $stats['today']++;
}

$lastOrderId = (int)$pdo->query("SELECT COALESCE(MAX(id),0) as last_id FROM orders")->fetchColumn();

$attrColorPalette  = ['#EFF6FF','#F0FDF4','#FEF3C7','#FDF2F8','#F0F9FF','#ECFDF5','#FFF7ED','#F5F3FF','#FFF1F2','#F0FDFA'];
$attrBorderPalette = ['#BFDBFE','#A7F3D0','#FDE68A','#F9A8D4','#BAE6FD','#6EE7B7','#FED7AA','#DDD6FE','#FECACA','#99F6E4'];
$attrTextPalette   = ['#1D4ED8','#065F46','#92400E','#9D174D','#0369A1','#047857','#C2410C','#6D28D9','#B91C1C','#0F766E'];
?>
<!DOCTYPE html>
<html dir="rtl" lang="ar">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>إدارة الطلبات</title>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;700;800;900&display=swap" rel="stylesheet">
    <style>
    :root {
        --primary:#1E40AF; --primary-light:#3B82F6; --primary-dark:#1E3A8A;
        --accent:#F59E0B; --success:#059669; --success-light:#D1FAE5;
        --danger:#DC2626; --danger-light:#FEE2E2;
        --warning:#D97706; --warning-light:#FEF3C7;
        --info:#0284C7; --info-light:#E0F2FE;
        --sent:#7C3AED; --sent-light:#EDE9FE;
        --bg:#F1F5F9; --surface:#FFFFFF; --surface-2:#F8FAFC;
        --border:#E2E8F0; --text:#0F172A; --text-2:#475569; --text-3:#94A3B8;
        --shadow-sm:0 1px 3px rgba(0,0,0,0.06); --shadow-md:0 4px 16px rgba(0,0,0,0.08); --shadow-lg:0 10px 40px rgba(0,0,0,0.12);
        --radius:14px; --radius-sm:8px; --tr:all 0.2s cubic-bezier(0.4,0,0.2,1);
    }
    *,*::before,*::after{margin:0;padding:0;box-sizing:border-box;font-family:'Tajawal',sans-serif;}
    body{background:var(--bg);color:var(--text);padding:20px;min-height:100vh;}
    ::-webkit-scrollbar{width:5px;height:5px;}
    ::-webkit-scrollbar-track{background:#f1f5f9;}
    ::-webkit-scrollbar-thumb{background:var(--primary-light);border-radius:10px;}
    .container{max-width:1600px;margin:0 auto;}

    .header{display:flex;justify-content:space-between;align-items:center;margin-bottom:22px;padding:18px 24px;background:var(--surface);border-radius:var(--radius);box-shadow:var(--shadow-sm);border:1px solid var(--border);animation:fadeDown 0.4s ease;flex-wrap:wrap;gap:12px;}
    @keyframes fadeDown{from{opacity:0;transform:translateY(-12px)}to{opacity:1;transform:translateY(0)}}
    .header h1{color:var(--primary);font-size:22px;font-weight:900;display:flex;align-items:center;gap:10px;}
    .header-icon{background:linear-gradient(135deg,var(--primary),var(--primary-light));color:white;width:38px;height:38px;border-radius:10px;display:flex;align-items:center;justify-content:center;}
    .filter-buttons{display:flex;gap:8px;flex-wrap:wrap;align-items:center;}

    .stats-grid{display:grid;grid-template-columns:repeat(6,1fr);gap:14px;margin-bottom:22px;animation:fadeUp 0.4s ease 0.1s both;}
    @keyframes fadeUp{from{opacity:0;transform:translateY(14px)}to{opacity:1;transform:translateY(0)}}
    @media(max-width:1200px){.stats-grid{grid-template-columns:repeat(3,1fr)}}
    @media(max-width:600px){.stats-grid{grid-template-columns:repeat(2,1fr)}}
    .stat-card{background:var(--surface);border-radius:var(--radius);padding:16px 18px;border:1px solid var(--border);box-shadow:var(--shadow-sm);transition:var(--tr);position:relative;overflow:hidden;}
    .stat-card::after{content:'';position:absolute;bottom:0;left:0;right:0;height:3px;border-radius:0 0 var(--radius) var(--radius);transition:var(--tr);}
    .stat-card:hover{transform:translateY(-4px);box-shadow:var(--shadow-md);}
    .stat-card.s-total::after{background:var(--primary);}
    .stat-card.s-today::after{background:var(--accent);}
    .stat-card.s-pending::after{background:var(--warning);}
    .stat-card.s-sent::after{background:var(--sent);}
    .stat-card.s-done::after{background:var(--success);}
    .stat-card.s-revenue::after{background:var(--info);}
    .stat-icon{width:38px;height:38px;border-radius:var(--radius-sm);display:flex;align-items:center;justify-content:center;font-size:20px;margin-bottom:12px;}
    .s-total .stat-icon{background:#EFF6FF;color:var(--primary);}
    .s-today .stat-icon{background:#FFFBEB;color:var(--accent);}
    .s-pending .stat-icon{background:var(--warning-light);color:var(--warning);}
    .s-sent .stat-icon{background:var(--sent-light);color:var(--sent);}
    .s-done .stat-icon{background:var(--success-light);color:var(--success);}
    .s-revenue .stat-icon{background:var(--info-light);color:var(--info);}
    .stat-value{font-size:28px;font-weight:900;color:var(--text);line-height:1;margin-bottom:4px;letter-spacing:-1px;}
    .stat-label{font-size:11px;color:var(--text-3);font-weight:700;text-transform:uppercase;letter-spacing:0.5px;}

    .card{background:var(--surface);border-radius:var(--radius);box-shadow:var(--shadow-sm);padding:20px;border:1px solid var(--border);animation:fadeUp 0.4s ease 0.2s both;}

    .search-bar{display:flex;margin-bottom:18px;border-radius:var(--radius-sm);overflow:hidden;border:1.5px solid var(--border);transition:var(--tr);}
    .search-bar:focus-within{border-color:var(--primary-light);box-shadow:0 0 0 3px rgba(59,130,246,0.12);}
    .search-bar input{flex:1;padding:12px 16px;border:none;outline:none;font-size:14px;color:var(--text);}
    .search-bar button{padding:0 20px;background:var(--primary);color:white;border:none;cursor:pointer;font-size:15px;transition:var(--tr);display:flex;align-items:center;gap:6px;}
    .search-bar button:hover{background:var(--primary-dark);}

    .bulk-toolbar{display:none;align-items:center;gap:10px;padding:12px 16px;background:linear-gradient(135deg,#EDE9FE,#F5F3FF);border:1.5px solid #DDD6FE;border-radius:var(--radius-sm);margin-bottom:14px;flex-wrap:wrap;animation:fadeUp 0.25s ease;}
    .bulk-toolbar.visible{display:flex;}
    .bulk-count{font-weight:900;color:var(--sent);font-size:15px;display:flex;align-items:center;gap:7px;}
    .bulk-count span{background:var(--sent);color:white;border-radius:50%;width:26px;height:26px;display:inline-flex;align-items:center;justify-content:center;font-size:13px;}
    .bulk-divider{width:1px;height:24px;background:#DDD6FE;}
    .bulk-status-wrap{display:flex;align-items:center;gap:7px;}
    .bulk-status-wrap select{padding:7px 12px;border:1.5px solid #DDD6FE;border-radius:var(--radius-sm);font-family:'Tajawal',sans-serif;font-size:13px;color:var(--text);background:white;outline:none;cursor:pointer;}

    .btn{padding:9px 15px;border-radius:var(--radius-sm);font-weight:700;cursor:pointer;transition:var(--tr);text-decoration:none;display:inline-flex;align-items:center;gap:6px;font-size:13px;border:none;letter-spacing:0.2px;}
    .btn-sm{padding:6px 10px;font-size:12px;}
    .btn-primary{background:var(--primary);color:white;}
    .btn-primary:hover{background:var(--primary-dark);transform:translateY(-1px);box-shadow:0 4px 12px rgba(30,64,175,0.3);}
    .btn-danger{background:var(--danger);color:white;}
    .btn-danger:hover{background:#B91C1C;transform:translateY(-1px);}
    .btn-warning{background:var(--warning);color:white;}
    .btn-warning:hover{background:#B45309;}
    .btn-success{background:var(--success);color:white;}
    .btn-success:hover{background:#047857;}
    .btn-info{background:var(--info);color:white;}
    .btn-info:hover{background:#0369A1;}
    .btn-edit{background:#16A34A;color:white;}
    .btn-edit:hover{background:#15803D;}
    .btn-delivery-edit{background:var(--sent);color:white;}
    .btn-delivery-edit:hover{background:#6D28D9;}
    .btn-ecotrack{background:linear-gradient(135deg,#7C3AED,#6D28D9);color:white;}
    .btn-ecotrack:hover{background:linear-gradient(135deg,#6D28D9,#5B21B6);transform:translateY(-1px);box-shadow:0 4px 14px rgba(124,58,237,0.35);}
    .btn-copy{background:#EFF6FF;color:var(--primary);padding:3px 8px;font-size:11px;border-radius:4px;border:none;cursor:pointer;transition:var(--tr);display:inline-flex;align-items:center;}
    .btn-copy:hover{background:var(--primary);color:white;}
    .filter-buttons .btn.active{background:var(--primary);color:white;box-shadow:0 4px 14px rgba(30,64,175,0.3);}
    .filter-buttons .btn:not(.active):not(.btn-export){background:var(--surface-2);color:var(--text-2);border:1px solid var(--border);}

    .order-checkbox{width:17px;height:17px;cursor:pointer;accent-color:var(--sent);border-radius:4px;}
    .select-all-wrap{display:flex;align-items:center;gap:6px;cursor:pointer;user-select:none;font-size:12px;font-weight:700;color:var(--text-2);}
    tr.selected-row td{background:#F5F3FF !important;}

    .export-wrap{position:relative;display:inline-block;}
    .btn-export{background:linear-gradient(135deg,#16A34A,#15803D);color:white;}
    .btn-export:hover{background:linear-gradient(135deg,#15803D,#166534);transform:translateY(-1px);box-shadow:0 4px 12px rgba(22,163,74,0.35);}
    .export-menu{display:none;position:absolute;top:calc(100% + 8px);left:0;background:white;border:1.5px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow-lg);min-width:250px;z-index:500;overflow:hidden;animation:fadeUp 0.2s ease;}
    .export-menu.open{display:block;}
    .export-menu-header{padding:10px 16px;background:var(--surface-2);border-bottom:1px solid var(--border);font-size:11px;font-weight:800;color:var(--text-3);text-transform:uppercase;letter-spacing:0.5px;}
    .export-option{display:flex;align-items:center;gap:10px;padding:11px 16px;color:var(--text);text-decoration:none;font-size:13px;font-weight:600;transition:var(--tr);border-bottom:1px solid #F1F5F9;}
    .export-option:hover{background:#EFF6FF;color:var(--primary);padding-right:20px;}
    .export-option:last-of-type{border-bottom:none;}
    .export-date-section{padding:12px 14px;background:var(--surface-2);border-top:1px solid var(--border);}
    .export-date-section label{font-size:11px;font-weight:700;color:var(--text-3);display:block;margin-bottom:7px;}
    .export-date-row{display:flex;gap:6px;align-items:center;margin-bottom:8px;}
    .export-date-row input{flex:1;padding:7px 9px;border:1.5px solid var(--border);border-radius:var(--radius-sm);font-size:12px;font-family:'Tajawal',sans-serif;color:var(--text);outline:none;transition:var(--tr);}
    .export-date-row input:focus{border-color:var(--primary-light);}
    .export-date-row span{color:var(--text-3);font-size:12px;}
    .btn-export-date{width:100%;padding:8px;background:linear-gradient(135deg,var(--primary),var(--primary-light));color:white;border:none;border-radius:var(--radius-sm);font-family:'Tajawal',sans-serif;font-weight:700;font-size:12px;cursor:pointer;transition:var(--tr);display:flex;align-items:center;justify-content:center;gap:6px;}
    .btn-export-date:hover{opacity:0.9;}

    .table-responsive{overflow-x:auto;border-radius:var(--radius-sm);border:1px solid var(--border);}
    table{width:100%;border-collapse:collapse;background:white;font-size:13px;}
    th{background:linear-gradient(135deg,var(--primary),var(--primary-dark));color:white;font-weight:700;font-size:12px;padding:14px 12px;text-align:right;white-space:nowrap;}
    td{padding:12px;text-align:right;border-bottom:1px solid #F1F5F9;vertical-align:middle;color:var(--text-2);}
    tr:last-child td{border-bottom:none;}
    tr{transition:var(--tr);}
    tr:hover td{background:#F8FAFC;}
    td:first-child{font-weight:800;color:var(--text);font-size:14px;}

    /* ═══ حالة الطلب مع اسم الشركة ═══ */
    .status-cell{display:flex;flex-direction:column;gap:5px;align-items:flex-start;}
    .status-select{padding:6px 10px;border:1.5px solid var(--border);border-radius:20px;font-size:12px;font-family:'Tajawal',sans-serif;font-weight:700;cursor:pointer;outline:none;transition:var(--tr);background:white;color:var(--text);appearance:none;text-align:center;}
    .status-select:focus{border-color:var(--primary-light);box-shadow:0 0 0 3px rgba(59,130,246,0.12);}

    /* بادج اسم الشركة يظهر فقط عند الإرسال */
    .company-badge{display:none;align-items:center;gap:4px;padding:3px 10px;border-radius:20px;font-size:11px;font-weight:800;background:linear-gradient(135deg,#7C3AED,#6D28D9);color:white;border:none;white-space:nowrap;animation:fadeUp 0.3s ease;}
    .company-badge.visible{display:inline-flex;}
    .company-badge-dot{width:6px;height:6px;border-radius:50%;background:rgba(255,255,255,0.7);flex-shrink:0;}

    .phone-badge{display:inline-flex;align-items:center;gap:5px;background:#EFF6FF;padding:4px 10px;border-radius:20px;font-size:12px;color:var(--primary);font-weight:700;border:1px solid #BFDBFE;}
    .phone-secondary{margin-top:4px;color:var(--text-3);font-size:12px;display:flex;align-items:center;gap:5px;}

    .delivery-cost-free{background:var(--success-light);color:var(--success);padding:4px 10px;border-radius:20px;font-weight:700;font-size:12px;display:inline-flex;align-items:center;gap:4px;border:1px solid #A7F3D0;}
    .delivery-cost{font-weight:700;color:var(--text);font-size:13px;}
    .delivery-cost-modified{background:var(--warning-light);color:var(--warning);padding:4px 10px;border-radius:20px;font-weight:700;font-size:12px;display:inline-flex;align-items:center;gap:4px;border:1px solid #FDE68A;}
    .delivery-modified{background:#FEF3C7;border:1px solid #FCD34D;padding:2px 6px;border-radius:4px;font-size:10px;color:var(--warning);font-weight:700;}

    .tracking-badge{display:inline-flex;align-items:center;gap:5px;background:#EDE9FE;padding:4px 10px;border-radius:20px;font-size:11px;color:var(--sent);font-weight:700;border:1px solid #DDD6FE;}
    .tracking-badge a{color:var(--sent);text-decoration:none;}
    .tracking-badge a:hover{text-decoration:underline;}
    .no-tracking{color:var(--text-3);font-size:12px;}

    .variant-badges{display:flex;flex-wrap:wrap;gap:4px;}
    .variant-badge{display:inline-flex;align-items:center;gap:3px;padding:3px 9px;border-radius:20px;font-size:11px;font-weight:700;border:1.5px solid;white-space:nowrap;}
    .variant-badge-dot{width:8px;height:8px;border-radius:50%;flex-shrink:0;}
    .variant-empty{color:var(--text-3);font-size:11px;font-style:italic;}

    .action-buttons{display:flex;gap:4px;flex-wrap:nowrap;}

    .message,.error{padding:14px 18px;margin-bottom:18px;border-radius:var(--radius-sm);display:flex;align-items:center;gap:10px;font-weight:600;animation:slideIn 0.3s ease;}
    @keyframes slideIn{from{opacity:0;transform:translateY(-8px)}to{opacity:1;transform:translateY(0)}}
    .message{background:var(--success-light);color:var(--success);border:1px solid #A7F3D0;}
    .error{background:var(--danger-light);color:var(--danger);border:1px solid #FECACA;}

    /* ===== STOCK RESTORE MODAL ===== */
    .sr-modal{display:none;position:fixed;z-index:2000;inset:0;background:rgba(15,23,42,0.6);align-items:center;justify-content:center;backdrop-filter:blur(5px);padding:20px;}
    .sr-modal.open{display:flex;}
    .sr-box{background:white;border-radius:20px;width:90%;max-width:420px;box-shadow:0 25px 60px rgba(0,0,0,0.2);overflow:hidden;animation:srIn 0.3s cubic-bezier(0.34,1.56,0.64,1);}
    @keyframes srIn{from{opacity:0;transform:scale(0.88) translateY(20px)}to{opacity:1;transform:scale(1) translateY(0)}}
    .sr-header{padding:22px 24px 16px;text-align:center;}
    .sr-icon{width:70px;height:70px;border-radius:50%;margin:0 auto 14px;display:flex;align-items:center;justify-content:center;font-size:34px;}
    .sr-icon.danger{background:#FEE2E2;}
    .sr-icon.cancel{background:#FEF3C7;}
    .sr-title{font-size:19px;font-weight:900;color:var(--text);margin-bottom:6px;}
    .sr-sub{font-size:13px;color:var(--text-3);line-height:1.6;}
    .sr-divider{height:1px;background:var(--border);margin:0 24px;}
    .sr-body{padding:20px 24px;}
    .sr-question{font-size:14px;font-weight:700;color:var(--text);margin-bottom:14px;display:flex;align-items:center;gap:8px;}
    .sr-options{display:flex;flex-direction:column;gap:10px;margin-bottom:20px;}
    .sr-option{display:flex;align-items:flex-start;gap:12px;padding:14px 16px;border:2px solid var(--border);border-radius:12px;cursor:pointer;transition:var(--tr);background:var(--surface-2);}
    .sr-option:hover{border-color:var(--primary-light);background:#EFF6FF;}
    .sr-option input[type="radio"]{display:none;}
    .sr-option.selected-opt{border-color:var(--primary);background:#EFF6FF;}
    .sr-option-icon{width:36px;height:36px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:18px;flex-shrink:0;}
    .sr-option-icon.yes{background:#D1FAE5;}
    .sr-option-icon.no{background:#FEE2E2;}
    .sr-option-text strong{display:block;font-size:13px;font-weight:800;color:var(--text);margin-bottom:2px;}
    .sr-option-text small{font-size:11px;color:var(--text-3);}
    .sr-footer{display:flex;gap:10px;padding:0 24px 22px;}
    .sr-footer .btn{flex:1;justify-content:center;padding:13px;}
    .sr-btn-confirm-danger{background:linear-gradient(135deg,var(--danger),#B91C1C);color:white;font-size:14px;}
    .sr-btn-confirm-danger:hover{opacity:0.9;transform:translateY(-1px);}
    .sr-btn-confirm-cancel{background:linear-gradient(135deg,#D97706,#B45309);color:white;font-size:14px;}
    .sr-btn-confirm-cancel:hover{opacity:0.9;transform:translateY(-1px);}
    .sr-btn-abort{background:var(--surface-2);color:var(--text-2);border:1.5px solid var(--border);font-size:14px;}
    .sr-btn-abort:hover{background:var(--border);}

    /* ===== GENERAL MODALS ===== */
    .modal{display:none;position:fixed;z-index:1000;inset:0;background:rgba(15,23,42,0.55);align-items:center;justify-content:center;backdrop-filter:blur(4px);padding:20px;}
    .modal-content{background:white;padding:28px;border-radius:var(--radius);width:90%;max-width:1000px;max-height:90vh;overflow-y:auto;box-shadow:var(--shadow-lg);animation:modalIn 0.25s ease;}
    @keyframes modalIn{from{opacity:0;transform:scale(0.96) translateY(-10px)}to{opacity:1;transform:scale(1) translateY(0)}}
    .modal-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:22px;padding-bottom:16px;border-bottom:1.5px solid var(--border);}
    .modal-header h2{color:var(--primary);font-size:19px;font-weight:900;display:flex;align-items:center;gap:10px;}
    .close{width:32px;height:32px;display:flex;align-items:center;justify-content:center;border-radius:50%;font-size:20px;cursor:pointer;color:var(--text-3);transition:var(--tr);background:var(--surface-2);border:1px solid var(--border);}
    .close:hover{background:var(--danger-light);color:var(--danger);}
    .modal-footer{display:flex;justify-content:flex-end;gap:10px;margin-top:22px;padding-top:16px;border-top:1px solid var(--border);}

    .form-group{margin-bottom:16px;}
    .form-group label{display:block;margin-bottom:6px;font-weight:700;font-size:13px;color:var(--text);}
    .form-group input,.form-group select,.form-group textarea{width:100%;padding:11px 14px;border:1.5px solid var(--border);border-radius:var(--radius-sm);font-size:14px;transition:var(--tr);font-family:'Tajawal',sans-serif;color:var(--text);background:white;}
    .form-group input:focus,.form-group select:focus,.form-group textarea:focus{border-color:var(--primary-light);outline:none;box-shadow:0 0 0 3px rgba(59,130,246,0.12);}
    .form-row{display:grid;grid-template-columns:1fr 1fr;gap:16px;}

    .customer-info-section{background:var(--surface-2);padding:20px;border-radius:var(--radius-sm);margin-bottom:20px;border:1px solid var(--border);}
    .customer-info-section h3{font-size:14px;font-weight:800;color:var(--primary);margin-bottom:14px;display:flex;align-items:center;gap:8px;}
    .customer-info-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:14px;}
    .info-item{display:flex;flex-direction:column;}
    .info-label{font-size:11px;color:var(--text-3);margin-bottom:3px;text-transform:uppercase;font-weight:700;letter-spacing:0.5px;}
    .info-value{font-size:14px;font-weight:700;color:var(--text);display:flex;align-items:center;flex-wrap:wrap;gap:5px;}

    .products-table{width:100%;border-collapse:collapse;font-size:13px;margin-bottom:16px;}
    .products-table th{background:#F1F5F9;color:var(--text-2);padding:10px 12px;font-weight:700;}
    .products-table td{padding:10px 12px;border-bottom:1px solid var(--border);}

    .summary-section{background:var(--surface-2);padding:16px 20px;border-radius:var(--radius-sm);border:1px solid var(--border);}
    .summary-section h3{font-size:14px;font-weight:800;color:var(--text);margin-bottom:12px;}
    .summary-row{display:flex;justify-content:space-between;padding:8px 0;border-bottom:1px solid var(--border);font-size:14px;color:var(--text-2);}
    .summary-row:last-child{border-bottom:none;}
    .summary-row.total{font-size:16px;font-weight:900;color:var(--primary);padding-top:12px;}

    .items-list{max-height:420px;overflow-y:auto;display:flex;flex-direction:column;gap:10px;}
    .item-row{padding:16px;border:1px solid var(--border);background:white;border-radius:var(--radius-sm);box-shadow:var(--shadow-sm);transition:var(--tr);}
    .item-row:hover{border-color:var(--primary-light);}
    .item-header{display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:8px;}
    .item-info strong{font-size:15px;color:var(--text);}
    .item-attributes{margin-top:10px;padding:10px 14px;background:#F8FAFC;border-radius:var(--radius-sm);border-right:3px solid var(--primary-light);}
    .item-actions{display:flex;gap:6px;}
    .delete-item-btn,.edit-item-btn{border:none;padding:6px 14px;border-radius:var(--radius-sm);font-size:12px;cursor:pointer;font-weight:700;transition:var(--tr);font-family:'Tajawal',sans-serif;color:white;display:inline-flex;align-items:center;gap:5px;}
    .delete-item-btn{background:var(--danger);}
    .delete-item-btn:hover{background:#B91C1C;}
    .edit-item-btn{background:var(--warning);}
    .edit-item-btn:hover{background:#B45309;}

    #notif-toast{position:fixed;top:22px;left:22px;z-index:9999;display:none;min-width:310px;max-width:380px;animation:toastIn 0.4s cubic-bezier(0.34,1.56,0.64,1);}
    @keyframes toastIn{from{opacity:0;transform:translateX(-30px) scale(0.95)}to{opacity:1;transform:translateX(0) scale(1)}}
    .toast-inner{background:white;border-radius:var(--radius);box-shadow:0 20px 50px rgba(0,0,0,0.15);padding:16px 18px;display:flex;align-items:flex-start;gap:12px;border:1.5px solid var(--success-light);position:relative;overflow:hidden;}
    .toast-inner::before{content:'';position:absolute;top:0;right:0;width:4px;height:100%;background:var(--success);}
    .toast-icon{width:40px;height:40px;background:var(--success-light);border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:22px;flex-shrink:0;}
    .toast-body{flex:1;}
    .toast-title{font-weight:900;color:var(--text);font-size:15px;margin-bottom:3px;}
    .toast-message{color:var(--text-2);font-size:13px;line-height:1.5;}
    .toast-close{background:none;border:none;color:var(--text-3);font-size:20px;cursor:pointer;padding:0;line-height:1;flex-shrink:0;transition:var(--tr);}
    .toast-close:hover{color:var(--danger);}
    .toast-progress{position:absolute;bottom:0;right:0;height:3px;background:var(--success);border-radius:0 0 0 var(--radius);animation:toastProgress 6s linear forwards;}
    @keyframes toastProgress{from{width:100%}to{width:0%}}

    .empty-state{text-align:center;padding:50px 20px;color:var(--text-3);}
    .empty-state .empty-icon{font-size:52px;margin-bottom:14px;display:block;}

    @media(max-width:768px){
        body{padding:12px;}
        .header{flex-direction:column;gap:12px;align-items:flex-start;}
        th,td{padding:9px 8px;font-size:11px;}
        .form-row{grid-template-columns:1fr;}
        #notif-toast{left:12px;right:12px;min-width:unset;}
        .action-buttons{flex-wrap:wrap;}
    }
    </style>
</head>
<body>
    <button onclick="toggleSidebar()" style="position:fixed;top:15px;right:15px;z-index:900;background:var(--primary);color:white;border:none;padding:10px 13px;border-radius:var(--radius-sm);cursor:pointer;display:flex;align-items:center" title="القائمة">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></svg>
    </button>
    <div class="sidebar-overlay" onclick="toggleSidebar()"></div>
    <?php include 'sidebar.php'; ?>

<div class="container">

    <div class="header">
        <h1>
            <span class="header-icon">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="white"><path d="M6 2L3 6v14a2 2 0 002 2h14a2 2 0 002-2V6l-3-4z"/><line x1="3" y1="6" x2="21" y2="6" stroke="white" stroke-width="2" fill="none"/><path d="M16 10a4 4 0 01-8 0" fill="none" stroke="white" stroke-width="2"/></svg>
            </span>
            إدارة الطلبات
        </h1>
        <div class="filter-buttons">
            <a href="?filter=all<?= !empty($searchQuery) ? '&search='.urlencode($searchQuery) : '' ?>" class="btn <?= $filter=='all' ? 'active btn-primary' : '' ?>">الكل</a>
            <a href="?filter=pending<?= !empty($searchQuery) ? '&search='.urlencode($searchQuery) : '' ?>" class="btn <?= $filter=='pending' ? 'active btn-warning' : '' ?>">⏳ انتظار</a>
            <a href="?filter=sent<?= !empty($searchQuery) ? '&search='.urlencode($searchQuery) : '' ?>" class="btn <?= $filter=='sent' ? 'active' : '' ?>" style="<?= $filter=='sent' ? 'background:var(--sent);color:white' : '' ?>">🚚 مرسل</a>
            <a href="?filter=delivered<?= !empty($searchQuery) ? '&search='.urlencode($searchQuery) : '' ?>" class="btn <?= $filter=='delivered' ? 'active btn-success' : '' ?>">✅ مسلّم</a>
            <div class="export-wrap" id="exportWrap">
                <button class="btn btn-export" onclick="toggleExportMenu(event)">
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
                    تصدير Excel
                    <svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor"><path d="M6 9l6 6 6-6"/></svg>
                </button>
                <div class="export-menu" id="exportMenu">
                    <div class="export-menu-header">اختر ما تريد تصديره</div>
                    <a href="export_orders.php?filter=all<?= !empty($searchQuery) ? '&search='.urlencode($searchQuery) : '' ?>" class="export-option">📋 كل الطلبات (<?= $stats['total'] ?>)</a>
                    <a href="export_orders.php?filter=pending<?= !empty($searchQuery) ? '&search='.urlencode($searchQuery) : '' ?>" class="export-option">⏳ طلبات الانتظار (<?= $stats['pending'] ?>)</a>
                    <a href="export_orders.php?filter=sent<?= !empty($searchQuery) ? '&search='.urlencode($searchQuery) : '' ?>" class="export-option">🚚 الطلبات المرسلة (<?= $stats['sent'] ?>)</a>
                    <a href="export_orders.php?filter=delivered<?= !empty($searchQuery) ? '&search='.urlencode($searchQuery) : '' ?>" class="export-option">✅ الطلبات المسلّمة (<?= $stats['delivered'] ?>)</a>
                    <div class="export-date-section">
                        <label>📅 تصدير بتاريخ محدد:</label>
                        <div class="export-date-row">
                            <input type="date" id="export_date_from">
                            <span>←</span>
                            <input type="date" id="export_date_to">
                        </div>
                        <button class="btn-export-date" onclick="exportByDate()">
                            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
                            تصدير بالتاريخ
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <?php if (isset($_SESSION['message'])): ?>
        <div class="message">✅ <?= htmlspecialchars($_SESSION['message']) ?></div>
        <?php unset($_SESSION['message']); ?>
    <?php endif; ?>
    <?php if (isset($_SESSION['error'])): ?>
        <div class="error">❌ <?= htmlspecialchars($_SESSION['error']) ?></div>
        <?php unset($_SESSION['error']); ?>
    <?php endif; ?>

    <div class="stats-grid">
        <div class="stat-card s-total"><div class="stat-icon">🛒</div><div class="stat-value"><?= $stats['total'] ?></div><div class="stat-label">إجمالي الطلبات</div></div>
        <div class="stat-card s-today"><div class="stat-icon">📅</div><div class="stat-value" id="stat-today"><?= $stats['today'] ?></div><div class="stat-label">طلبات اليوم</div></div>
        <div class="stat-card s-pending"><div class="stat-icon">⏳</div><div class="stat-value"><?= $stats['pending'] ?></div><div class="stat-label">قيد الانتظار</div></div>
        <div class="stat-card s-sent"><div class="stat-icon">🚚</div><div class="stat-value"><?= $stats['sent'] ?></div><div class="stat-label">تم الإرسال</div></div>
        <div class="stat-card s-done"><div class="stat-icon">✅</div><div class="stat-value"><?= $stats['delivered'] ?></div><div class="stat-label">تم التسليم</div></div>
        <div class="stat-card s-revenue"><div class="stat-icon">💰</div><div class="stat-value"><?= $stats['revenue'] >= 1000 ? number_format($stats['revenue']/1000,1).'k' : number_format($stats['revenue']) ?></div><div class="stat-label">الإيرادات (دج)</div></div>
    </div>

    <div class="card">
        <form method="GET" class="search-bar">
            <input type="text" name="search" placeholder="ابحث بالاسم، الهاتف، الولاية..." value="<?= htmlspecialchars($searchQuery) ?>">
            <input type="hidden" name="filter" value="<?= htmlspecialchars($filter) ?>">
            <button type="submit">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>
                بحث
            </button>
        </form>

        <div class="bulk-toolbar" id="bulkToolbar">
            <div class="bulk-count"><span id="bulkCountBadge">0</span> طلب محدد</div>
            <div class="bulk-divider"></div>
            <form method="POST" id="bulkStatusForm" style="display:contents">
                <input type="hidden" name="bulk_change_status" value="1">
                <input type="hidden" name="restore_stock" id="bulkRestoreStock" value="0">
                <div id="bulkCheckboxesStatus"></div>
                <div class="bulk-status-wrap">
                    <label style="font-size:12px;font-weight:700;color:var(--text-2)">تغيير الحالة إلى:</label>
                    <select name="bulk_new_status" id="bulkNewStatus">
                        <option value="">اختر...</option>
                        <option value="1">⏳ انتظار</option>
                        <option value="2">🚚 مرسل</option>
                        <option value="3">✅ مسلّم</option>
                        <option value="4">❌ ملغي</option>
                    </select>
                    <button type="button" class="btn btn-warning btn-sm" onclick="handleBulkStatus()">تطبيق</button>
                </div>
            </form>
            <div class="bulk-divider"></div>
            <form method="POST" id="bulkEcotrackForm" style="display:contents">
                <input type="hidden" name="bulk_send_ecotrack" value="1">
                <div id="bulkCheckboxesEco"></div>
                <button type="submit" class="btn btn-ecotrack btn-sm" onclick="return injectBulkCheckboxes('bulkCheckboxesEco') && confirmBulkEco()">🚀 إرسال إلى Ecotrack</button>
            </form>
        </div>

        <div class="table-responsive">
            <table>
                <thead>
                    <tr>
                        <th style="width:38px;text-align:center">
                            <label class="select-all-wrap" title="تحديد الكل">
                                <input type="checkbox" id="selectAllCheckbox" class="order-checkbox" onchange="toggleSelectAll(this)">
                            </label>
                        </th>
                        <th>#</th>
                        <th>العميل</th>
                        <th>الهاتف</th>
                        <th>الولاية</th>
                        <th>البلدية</th>
                        <th>الخصائص</th>
                        <th>التاريخ</th>
                        <th>الحالة</th>
                        <th>التوصيل</th>
                        <th>الإجمالي</th>
                        <th>رمز التتبع</th>
                        <th>الإجراءات</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (empty($orders)): ?>
                    <tr><td colspan="13"><div class="empty-state"><span class="empty-icon">📭</span><p>لا توجد طلبات للعرض</p></div></td></tr>
                <?php else: ?>
                    <?php foreach ($orders as $order):
                        $items = $orderItems[$order['id']] ?? [];
                        $totalPrice = $orderTotals[$order['id']] ?? 0;
                        $deliveryPrice = $deliveryPrices[$order['id']] ?? 0;
                        $finalTotal = $totalPrice + $deliveryPrice;
                        $communeName = $communeNames[$order['id']] ?? '--';
                        $isDeliveryModified = ($order['delivery_price_modified'] !== null);
                        $trackingCode = $order['tracking_code'] ?? null;
                        $hasApiToken = !empty($order['api_token']);
                        $variantBadges = $orderVariantBadges[$order['id']] ?? [];
                        $companyName = $order['delivery_company_name'] ?? '';
                        $isSent = ($order['status_id'] == 2);
                        $attrColorMap = []; $attrColorIdx = 0;
                        foreach ($variantBadges as $badge) {
                            $key = strtolower($badge['name']);
                            if (!isset($attrColorMap[$key])) { $attrColorMap[$key] = $attrColorIdx % count($attrColorPalette); $attrColorIdx++; }
                        }
                    ?>
                    <tr id="row-<?= $order['id'] ?>">
                        <td style="text-align:center;padding:8px">
                            <input type="checkbox" class="order-checkbox order-select" value="<?= $order['id'] ?>" onchange="onCheckboxChange()" data-order-id="<?= $order['id'] ?>">
                        </td>
                        <td>#<?= $order['id'] ?></td>
                        <td><?= htmlspecialchars($order['customer_name']) ?></td>
                        <td>
                            <div class="phone-badge">📞 <?= htmlspecialchars($order['phone']) ?> <button class="btn-copy" onclick="copyPhone('<?= htmlspecialchars($order['phone']) ?>', this)">📋</button></div>
                            <?php if (!empty($order['phone2'])): ?>
                            <div class="phone-secondary">📞 <?= htmlspecialchars($order['phone2']) ?> <button class="btn-copy" onclick="copyPhone('<?= htmlspecialchars($order['phone2']) ?>', this)">📋</button></div>
                            <?php endif; ?>
                        </td>
                        <td><?= htmlspecialchars($order['wilaya_name'] ?? '--') ?></td>
                        <td><?= htmlspecialchars($communeName) ?></td>
                        <td>
                            <?php if (!empty($variantBadges)): ?>
                                <div class="variant-badges">
                                <?php foreach ($variantBadges as $badge):
                                    $key = strtolower($badge['name']); $ci = $attrColorMap[$key] ?? 0;
                                    $bg = $attrColorPalette[$ci]; $bd = $attrBorderPalette[$ci]; $tc = $attrTextPalette[$ci];
                                    $colorNames = ['أحمر'=>'#EF4444','red'=>'#EF4444','rouge'=>'#EF4444','أخضر'=>'#22C55E','green'=>'#22C55E','vert'=>'#22C55E','أزرق'=>'#3B82F6','blue'=>'#3B82F6','bleu'=>'#3B82F6','أصفر'=>'#EAB308','yellow'=>'#EAB308','أسود'=>'#1F2937','black'=>'#1F2937','noir'=>'#1F2937','أبيض'=>'#E5E7EB','white'=>'#E5E7EB','بنفسجي'=>'#8B5CF6','violet'=>'#8B5CF6','purple'=>'#8B5CF6','وردي'=>'#EC4899','pink'=>'#EC4899','برتقالي'=>'#F97316','orange'=>'#F97316','بني'=>'#92400E','brown'=>'#92400E','رمادي'=>'#6B7280','gray'=>'#6B7280','ذهبي'=>'#F59E0B','gold'=>'#F59E0B','فضي'=>'#9CA3AF','silver'=>'#9CA3AF'];
                                    $dotColor = null; $valLower = mb_strtolower($badge['value']);
                                    foreach ($colorNames as $cn => $hex) { if (mb_strpos($valLower, mb_strtolower($cn)) !== false) { $dotColor = $hex; break; } }
                                ?>
                                    <span class="variant-badge" style="background:<?= $bg ?>;border-color:<?= $bd ?>;color:<?= $tc ?>">
                                        <?php if ($dotColor): ?><span class="variant-badge-dot" style="background:<?= $dotColor ?>;border:1.5px solid rgba(0,0,0,0.15)"></span><?php else: ?><span style="font-size:9px">🏷</span><?php endif; ?>
                                        <?= htmlspecialchars($badge['value']) ?>
                                    </span>
                                <?php endforeach; ?>
                                </div>
                            <?php else: ?><span class="variant-empty">—</span><?php endif; ?>
                        </td>
                        <td style="white-space:nowrap;font-size:12px;color:var(--text-3)"><?= date('Y-m-d H:i', strtotime($order['order_date'])) ?></td>

                        <!-- ═══ خانة الحالة — تُظهر اسم الشركة عند "مرسل" ═══ -->
                        <td>
                            <div class="status-cell">
                                <select class="status-select"
                                    id="status-select-<?= $order['id'] ?>"
                                    onchange="handleStatusChange(this, <?= $order['id'] ?>)"
                                    style="<?php
                                        if($order['status_id']==1) echo 'background:#FEF3C7;color:#D97706;border-color:#FDE68A';
                                        elseif($order['status_id']==2) echo 'background:#EDE9FE;color:#7C3AED;border-color:#DDD6FE';
                                        elseif($order['status_id']==3) echo 'background:#D1FAE5;color:#059669;border-color:#A7F3D0';
                                        else echo 'background:#FEE2E2;color:#DC2626;border-color:#FECACA';
                                    ?>"
                                    data-current="<?= $order['status_id'] ?>">
                                    <option value="1" <?= $order['status_id']==1?'selected':'' ?>>⏳ انتظار</option>
                                    <option value="2" <?= $order['status_id']==2?'selected':'' ?>>🚚 مرسل</option>
                                    <option value="3" <?= $order['status_id']==3?'selected':'' ?>>✅ مسلّم</option>
                                    <option value="4" <?= $order['status_id']==4?'selected':'' ?>>❌ ملغي</option>
                                </select>

                                <!-- بادج اسم الشركة — يظهر فقط إذا كانت الحالة "مرسل" -->
                                <?php if (!empty($companyName)): ?>
                                <span class="company-badge <?= $isSent ? 'visible' : '' ?>"
                                      id="company-badge-<?= $order['id'] ?>"
                                      title="شركة التوصيل المختارة">
                                    <span class="company-badge-dot"></span>
                                    <?= htmlspecialchars($companyName) ?>
                                </span>
                                <?php endif; ?>
                            </div>
                        </td>

                        <td>
                            <?php if ($isDeliveryModified): ?>
                                <span class="delivery-cost-modified"><?= $deliveryPrice==0 ? '🎁 مجاني' : number_format($deliveryPrice,2).' دج' ?></span>
                                <span class="delivery-modified">معدل</span>
                            <?php elseif ($deliveryPrice==0): ?>
                                <span class="delivery-cost-free">🎁 مجاني</span>
                            <?php else: ?>
                                <span class="delivery-cost"><?= number_format($deliveryPrice,2) ?> دج</span>
                            <?php endif; ?>
                        </td>
                        <td><strong style="color:var(--primary)"><?= number_format($finalTotal,2) ?> دج</strong></td>
                        <td>
                            <?php if ($trackingCode): ?>
                                <span class="tracking-badge">🔍 <a href="https://navexdelivery.ecotrack.dz/track/<?= urlencode($trackingCode) ?>" target="_blank"><?= htmlspecialchars($trackingCode) ?></a> <button class="btn-copy" onclick="copyPhone('<?= htmlspecialchars($trackingCode) ?>', this)">📋</button></span>
                            <?php elseif ($order['status_id'] == 2 && $hasApiToken): ?>
                                <span class="no-tracking" title="لم يُرسل إلى Ecotrack بعد">⚠️ لا يوجد</span>
                            <?php else: ?>
                                <span class="no-tracking">—</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <div class="action-buttons">
                                <button onclick="openDetailsModal(<?= $order['id'] ?>)" class="btn btn-info btn-sm" title="تفاصيل">👁</button>
                                <button onclick="openEditModal(<?= $order['id'] ?>)" class="btn btn-edit btn-sm" title="تعديل">✏️</button>
                                <button onclick="openItemsModal(<?= $order['id'] ?>)" class="btn btn-primary btn-sm" title="المنتجات">📦 (<?= count($items) ?>)</button>
                                <button onclick="openDeliveryPriceModal(<?= $order['id'] ?>)" class="btn btn-delivery-edit btn-sm" title="تعديل التوصيل">🚚</button>
                                <button onclick="confirmDeleteOrder(<?= $order['id'] ?>)" class="btn btn-danger btn-sm" title="حذف">🗑️</button>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- ═══ STOCK RESTORE MODAL ═══ -->
<div class="sr-modal" id="srModal">
    <div class="sr-box">
        <div class="sr-header">
            <div class="sr-icon" id="srIcon">🗑️</div>
            <div class="sr-title" id="srTitle">تأكيد الحذف</div>
            <div class="sr-sub" id="srSub">هل أنت متأكد من هذه العملية؟</div>
        </div>
        <div class="sr-divider"></div>
        <div class="sr-body">
            <div class="sr-question">📦 ماذا تريد أن تفعل بالمخزون؟</div>
            <div class="sr-options">
                <label class="sr-option selected-opt" id="srOptYes" onclick="selectSrOpt(1)">
                    <input type="radio" name="sr_restore" value="1" checked>
                    <div class="sr-option-icon yes">🔄</div>
                    <div class="sr-option-text">
                        <strong>إرجاع الكمية للمخزون</strong>
                        <small>سيتم إضافة كمية المنتجات مرة أخرى إلى المخزون</small>
                    </div>
                </label>
                <label class="sr-option" id="srOptNo" onclick="selectSrOpt(0)">
                    <input type="radio" name="sr_restore" value="0">
                    <div class="sr-option-icon no">❌</div>
                    <div class="sr-option-text">
                        <strong>عدم إرجاع المخزون</strong>
                        <small>سيبقى المخزون كما هو دون تغيير</small>
                    </div>
                </label>
            </div>
        </div>
        <div class="sr-footer">
            <button class="btn sr-btn-abort" onclick="closeSrModal()">إلغاء</button>
            <button class="btn" id="srConfirmBtn" onclick="executeSrAction()">تأكيد</button>
        </div>
    </div>
</div>

<!-- General Modals -->
<div id="detailsModal" class="modal">
    <div class="modal-content">
        <div class="modal-header"><h2>👁 تفاصيل الطلب</h2><span class="close" onclick="closeModal('detailsModal')">×</span></div>
        <div id="detailsContent"></div>
        <div class="modal-footer"><button class="btn btn-danger" onclick="closeModal('detailsModal')">إغلاق</button></div>
    </div>
</div>

<div id="itemsModal" class="modal">
    <div class="modal-content">
        <div class="modal-header"><h2>📦 منتجات الطلب</h2><span class="close" onclick="closeModal('itemsModal')">×</span></div>
        <div id="itemsContent"></div>
        <div class="modal-footer"><button class="btn btn-danger" onclick="closeModal('itemsModal')">إغلاق</button></div>
    </div>
</div>

<div id="editItemModal" class="modal">
    <div class="modal-content" style="max-width:520px">
        <div class="modal-header"><h2>✏️ تعديل المنتج</h2><span class="close" onclick="closeModal('editItemModal')">×</span></div>
        <form method="post" onsubmit="event.preventDefault(); saveEditedItem();">
            <input type="hidden" name="edit_order_item" value="1">
            <input type="hidden" name="item_id" id="edit_item_id">
            <input type="hidden" name="order_id" id="edit_item_order_id">
            <div class="form-group"><label>اسم المنتج:</label><div id="edit_item_name" style="font-weight:700;padding:10px;background:var(--surface-2);border-radius:var(--radius-sm);border:1px solid var(--border)"></div></div>
            <div class="form-group"><label>الخصائص الحالية:</label><div id="edit_current_attributes" style="padding:10px;background:var(--surface-2);border-radius:var(--radius-sm);border:1px solid var(--border)"></div></div>
            <div class="form-group"><label>تعديل الخصائص:</label><div id="edit_attributes_container"></div></div>
            <div class="form-row">
                <div class="form-group"><label>السعر الجديد (دج):</label><input type="number" name="new_price" id="edit_new_price" step="0.01" min="0" required></div>
                <div class="form-group"><label>الكمية الجديدة:</label><input type="number" name="new_quantity" id="edit_new_quantity" min="1" value="1" required></div>
            </div>
            <div class="modal-footer"><button type="button" class="btn btn-danger" onclick="closeModal('editItemModal')">إلغاء</button><button type="submit" class="btn btn-success">💾 حفظ</button></div>
        </form>
    </div>
</div>

<div id="editDeliveryPriceModal" class="modal">
    <div class="modal-content" style="max-width:450px">
        <div class="modal-header"><h2>🚚 تعديل سعر التوصيل</h2><span class="close" onclick="closeModal('editDeliveryPriceModal')">×</span></div>
        <form method="post">
            <input type="hidden" name="update_delivery_price" value="1">
            <input type="hidden" name="order_id" id="delivery_order_id">
            <div class="form-group"><label>السعر الجديد (دج):</label><input type="number" name="new_delivery_price" id="new_delivery_price" step="0.01" min="0" placeholder="0 = مجاني"><small style="color:var(--text-3);margin-top:6px;display:block">أدخل 0 لجعل التوصيل مجانياً</small></div>
            <div class="modal-footer"><button type="button" class="btn btn-danger" onclick="closeModal('editDeliveryPriceModal')">إلغاء</button><button type="submit" class="btn btn-success">💾 حفظ</button></div>
        </form>
    </div>
</div>

<div id="editModal" class="modal">
    <div class="modal-content">
        <div class="modal-header"><h2>✏️ تعديل الطلب</h2><span class="close" onclick="closeModal('editModal')">×</span></div>
        <form method="post">
            <input type="hidden" name="order_id" id="edit_order_id">
            <input type="hidden" name="update_order" value="1">
            <div class="form-row">
                <div class="form-group"><label>اسم العميل:</label><input type="text" name="customer_name" id="edit_customer_name" required></div>
                <div class="form-group"><label>الهاتف الأساسي:</label><input type="tel" name="phone" id="edit_phone" required></div>
            </div>
            <div class="form-row">
                <div class="form-group"><label>هاتف إضافي:</label><input type="tel" name="phone2" id="edit_phone2"></div>
                <div class="form-group"><label>الولاية:</label>
                    <select name="wilaya_id" id="edit_wilaya_id" required onchange="loadCommunes(this.value)">
                        <option value="">اختر الولاية</option>
                        <?php foreach ($wilayas as $wilaya): ?><option value="<?= $wilaya['id'] ?>"><?= htmlspecialchars($wilaya['name']) ?></option><?php endforeach; ?>
                    </select>
                </div>
            </div>
            <div class="form-row">
                <div class="form-group"><label>البلدية:</label><select name="municipality" id="edit_municipality"><option value="">اختر البلدية</option></select></div>
                <div class="form-group"><label>نوع التوصيل:</label><select name="delivery_type" id="edit_delivery_type"><option value="home">🏠 توصيل للمنزل</option><option value="office">🏢 توصيل للمكتب</option></select></div>
            </div>
            <div class="form-group"><label>العنوان:</label><textarea name="address" id="edit_address" rows="3"></textarea></div>
            <div class="modal-footer"><button type="button" class="btn btn-danger" onclick="closeModal('editModal')">إلغاء</button><button type="submit" class="btn btn-success">💾 حفظ</button></div>
        </form>
    </div>
</div>

<!-- Hidden Forms -->
<form id="deleteSingleOrderForm" method="POST" style="display:none">
    <input type="hidden" name="delete_single_order" value="1">
    <input type="hidden" name="order_id" id="delete_single_order_id">
    <input type="hidden" name="restore_stock" id="delete_order_restore_stock" value="0">
</form>
<form id="deleteSingleItemForm" method="POST" style="display:none">
    <input type="hidden" name="delete_single_item" value="1">
    <input type="hidden" name="item_id" id="delete_single_item_id">
    <input type="hidden" name="order_id" id="delete_item_order_id">
    <input type="hidden" name="restore_stock" id="delete_item_restore_stock" value="0">
</form>
<form id="changeStatusForm" method="POST" style="display:none">
    <input type="hidden" name="change_order_status" value="1">
    <input type="hidden" name="order_id" id="status_form_order_id">
    <input type="hidden" name="new_status" id="status_form_new_status">
    <input type="hidden" name="restore_stock" id="status_form_restore_stock" value="0">
</form>

<!-- TOAST -->
<div id="notif-toast">
    <div class="toast-inner">
        <div class="toast-icon">🔔</div>
        <div class="toast-body">
            <div class="toast-title">طلب جديد وصل!</div>
            <div class="toast-message" id="toast-msg">تم استلام طلب جديد في متجرك</div>
        </div>
        <button class="toast-close" onclick="dismissToast()">×</button>
        <div class="toast-progress"></div>
    </div>
</div>

<script>
var orders            = <?= json_encode($orders) ?>;
var orderItems        = <?= json_encode($orderItems) ?>;
var orderTotals       = <?= json_encode($orderTotals) ?>;
var deliveryPrices    = <?= json_encode($deliveryPrices) ?>;
var allCommunes       = <?= json_encode($allCommunes) ?>;
var communeNames      = <?= json_encode($communeNames) ?>;
var productAttributes = <?= json_encode($productAttributes) ?>;

var communesMap = {};
for (var wilayaId in allCommunes) { communesMap[wilayaId] = allCommunes[wilayaId]; }
allCommunes = communesMap;

// ============================================================
//  STOCK RESTORE MODAL — State
// ============================================================
var srState = {
    mode:       null,
    orderId:    null,
    itemId:     null,
    newStatus:  null,
    restore:    1,
    selectEl:   null,
    oldStatus:  null
};

function selectSrOpt(val) {
    srState.restore = val;
    document.getElementById('srOptYes').classList.toggle('selected-opt', val === 1);
    document.getElementById('srOptNo').classList.toggle('selected-opt', val === 0);
}

function closeSrModal() {
    document.getElementById('srModal').classList.remove('open');
    if (srState.mode === 'cancel_status' && srState.selectEl) {
        srState.selectEl.value = srState.oldStatus;
        updateSelectStyle(srState.selectEl, srState.oldStatus);
        // أُعِد إظهار بادج الشركة إذا كانت الحالة القديمة "مرسل"
        updateCompanyBadge(srState.orderId, srState.oldStatus);
    }
    srState = { mode:null, orderId:null, itemId:null, newStatus:null, restore:1, selectEl:null, oldStatus:null };
}

function openSrModal(title, sub, iconEmoji, iconClass, confirmLabel, confirmClass) {
    document.getElementById('srTitle').textContent = title;
    document.getElementById('srSub').textContent   = sub;
    document.getElementById('srIcon').textContent  = iconEmoji;
    document.getElementById('srIcon').className    = 'sr-icon ' + iconClass;
    var btn = document.getElementById('srConfirmBtn');
    btn.textContent = confirmLabel;
    btn.className   = 'btn ' + confirmClass;
    selectSrOpt(1);
    document.getElementById('srModal').classList.add('open');
}

function executeSrAction() {
    var restore = srState.restore;
    if (srState.mode === 'delete_order') {
        document.getElementById('delete_single_order_id').value      = srState.orderId;
        document.getElementById('delete_order_restore_stock').value  = restore;
        document.getElementById('deleteSingleOrderForm').submit();
    } else if (srState.mode === 'delete_item') {
        document.getElementById('delete_single_item_id').value      = srState.itemId;
        document.getElementById('delete_item_order_id').value       = srState.orderId;
        document.getElementById('delete_item_restore_stock').value  = restore;
        document.getElementById('deleteSingleItemForm').submit();
    } else if (srState.mode === 'cancel_status') {
        document.getElementById('status_form_order_id').value     = srState.orderId;
        document.getElementById('status_form_new_status').value   = srState.newStatus;
        document.getElementById('status_form_restore_stock').value = restore;
        document.getElementById('changeStatusForm').submit();
    }
    document.getElementById('srModal').classList.remove('open');
}

// ============================================================
//  إظهار / إخفاء بادج الشركة حسب الحالة
// ============================================================
function updateCompanyBadge(orderId, statusId) {
    var badge = document.getElementById('company-badge-' + orderId);
    if (!badge) return;
    if (parseInt(statusId) === 2) {
        badge.classList.add('visible');
    } else {
        badge.classList.remove('visible');
    }
}

// تحديث لون الـ select
function updateSelectStyle(sel, statusId) {
    var styles = {
        1: 'background:#FEF3C7;color:#D97706;border-color:#FDE68A',
        2: 'background:#EDE9FE;color:#7C3AED;border-color:#DDD6FE',
        3: 'background:#D1FAE5;color:#059669;border-color:#A7F3D0',
        4: 'background:#FEE2E2;color:#DC2626;border-color:#FECACA'
    };
    sel.style.cssText = styles[statusId] || '';
}

// ============================================================
//  Trigger points
// ============================================================
function confirmDeleteOrder(orderId) {
    srState.mode    = 'delete_order';
    srState.orderId = orderId;
    openSrModal('حذف الطلب #' + orderId, 'سيتم حذف الطلب وجميع منتجاته نهائياً.', '🗑️', 'danger', '🗑️ تأكيد الحذف', 'sr-btn-confirm-danger');
}

function deleteSingleItem(itemId, orderId) {
    srState.mode    = 'delete_item';
    srState.itemId  = itemId;
    srState.orderId = orderId;
    openSrModal('حذف المنتج من الطلب', 'سيتم حذف هذا المنتج من الطلب #' + orderId + '.', '📦', 'danger', '🗑️ تأكيد الحذف', 'sr-btn-confirm-danger');
}

function handleStatusChange(selectEl, orderId) {
    var newStatus = parseInt(selectEl.value);
    var oldStatus = parseInt(selectEl.getAttribute('data-current'));

    // تحديث لون الـ select فوراً
    updateSelectStyle(selectEl, newStatus);
    // تحديث بادج الشركة فوراً (سيُصحَّح من السيرفر عند reload)
    updateCompanyBadge(orderId, newStatus);

    if (newStatus === 4) {
        srState.mode      = 'cancel_status';
        srState.orderId   = orderId;
        srState.newStatus = 4;
        srState.selectEl  = selectEl;
        srState.oldStatus = oldStatus;
        openSrModal('إلغاء الطلب #' + orderId, 'سيتم تغيير حالة الطلب إلى "ملغي".', '❌', 'cancel', '✅ تأكيد الإلغاء', 'sr-btn-confirm-cancel');
    } else {
        document.getElementById('status_form_order_id').value     = orderId;
        document.getElementById('status_form_new_status').value   = newStatus;
        document.getElementById('status_form_restore_stock').value = 0;
        document.getElementById('changeStatusForm').submit();
    }
}

// ============================================================
//  BULK SELECT
// ============================================================
function getSelectedIds() {
    return Array.from(document.querySelectorAll('.order-select:checked')).map(function(cb) { return cb.value; });
}
function onCheckboxChange() {
    var ids = getSelectedIds(); var count = ids.length;
    document.getElementById('bulkCountBadge').textContent = count;
    document.getElementById('bulkToolbar').classList.toggle('visible', count > 0);
    document.querySelectorAll('.order-select').forEach(function(cb) {
        var row = document.getElementById('row-' + cb.value);
        if (row) row.classList.toggle('selected-row', cb.checked);
    });
    var total = document.querySelectorAll('.order-select').length;
    var masterCb = document.getElementById('selectAllCheckbox');
    masterCb.checked       = (count === total && total > 0);
    masterCb.indeterminate = (count > 0 && count < total);
    if (count === 0) masterCb.checked = false;
}
function toggleSelectAll(masterCb) {
    document.querySelectorAll('.order-select').forEach(function(cb) { cb.checked = masterCb.checked; });
    onCheckboxChange();
}
function injectBulkCheckboxes(containerId) {
    var ids = getSelectedIds();
    if (ids.length === 0) { alert('يرجى تحديد طلب واحد على الأقل'); return false; }
    var container = document.getElementById(containerId);
    container.innerHTML = '';
    ids.forEach(function(id) {
        var inp = document.createElement('input'); inp.type='hidden'; inp.name='selected_orders[]'; inp.value=id;
        container.appendChild(inp);
    });
    return true;
}

function handleBulkStatus() {
    var status = document.getElementById('bulkNewStatus').value;
    if (!status) { alert('اختر الحالة المراد التغيير إليها'); return; }
    if (!injectBulkCheckboxes('bulkCheckboxesStatus')) return;
    if (status == 4) {
        if (!confirm('تغيير حالة ' + getSelectedIds().length + ' طلب إلى ملغي؟')) return;
        var restoreAns = confirm('هل تريد إرجاع كميات المنتجات إلى المخزون؟\n\nاضغط "موافق" للإرجاع، أو "إلغاء" للإبقاء على المخزون كما هو.');
        document.getElementById('bulkRestoreStock').value = restoreAns ? 1 : 0;
    } else {
        if (!confirm('تغيير حالة ' + getSelectedIds().length + ' طلب؟')) return;
        document.getElementById('bulkRestoreStock').value = 0;
    }
    document.getElementById('bulkStatusForm').submit();
}
function confirmBulkEco() {
    return confirm('إرسال ' + getSelectedIds().length + ' طلب إلى Ecotrack؟\nسيتم تغيير حالتهم إلى "مرسل" تلقائياً.');
}

// ============================================================
//  EXPORT
// ============================================================
function toggleExportMenu(e) { e.stopPropagation(); document.getElementById('exportMenu').classList.toggle('open'); }
document.addEventListener('click', function(e) { var wrap = document.getElementById('exportWrap'); if (wrap && !wrap.contains(e.target)) document.getElementById('exportMenu').classList.remove('open'); });
function exportByDate() {
    var from = document.getElementById('export_date_from').value; var to = document.getElementById('export_date_to').value;
    if (!from && !to) { alert('اختر تاريخاً'); return; }
    var url = 'export_orders.php?filter=all';
    if (from) url += '&date_from=' + from;
    if (to)   url += '&date_to='   + to;
    window.location.href = url;
}

function copyPhone(text, btn) {
    navigator.clipboard.writeText(text).then(function() {
        var orig = btn.innerHTML; btn.innerHTML = '✓'; btn.style.background='#059669'; btn.style.color='white';
        setTimeout(function() { btn.innerHTML=orig; btn.style.background=''; btn.style.color=''; }, 1800);
    });
}

function escapeHtml(text) {
    if (!text) return '';
    var d = document.createElement('div'); d.textContent = text; return d.innerHTML;
}
function formatAttributes(val) {
    if (!val || val === '[]') return '<span style="color:#aaa;font-style:italic">بدون خصائص</span>';
    try {
        var attrs = JSON.parse(val); var html = '<div style="display:flex;flex-wrap:wrap;gap:6px;margin-top:6px">';
        for (var k in attrs) { html += '<span style="background:#EFF6FF;color:#1E40AF;padding:4px 12px;border-radius:20px;font-size:12px;font-weight:700">'+escapeHtml(k)+': '+escapeHtml(attrs[k])+'</span>'; }
        return html + '</div>';
    } catch(e) { return escapeHtml(val); }
}
function createAttributesInputs(productId, selectedJson) {
    var sel = {}; try { sel = JSON.parse(selectedJson) || {}; } catch(e) {}
    var attrs = productAttributes[productId] || [];
    if (!attrs.length) return '<p style="color:#aaa;font-style:italic">لا توجد خصائص</p>';
    var html = '';
    attrs.forEach(function(attr) {
        html += '<div style="margin-bottom:10px"><label style="display:block;margin-bottom:5px;font-weight:700;font-size:13px">'+escapeHtml(attr.name)+'</label>';
        if (attr.input_type === 'select' && attr.values_list) {
            html += '<select class="attribute-select" data-attr-name="'+escapeHtml(attr.name)+'" style="width:100%;padding:9px;border-radius:8px;border:1.5px solid #E2E8F0;font-family:Tajawal,sans-serif"><option value="">اختر...</option>';
            attr.values_list.split(',').forEach(function(v) { v=v.trim(); html += '<option value="'+escapeHtml(v)+'"'+(sel[attr.name]===v?' selected':'')+'>'+escapeHtml(v)+'</option>'; });
            html += '</select>';
        } else {
            html += '<input type="text" class="attribute-input" data-attr-name="'+escapeHtml(attr.name)+'" value="'+escapeHtml(sel[attr.name]||'')+'" style="width:100%;padding:9px;border-radius:8px;border:1.5px solid #E2E8F0;font-family:Tajawal,sans-serif">';
        }
        html += '</div>';
    });
    return html;
}

function closeModal(id) { document.getElementById(id).style.display = 'none'; }
window.onclick = function(e) { if (e.target.classList.contains('modal')) e.target.style.display='none'; };

function infoRow(label, value, copyVal) {
    var cv = copyVal !== undefined ? copyVal : value; var canCopy = cv && cv !== '--';
    var copyBtn = canCopy ? '<button onclick="copyInfo(this,\''+cv.replace(/'/g,"\\'")+'\')\" style="margin-right:6px;background:#EFF6FF;color:#1E40AF;border:1px solid #BFDBFE;border-radius:6px;padding:2px 8px;font-size:11px;font-weight:700;cursor:pointer;font-family:Tajawal,sans-serif">📋 نسخ</button>' : '';
    return '<div class="info-item"><span class="info-label">'+label+'</span><span class="info-value" style="display:flex;align-items:center;justify-content:space-between;gap:6px"><span>'+escapeHtml(value)+'</span>'+copyBtn+'</span></div>';
}
function copyInfo(btn, text) {
    navigator.clipboard.writeText(text).then(function() {
        var orig = btn.innerHTML; btn.innerHTML='✅ تم'; btn.style.background='#D1FAE5'; btn.style.color='#059669';
        setTimeout(function() { btn.innerHTML=orig; btn.style.background=''; btn.style.color=''; }, 2000);
    });
}

function openDetailsModal(orderId) {
    var order = orders.find(function(o) { return o.id == orderId; });
    var items = orderItems[orderId] || []; var total = orderTotals[orderId] || 0; var delivery = deliveryPrices[orderId] || 0;
    var commune = communeNames[orderId] || '--';
    var statusMap = {1:'⏳ قيد الانتظار',2:'🚚 تم الإرسال',3:'✅ تم التسليم',4:'❌ ملغي'};
    var deliveryLabel = order.delivery_type=='home' ? '🏠 للمنزل' : '🏢 للمكتب';
    var html = '<div class="customer-info-section"><h3 style="margin:0 0 14px">👤 معلومات العميل</h3><div class="customer-info-grid">';
    html += infoRow('الاسم', order.customer_name || '--');
    html += infoRow('الهاتف', order.phone || '--');
    if (order.phone2) html += infoRow('هاتف إضافي', order.phone2);
    html += infoRow('الولاية', order.wilaya_name || '--');
    html += infoRow('البلدية', commune);
    html += infoRow('العنوان', order.address || '--');
    html += infoRow('نوع التوصيل', deliveryLabel);
    html += infoRow('الحالة', statusMap[order.status_id] || '--');
    html += infoRow('التاريخ', order.order_date || '--');
    html += infoRow('شركة التوصيل', order.delivery_company_name || '--');
    if (order.tracking_code) html += infoRow('رمز التتبع', order.tracking_code);
    html += '</div></div>';
    if (items.length) {
        html += '<h3 style="margin:16px 0 12px;font-weight:800">📦 المنتجات</h3>';
        html += '<table class="products-table"><thead><tr><th>المنتج</th><th>الخصائص</th><th>الكمية</th><th>السعر</th><th>الإجمالي</th></tr></thead><tbody>';
        items.forEach(function(item) { html += '<tr><td>'+escapeHtml(item.product_name||'منتج')+'</td><td>'+formatAttributes(item.selected_attribute_value)+'</td><td>'+item.quantity+'</td><td>'+Number(item.unit_price).toFixed(2)+' دج</td><td>'+(item.quantity*item.unit_price).toFixed(2)+' دج</td></tr>'; });
        html += '</tbody></table>';
    }
    html += '<div class="summary-section"><h3>ملخص الطلب</h3>';
    html += '<div class="summary-row"><span>إجمالي المنتجات</span><span>'+total.toFixed(2)+' دج</span></div>';
    html += '<div class="summary-row"><span>التوصيل</span><span>'+(delivery==0?'مجاني':delivery.toFixed(2)+' دج')+'</span></div>';
    html += '<div class="summary-row total"><span>الإجمالي الكلي</span><span>'+(total+delivery).toFixed(2)+' دج</span></div></div>';
    document.getElementById('detailsContent').innerHTML = html;
    document.getElementById('detailsModal').style.display = 'flex';
}

function openItemsModal(orderId) {
    var items = orderItems[orderId] || [];
    if (!items.length) { alert('لا توجد منتجات في هذا الطلب'); return; }
    var html = '<div class="items-list">';
    items.forEach(function(item) {
        html += '<div class="item-row"><div class="item-header"><div class="item-info"><strong>'+escapeHtml(item.product_name||'منتج')+'</strong><br><small style="color:var(--text-3)">الكمية: '+item.quantity+' | السعر: '+Number(item.unit_price).toFixed(2)+' دج</small></div>';
        html += '<div class="item-actions"><button class="edit-item-btn" onclick="openEditItemModal('+item.id+','+orderId+','+item.product_id+')">✏️ تعديل</button>';
        html += '<button class="delete-item-btn" onclick="deleteSingleItem('+item.id+','+orderId+')">🗑️ حذف</button></div></div>';
        if (item.selected_attribute_value && item.selected_attribute_value !== '[]') {
            html += '<div class="item-attributes"><strong style="font-size:12px;color:var(--primary)">🏷️ الخصائص:</strong>'+formatAttributes(item.selected_attribute_value)+'</div>';
        }
        html += '</div>';
    });
    html += '</div>';
    document.getElementById('itemsContent').innerHTML = html;
    document.getElementById('itemsModal').style.display = 'flex';
}

function openEditItemModal(itemId, orderId, productId) {
    var items = orderItems[orderId] || []; var item = items.find(function(i) { return i.id == itemId; });
    if (!item) return;
    document.getElementById('edit_item_id').value = itemId;
    document.getElementById('edit_item_order_id').value = orderId;
    document.getElementById('edit_item_name').textContent = item.product_name || 'منتج';
    document.getElementById('edit_new_price').value = item.unit_price;
    document.getElementById('edit_new_quantity').value = item.quantity;
    document.getElementById('edit_current_attributes').innerHTML = formatAttributes(item.selected_attribute_value);
    document.getElementById('edit_attributes_container').innerHTML = createAttributesInputs(productId, item.selected_attribute_value);
    document.getElementById('editItemModal').style.display = 'flex';
}

function saveEditedItem() {
    var itemId=document.getElementById('edit_item_id').value, orderId=document.getElementById('edit_item_order_id').value;
    var newPrice=document.getElementById('edit_new_price').value, newQty=document.getElementById('edit_new_quantity').value;
    if (!newPrice||parseFloat(newPrice)<=0) { alert('أدخل سعراً صحيحاً'); return; }
    if (!newQty||parseInt(newQty)<=0)       { alert('أدخل كمية صحيحة');  return; }
    var selectedAttrs = {};
    document.querySelectorAll('#edit_attributes_container .attribute-select').forEach(function(s) { if (s.value) selectedAttrs[s.getAttribute('data-attr-name')]=s.value; });
    document.querySelectorAll('#edit_attributes_container .attribute-input').forEach(function(i)  { if (i.value.trim()) selectedAttrs[i.getAttribute('data-attr-name')]=i.value.trim(); });
    if (!confirm('تأكيد تعديل المنتج؟')) return;
    var f=document.createElement('form'); f.method='POST'; f.style.display='none';
    var fields={edit_order_item:'1',item_id:itemId,order_id:orderId,new_price:newPrice,new_quantity:newQty,selected_attributes:JSON.stringify(selectedAttrs)};
    for (var k in fields) { var inp=document.createElement('input'); inp.type='hidden'; inp.name=k; inp.value=fields[k]; f.appendChild(inp); }
    document.body.appendChild(f); f.submit();
}

function openDeliveryPriceModal(orderId) {
    document.getElementById('delivery_order_id').value = orderId;
    document.getElementById('new_delivery_price').value = '';
    document.getElementById('editDeliveryPriceModal').style.display = 'flex';
}

function openEditModal(orderId) {
    var order = orders.find(function(o) { return o.id == orderId; });
    if (!order) return;
    document.getElementById('edit_order_id').value = order.id;
    document.getElementById('edit_customer_name').value = order.customer_name || '';
    document.getElementById('edit_phone').value = order.phone || '';
    document.getElementById('edit_phone2').value = order.phone2 || '';
    document.getElementById('edit_address').value = order.address || '';
    document.getElementById('edit_wilaya_id').value = order.wilaya_id || '';
    document.getElementById('edit_delivery_type').value = order.delivery_type || 'home';
    var selectedCommune = order.commune_id || communeNames[orderId] || '';
    if (order.wilaya_id) loadCommunes(order.wilaya_id, selectedCommune);
    document.getElementById('editModal').style.display = 'flex';
}

function loadCommunes(wilayaId, selected) {
    var sel = document.getElementById('edit_municipality');
    sel.innerHTML = '<option value="">اختر البلدية</option>';
    if (wilayaId && allCommunes[wilayaId]) {
        allCommunes[wilayaId].forEach(function(c) {
            var o = document.createElement('option');
            o.value = c.id; o.textContent = c.name + (c.arabic_name && c.arabic_name !== c.name ? ' / '+c.arabic_name : '');
            if (selected && (selected == c.id || selected === c.name || selected === c.arabic_name)) o.selected = true;
            sel.appendChild(o);
        });
    }
}

/* TOAST */
var lastKnownId = parseInt(localStorage.getItem('last_order_id') || '<?= $lastOrderId ?>');
var toastTimer  = null;

function playSound() {
    try {
        var ctx = new (window.AudioContext || window.webkitAudioContext)();
        [[0,880],[0.15,1100],[0.3,1320]].forEach(function(p) {
            var osc=ctx.createOscillator(), g=ctx.createGain();
            osc.connect(g); g.connect(ctx.destination);
            osc.frequency.value=p[1];
            g.gain.setValueAtTime(0.25,ctx.currentTime+p[0]);
            g.gain.exponentialRampToValueAtTime(0.001,ctx.currentTime+p[0]+0.2);
            osc.start(ctx.currentTime+p[0]); osc.stop(ctx.currentTime+p[0]+0.25);
        });
    } catch(e) {}
}
function showToast(msg) {
    var toast = document.getElementById('notif-toast');
    document.getElementById('toast-msg').textContent = msg;
    toast.style.animation='none'; toast.style.display='none';
    void toast.offsetWidth;
    toast.style.animation=''; toast.style.display='block';
    var prog = toast.querySelector('.toast-progress');
    if (prog) { prog.style.animation='none'; void prog.offsetWidth; prog.style.animation='toastProgress 6s linear forwards'; }
    playSound();
    clearTimeout(toastTimer);
    toastTimer = setTimeout(dismissToast, 6000);
}
function dismissToast() {
    var t = document.getElementById('notif-toast');
    t.style.transition='opacity 0.3s,transform 0.3s'; t.style.opacity='0'; t.style.transform='translateX(-20px)';
    setTimeout(function() { t.style.display='none'; t.style.opacity=''; t.style.transform=''; t.style.transition=''; }, 320);
    clearTimeout(toastTimer);
}
function checkNewOrders() {
    fetch('check_new_orders.php?last_id=' + lastKnownId)
        .then(function(r) { return r.json(); })
        .then(function(data) {
            if (data.new_count > 0) {
                showToast(data.new_count===1 ? 'وصل طلب جديد! رقم #'+data.latest_id : 'وصلت '+data.new_count+' طلبات جديدة!');
                lastKnownId = data.latest_id;
                localStorage.setItem('last_order_id', lastKnownId);
                var el = document.getElementById('stat-today');
                if (el && data.today_count !== undefined) el.textContent = data.today_count;
            }
        }).catch(function() {});
}
localStorage.setItem('last_order_id', <?= $lastOrderId ?>);
lastKnownId = <?= $lastOrderId ?>;
setInterval(checkNewOrders, 30000);
</script>
<script>window.__lastOrderId = <?= $lastOrderId ?>;</script>
<script src="notifications.js"></script>
</body>
</html>