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

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

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

// ===== تأكد من وجود جدول المحذوفات =====
$pdo->exec("
CREATE TABLE IF NOT EXISTS `deleted_orders` (
  `id`                            INT(11) NOT NULL AUTO_INCREMENT,
  `original_order_id`             INT(11) NOT NULL,
  `customer_name`                 VARCHAR(100) NOT NULL,
  `phone`                         VARCHAR(20) NOT NULL,
  `phone2`                        VARCHAR(20) DEFAULT NULL,
  `address`                       TEXT NOT NULL,
  `municipality`                  VARCHAR(255) DEFAULT NULL,
  `order_date`                    DATETIME NOT NULL,
  `status_id`                     INT(11) NOT NULL DEFAULT 1,
  `delivery_company_id`           INT(11) DEFAULT NULL,
  `delivery_price_id`             INT(11) DEFAULT NULL,
  `delivery_price_modified`       DECIMAL(10,2) DEFAULT NULL,
  `original_delivery_price`       DECIMAL(10,2) DEFAULT NULL,
  `tracking_number`               VARCHAR(100) DEFAULT NULL,
  `sent_date`                     DATETIME DEFAULT NULL,
  `wilaya_id`                     INT(11) DEFAULT NULL,
  `commune_id`                    INT(11) DEFAULT NULL,
  `delivery_type`                 ENUM('home','office') NOT NULL DEFAULT 'home',
  `tracking_code`                 VARCHAR(100) DEFAULT NULL,
  `shipping_status`               VARCHAR(30) DEFAULT NULL,
  `api_response`                  TEXT DEFAULT NULL,
  `deleted_at`                    DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `deleted_by`                    VARCHAR(100) DEFAULT NULL,
  `delete_reason`                 VARCHAR(255) DEFAULT NULL,
  `expires_at`                    DATETIME NOT NULL,
  `order_items_json`              LONGTEXT DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `expires_at` (`expires_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci
");

// ===== حذف نهائي تلقائي للمنتهية الصلاحية =====
$pdo->exec("DELETE FROM deleted_orders WHERE expires_at <= NOW()");

// ===== استرجاع طلب =====
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['restore_order'])) {
    $trashId = (int)($_POST['trash_id'] ?? 0);
    if ($trashId) {
        try {
            $pdo->beginTransaction();
            $stmt = $pdo->prepare("SELECT * FROM deleted_orders WHERE id = ?");
            $stmt->execute([$trashId]);
            $del = $stmt->fetch();
            if ($del) {
                // إدراج الطلب مجدداً في orders
                $pdo->prepare("
                    INSERT INTO orders
                    (customer_name,phone,phone2,address,municipality,order_date,status_id,
                     delivery_company_id,delivery_price_id,delivery_price_modified,
                     original_delivery_price,tracking_number,sent_date,wilaya_id,commune_id,
                     delivery_type,tracking_code,shipping_status,api_response)
                    VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
                ")->execute([
                    $del['customer_name'], $del['phone'], $del['phone2'],
                    $del['address'], $del['municipality'], $del['order_date'],
                    $del['status_id'], $del['delivery_company_id'], $del['delivery_price_id'],
                    $del['delivery_price_modified'], $del['original_delivery_price'],
                    $del['tracking_number'], $del['sent_date'], $del['wilaya_id'],
                    $del['commune_id'], $del['delivery_type'], $del['tracking_code'],
                    $del['shipping_status'], $del['api_response']
                ]);
                $newOrderId = $pdo->lastInsertId();

                // إعادة إدراج المنتجات من JSON
                if (!empty($del['order_items_json'])) {
                    $items = json_decode($del['order_items_json'], true);
                    if (is_array($items)) {
                        $insItem = $pdo->prepare("
                            INSERT INTO order_items
                            (order_id, product_variant_id, quantity, unit_price, selected_attribute_value)
                            VALUES (?,?,?,?,?)
                        ");
                        foreach ($items as $item) {
                            $insItem->execute([
                                $newOrderId,
                                $item['product_variant_id'] ?? null,
                                $item['quantity'] ?? 1,
                                $item['unit_price'] ?? 0,
                                $item['selected_attribute_value'] ?? null
                            ]);
                        }
                    }
                }

                // حذف من سلة المحذوفات
                $pdo->prepare("DELETE FROM deleted_orders WHERE id = ?")->execute([$trashId]);
                $pdo->commit();
                $_SESSION['message'] = "✅ تم استرجاع الطلب #" . $del['original_order_id'] . " بنجاح (رقم جديد: #$newOrderId)";
            }
        } catch (Exception $e) {
            $pdo->rollBack();
            $_SESSION['error'] = "خطأ: " . $e->getMessage();
        }
    }
    header("Location: trash_orders.php"); exit();
}

// ===== استرجاع جماعي =====
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_restore'])) {
    $ids = array_filter(array_map('intval', $_POST['selected_trash'] ?? []));
    $count = 0;
    foreach ($ids as $trashId) {
        try {
            $pdo->beginTransaction();
            $stmt = $pdo->prepare("SELECT * FROM deleted_orders WHERE id = ?");
            $stmt->execute([$trashId]);
            $del = $stmt->fetch();
            if ($del) {
                $pdo->prepare("
                    INSERT INTO orders
                    (customer_name,phone,phone2,address,municipality,order_date,status_id,
                     delivery_company_id,delivery_price_id,delivery_price_modified,
                     original_delivery_price,tracking_number,sent_date,wilaya_id,commune_id,
                     delivery_type,tracking_code,shipping_status,api_response)
                    VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
                ")->execute([
                    $del['customer_name'],$del['phone'],$del['phone2'],
                    $del['address'],$del['municipality'],$del['order_date'],
                    $del['status_id'],$del['delivery_company_id'],$del['delivery_price_id'],
                    $del['delivery_price_modified'],$del['original_delivery_price'],
                    $del['tracking_number'],$del['sent_date'],$del['wilaya_id'],
                    $del['commune_id'],$del['delivery_type'],$del['tracking_code'],
                    $del['shipping_status'],$del['api_response']
                ]);
                $newOrderId = $pdo->lastInsertId();
                if (!empty($del['order_items_json'])) {
                    $items = json_decode($del['order_items_json'], true);
                    if (is_array($items)) {
                        $insItem = $pdo->prepare("INSERT INTO order_items (order_id,product_variant_id,quantity,unit_price,selected_attribute_value) VALUES (?,?,?,?,?)");
                        foreach ($items as $item) {
                            $insItem->execute([$newOrderId,$item['product_variant_id']??null,$item['quantity']??1,$item['unit_price']??0,$item['selected_attribute_value']??null]);
                        }
                    }
                }
                $pdo->prepare("DELETE FROM deleted_orders WHERE id = ?")->execute([$trashId]);
                $pdo->commit();
                $count++;
            }
        } catch (Exception $e) { $pdo->rollBack(); }
    }
    $_SESSION['message'] = "✅ تم استرجاع $count طلب بنجاح";
    header("Location: trash_orders.php"); exit();
}

// ===== حذف نهائي يدوي =====
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['permanent_delete'])) {
    $trashId = (int)($_POST['trash_id'] ?? 0);
    if ($trashId) {
        $pdo->prepare("DELETE FROM deleted_orders WHERE id = ?")->execute([$trashId]);
        $_SESSION['message'] = "🗑️ تم الحذف النهائي";
    }
    header("Location: trash_orders.php"); exit();
}

// ===== تفريغ السلة كاملاً =====
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['empty_trash'])) {
    $pdo->exec("DELETE FROM deleted_orders");
    $_SESSION['message'] = "🗑️ تم تفريغ سلة المحذوفات نهائياً";
    header("Location: trash_orders.php"); exit();
}

// ===== جلب البيانات =====
$searchQuery = trim($_GET['search'] ?? '');
$query = "
    SELECT do.*, w.name as wilaya_name, os.name as status_name,
           dc.name as delivery_company_name,
           TIMESTAMPDIFF(HOUR, NOW(), do.expires_at) as hours_left,
           TIMESTAMPDIFF(DAY,  NOW(), do.expires_at) as days_left
    FROM deleted_orders do
    LEFT JOIN wilayas w ON do.wilaya_id = w.id
    LEFT JOIN order_statuses os ON do.status_id = os.id
    LEFT JOIN delivery_companies dc ON do.delivery_company_id = dc.id
    WHERE 1=1
";
$params = [];
if (!empty($searchQuery)) {
    $query .= " AND (do.customer_name LIKE :s OR do.phone LIKE :s OR w.name LIKE :s)";
    $params[':s'] = '%' . $searchQuery . '%';
}
$query .= " ORDER BY do.deleted_at DESC";
$stmt = $pdo->prepare($query);
foreach ($params as $k => $v) $stmt->bindValue($k, $v);
$stmt->execute();
$deletedOrders = $stmt->fetchAll();

// إحصائيات
$totalTrash   = count($deletedOrders);
$expiringSoon = 0; // تنتهي خلال يومين
foreach ($deletedOrders as $d) { if ($d['days_left'] <= 2) $expiringSoon++; }
?>
<!DOCTYPE html>
<html dir="rtl" lang="ar">
<head>
    <?php include __DIR__ . '/darkmode.php'; ?>s
    <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;
    --danger:#DC2626;--danger-light:#FEE2E2;
    --success:#059669;--success-light:#D1FAE5;
    --warning:#D97706;--warning-light:#FEF3C7;
    --trash:#7C3AED;--trash-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 ease;
}
*,*::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;}
.container{max-width:1600px;margin:0 auto;}
::-webkit-scrollbar{width:5px;height:5px;}
::-webkit-scrollbar-thumb{background:var(--primary-light);border-radius:10px;}

/* HEADER */
.page-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);flex-wrap:wrap;gap:12px;animation:fadeDown 0.4s ease;}
@keyframes fadeDown{from{opacity:0;transform:translateY(-12px)}to{opacity:1;transform:translateY(0)}}
.page-title{display:flex;align-items:center;gap:12px;}
.page-title h1{font-size:22px;font-weight:900;color:var(--trash);}
.trash-icon-wrap{width:42px;height:42px;background:linear-gradient(135deg,var(--trash),#6D28D9);border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:22px;}
.header-actions{display:flex;gap:8px;flex-wrap:wrap;}

/* ALERT BANNER */
.alert-banner{background:linear-gradient(135deg,#FEF3C7,#FFF7ED);border:1.5px solid #FDE68A;border-radius:var(--radius-sm);padding:14px 18px;margin-bottom:18px;display:flex;align-items:center;gap:12px;color:#92400E;font-weight:600;font-size:14px;animation:fadeDown 0.3s ease;}
.alert-banner .alert-icon{font-size:22px;flex-shrink:0;}

/* STATS */
.stats-row{display:grid;grid-template-columns:repeat(3,1fr);gap:14px;margin-bottom:20px;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:600px){.stats-row{grid-template-columns:1fr 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);}
.stat-card:hover{transform:translateY(-4px);box-shadow:var(--shadow-md);}
.stat-card.s-trash::after{background:var(--trash);}
.stat-card.s-warn::after{background:var(--warning);}
.stat-card.s-safe::after{background:var(--success);}
.stat-icon{width:38px;height:38px;border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:20px;margin-bottom:10px;}
.s-trash .stat-icon{background:#EDE9FE;color:var(--trash);}
.s-warn  .stat-icon{background:var(--warning-light);color:var(--warning);}
.s-safe  .stat-icon{background:var(--success-light);color:var(--success);}
.stat-val{font-size:28px;font-weight:900;line-height:1;margin-bottom:4px;letter-spacing:-1px;}
.s-trash .stat-val{color:var(--trash);}
.s-warn  .stat-val{color:var(--warning);}
.s-safe  .stat-val{color:var(--success);}
.stat-lbl{font-size:11px;color:var(--text-3);font-weight:700;text-transform:uppercase;letter-spacing:0.5px;}

/* CARD */
.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 */
.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;}
.search-bar button{padding:0 20px;background:var(--primary);color:white;border:none;cursor:pointer;font-size:15px;display:flex;align-items:center;gap:6px;}

/* BULK BAR */
.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(--trash);font-size:15px;display:flex;align-items:center;gap:7px;}
.bulk-count span{background:var(--trash);color:white;border-radius:50%;width:26px;height:26px;display:inline-flex;align-items:center;justify-content:center;font-size:13px;}

/* BUTTONS */
.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);}
.btn-danger{background:var(--danger);color:white;}
.btn-danger:hover{background:#B91C1C;}
.btn-success{background:var(--success);color:white;}
.btn-success:hover{background:#047857;}
.btn-warning{background:var(--warning);color:white;}
.btn-warning:hover{background:#B45309;}
.btn-trash{background:linear-gradient(135deg,var(--trash),#6D28D9);color:white;}
.btn-trash:hover{opacity:0.9;}
.btn-outline{background:var(--surface-2);color:var(--text-2);border:1.5px solid var(--border);}
.btn-outline:hover{background:var(--border);}

/* TABLE */
.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(--trash),#6D28D9);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:hover td{background:#F8FAFC;}
tr.selected-row td{background:#F5F3FF!important;}

/* COUNTDOWN BADGE */
.countdown{display:inline-flex;align-items:center;gap:5px;padding:4px 10px;border-radius:20px;font-size:12px;font-weight:700;white-space:nowrap;}
.countdown.urgent{background:#FEE2E2;color:var(--danger);border:1px solid #FECACA;}
.countdown.warning{background:var(--warning-light);color:var(--warning);border:1px solid #FDE68A;}
.countdown.safe{background:var(--success-light);color:var(--success);border:1px solid #A7F3D0;}

/* STATUS */
.status-badge{display:inline-flex;align-items:center;padding:4px 12px;border-radius:20px;font-size:12px;font-weight:700;}
.s1{background:#FEF3C7;color:#D97706;border:1px solid #FDE68A;}
.s2{background:#EDE9FE;color:#7C3AED;border:1px solid #DDD6FE;}
.s3{background:#D1FAE5;color:#059669;border:1px solid #A7F3D0;}
.s4{background:#FEE2E2;color:#DC2626;border:1px solid #FECACA;}

.order-checkbox{width:17px;height:17px;cursor:pointer;accent-color:var(--trash);border-radius:4px;}

/* MESSAGES */
.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;}
.empty-state{text-align:center;padding:60px 20px;color:var(--text-3);}
.empty-state .empty-icon{font-size:64px;display:block;margin-bottom:16px;}
.empty-state h3{font-size:18px;font-weight:800;margin-bottom:8px;color:var(--text-2);}

/* DETAIL MODAL */
.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:700px;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)}to{opacity:1;transform:scale(1)}}
.modal-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;padding-bottom:14px;border-bottom:1.5px solid var(--border);}
.modal-header h2{color:var(--trash);font-size:18px;font-weight:900;}
.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);background:var(--surface-2);border:1px solid var(--border);transition:var(--tr);}
.close:hover{background:var(--danger-light);color:var(--danger);}
.info-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:14px;background:var(--surface-2);padding:16px;border-radius:var(--radius-sm);border:1px solid var(--border);margin-bottom:16px;}
.info-item .lbl{font-size:11px;color:var(--text-3);font-weight:700;text-transform:uppercase;}
.info-item .val{font-size:14px;font-weight:700;color:var(--text);margin-top:2px;}
.items-table{width:100%;border-collapse:collapse;font-size:13px;}
.items-table th{background:#F1F5F9;color:var(--text-2);padding:9px 12px;font-weight:700;text-align:right;}
.items-table td{padding:9px 12px;border-bottom:1px solid var(--border);}
</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:8px;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="page-header">
        <div class="page-title">
            <div class="trash-icon-wrap">🗑️</div>
            <div>
                <h1>سلة المحذوفات</h1>
                <p style="font-size:12px;color:var(--text-3);margin-top:2px">الطلبات المحذوفة تُحفظ هنا لمدة <strong>10 أيام</strong> ثم تُمسح نهائياً</p>
            </div>
        </div>
        <div class="header-actions">
            <a href="orders.php" class="btn btn-outline">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M19 12H5M12 19l-7-7 7-7"/></svg>
                العودة للطلبات
            </a>
            <?php if ($totalTrash > 0): ?>
            <form method="POST" onsubmit="return confirm('⚠️ تفريغ سلة المحذوفات نهائياً؟ لا يمكن التراجع!');">
                <input type="hidden" name="empty_trash" value="1">
                <button type="submit" class="btn btn-danger">🗑️ تفريغ السلة</button>
            </form>
            <?php endif; ?>
        </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; ?>

    <?php if ($expiringSoon > 0): ?>
    <div class="alert-banner">
        <span class="alert-icon">⚠️</span>
        <div>
            <strong><?= $expiringSoon ?> طلب</strong> ستُحذف نهائياً خلال يومين أو أقل! استرجعها الآن إن أردت الاحتفاظ بها.
        </div>
    </div>
    <?php endif; ?>

    <div class="stats-row">
        <div class="stat-card s-trash"><div class="stat-icon">🗑️</div><div class="stat-val"><?= $totalTrash ?></div><div class="stat-lbl">إجمالي المحذوفات</div></div>
        <div class="stat-card s-warn"><div class="stat-icon">⏰</div><div class="stat-val"><?= $expiringSoon ?></div><div class="stat-lbl">تنتهي قريباً (يومان)</div></div>
        <div class="stat-card s-safe"><div class="stat-icon">🔒</div><div class="stat-val"><?= $totalTrash - $expiringSoon ?></div><div class="stat-lbl">آمنة (أكثر من يومين)</div></div>
    </div>

    <div class="card">
        <form method="GET" class="search-bar">
            <input type="text" name="search" placeholder="ابحث بالاسم أو الهاتف أو الولاية..." value="<?= htmlspecialchars($searchQuery) ?>">
            <button type="submit">🔍 بحث</button>
        </form>

        <!-- BULK RESTORE BAR -->
        <form method="POST" id="bulkRestoreForm">
            <input type="hidden" name="bulk_restore" value="1">
            <div class="bulk-toolbar" id="bulkBar">
                <div class="bulk-count"><span id="bulkBadge">0</span> محدد</div>
                <button type="submit" class="btn btn-success btn-sm" onclick="return injectChecks() && confirm('استرجاع الطلبات المحددة؟')">
                    🔄 استرجاع المحدد
                </button>
                <div id="bulkInputs"></div>
            </div>
        </form>

        <?php if (empty($deletedOrders)): ?>
        <div class="empty-state">
            <span class="empty-icon">✨</span>
            <h3>سلة المحذوفات فارغة</h3>
            <p>لا توجد طلبات محذوفة حالياً</p>
        </div>
        <?php else: ?>
        <div class="table-responsive">
            <table>
                <thead>
                    <tr>
                        <th style="width:38px;text-align:center">
                            <input type="checkbox" class="order-checkbox" id="selAll" onchange="toggleAll(this)">
                        </th>
                        <th>رقم أصلي</th>
                        <th>العميل</th>
                        <th>الهاتف</th>
                        <th>الولاية</th>
                        <th>تاريخ الطلب</th>
                        <th>الحالة</th>
                        <th>تاريخ الحذف</th>
                        <th>ينتهي بعد</th>
                        <th>الإجراءات</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($deletedOrders as $d):
                    $daysLeft  = (int)$d['days_left'];
                    $hoursLeft = (int)$d['hours_left'];
                    if ($hoursLeft <= 0) { $cdClass='urgent'; $cdLabel='منتهي الصلاحية!'; }
                    elseif ($daysLeft <= 1) { $cdClass='urgent'; $cdLabel='أقل من يوم!'; }
                    elseif ($daysLeft <= 2) { $cdClass='warning'; $cdLabel=$daysLeft.' يوم'; }
                    else { $cdClass='safe'; $cdLabel=$daysLeft.' يوم'; }
                    $statusCls = ['1'=>'s1','2'=>'s2','3'=>'s3','4'=>'s4'][$d['status_id']] ?? 's1';
                    $statusTxt = ['1'=>'⏳ انتظار','2'=>'🚚 مرسل','3'=>'✅ مسلّم','4'=>'❌ ملغي'][$d['status_id']] ?? '--';
                ?>
                <tr id="tr-<?= $d['id'] ?>">
                    <td style="text-align:center">
                        <input type="checkbox" class="order-checkbox trash-cb" value="<?= $d['id'] ?>" onchange="onCbChange()">
                    </td>
                    <td><strong style="color:var(--trash)">#<?= $d['original_order_id'] ?></strong></td>
                    <td style="font-weight:700;color:var(--text)"><?= htmlspecialchars($d['customer_name']) ?></td>
                    <td>
                        <span style="background:#EFF6FF;padding:4px 10px;border-radius:20px;font-size:12px;color:var(--primary);font-weight:700;border:1px solid #BFDBFE">
                            📞 <?= htmlspecialchars($d['phone']) ?>
                        </span>
                    </td>
                    <td><?= htmlspecialchars($d['wilaya_name'] ?? '--') ?></td>
                    <td style="font-size:12px;color:var(--text-3)"><?= date('Y-m-d', strtotime($d['order_date'])) ?></td>
                    <td><span class="status-badge <?= $statusCls ?>"><?= $statusTxt ?></span></td>
                    <td style="font-size:12px;color:var(--text-3)"><?= date('Y-m-d H:i', strtotime($d['deleted_at'])) ?></td>
                    <td><span class="countdown <?= $cdClass ?>">⏱️ <?= $cdLabel ?></span></td>
                    <td>
                        <div style="display:flex;gap:5px;flex-wrap:nowrap">
                            <button onclick='openDetail(<?= htmlspecialchars(json_encode($d), ENT_QUOTES) ?>)' class="btn btn-primary btn-sm" title="تفاصيل">👁</button>
                            <form method="POST" style="display:inline" onsubmit="return confirm('استرجاع الطلب #<?= $d['original_order_id'] ?>؟')">
                                <input type="hidden" name="restore_order" value="1">
                                <input type="hidden" name="trash_id" value="<?= $d['id'] ?>">
                                <button type="submit" class="btn btn-success btn-sm">🔄 استرجاع</button>
                            </form>
                            <form method="POST" style="display:inline" onsubmit="return confirm('⚠️ حذف نهائي لا يمكن التراجع عنه!')">
                                <input type="hidden" name="permanent_delete" value="1">
                                <input type="hidden" name="trash_id" value="<?= $d['id'] ?>">
                                <button type="submit" class="btn btn-danger btn-sm">💀 حذف نهائي</button>
                            </form>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- DETAIL MODAL -->
<div id="detailModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h2>🗑️ تفاصيل الطلب المحذوف</h2>
            <span class="close" onclick="document.getElementById('detailModal').style.display='none'">×</span>
        </div>
        <div id="detailContent"></div>
        <div style="display:flex;justify-content:flex-end;margin-top:16px;padding-top:14px;border-top:1px solid var(--border)">
            <button class="btn btn-outline" onclick="document.getElementById('detailModal').style.display='none'">إغلاق</button>
        </div>
    </div>
</div>

<script>
function toggleAll(cb) {
    document.querySelectorAll('.trash-cb').forEach(function(el){ el.checked = cb.checked; });
    onCbChange();
}
function onCbChange() {
    var cnt = document.querySelectorAll('.trash-cb:checked').length;
    document.getElementById('bulkBadge').textContent = cnt;
    document.getElementById('bulkBar').classList.toggle('visible', cnt > 0);
    document.querySelectorAll('.trash-cb').forEach(function(cb){
        var row = document.getElementById('tr-'+cb.value);
        if(row) row.classList.toggle('selected-row', cb.checked);
    });
    var total = document.querySelectorAll('.trash-cb').length;
    var master = document.getElementById('selAll');
    master.checked = (cnt===total && total>0);
    master.indeterminate = (cnt>0 && cnt<total);
}
function injectChecks() {
    var ids = Array.from(document.querySelectorAll('.trash-cb:checked')).map(function(cb){return cb.value;});
    if (!ids.length){ alert('اختر عنصراً واحداً على الأقل'); return false; }
    var c = document.getElementById('bulkInputs'); c.innerHTML='';
    ids.forEach(function(id){ var inp=document.createElement('input'); inp.type='hidden'; inp.name='selected_trash[]'; inp.value=id; c.appendChild(inp); });
    return true;
}
function openDetail(d) {
    var statusMap = {1:'⏳ انتظار',2:'🚚 مرسل',3:'✅ مسلّم',4:'❌ ملغي'};
    var html = '<div class="info-grid">';
    html += '<div class="info-item"><div class="lbl">رقم الطلب الأصلي</div><div class="val">#'+d.original_order_id+'</div></div>';
    html += '<div class="info-item"><div class="lbl">اسم العميل</div><div class="val">'+(d.customer_name||'--')+'</div></div>';
    html += '<div class="info-item"><div class="lbl">الهاتف</div><div class="val">'+(d.phone||'--')+'</div></div>';
    if(d.phone2) html += '<div class="info-item"><div class="lbl">هاتف إضافي</div><div class="val">'+d.phone2+'</div></div>';
    html += '<div class="info-item"><div class="lbl">الولاية</div><div class="val">'+(d.wilaya_name||'--')+'</div></div>';
    html += '<div class="info-item"><div class="lbl">البلدية</div><div class="val">'+(d.municipality||'--')+'</div></div>';
    html += '<div class="info-item"><div class="lbl">العنوان</div><div class="val" style="font-size:12px">'+(d.address||'--')+'</div></div>';
    html += '<div class="info-item"><div class="lbl">نوع التوصيل</div><div class="val">'+(d.delivery_type==='home'?'🏠 للمنزل':'🏢 للمكتب')+'</div></div>';
    html += '<div class="info-item"><div class="lbl">الحالة</div><div class="val">'+(statusMap[d.status_id]||'--')+'</div></div>';
    html += '<div class="info-item"><div class="lbl">تاريخ الطلب</div><div class="val" style="font-size:12px">'+(d.order_date||'--')+'</div></div>';
    html += '<div class="info-item"><div class="lbl">تاريخ الحذف</div><div class="val" style="font-size:12px;color:#DC2626">'+(d.deleted_at||'--')+'</div></div>';
    html += '<div class="info-item"><div class="lbl">ينتهي بعد</div><div class="val" style="color:#D97706">'+(d.days_left > 0 ? d.days_left+' يوم' : 'منتهي!')+'</div></div>';
    html += '</div>';

    if (d.order_items_json) {
        try {
            var items = JSON.parse(d.order_items_json);
            if (items && items.length) {
                html += '<h3 style="margin:14px 0 10px;font-weight:800;font-size:14px">📦 المنتجات</h3>';
                html += '<table class="items-table"><thead><tr><th>المنتج</th><th>الكمية</th><th>السعر</th><th>الإجمالي</th></tr></thead><tbody>';
                items.forEach(function(item){
                    html += '<tr><td>'+(item.product_name||'منتج #'+item.product_variant_id)+'</td>';
                    html += '<td>'+item.quantity+'</td>';
                    html += '<td>'+parseFloat(item.unit_price).toFixed(2)+' دج</td>';
                    html += '<td>'+(item.quantity*item.unit_price).toFixed(2)+' دج</td></tr>';
                });
                html += '</tbody></table>';
            }
        } catch(e) {}
    }
    document.getElementById('detailContent').innerHTML = html;
    document.getElementById('detailModal').style.display = 'flex';
}
window.onclick = function(e){ if(e.target.classList.contains('modal')) e.target.style.display='none'; };
</script>
</body>
</html>