<?php

declare(strict_types=1);

require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/module_hub_helpers.php';
require_once __DIR__ . '/includes/v3_admin_helpers.php';

$db = hub_db();
v3_ensure_schema($db);

function dash_order_status_expr(string $column): string
{
    return "CASE
        WHEN {$column} IN ('cancelled','returned') THEN 'cancelled'
        WHEN {$column} IN ('delivered','completed') THEN 'delivered'
        WHEN {$column} IN ('ready','out_for_delivery','shipped') THEN 'ready'
        WHEN {$column} = 'postponed' THEN 'postponed'
        ELSE 'pending' END";
}

function dash_link(string $href, string $label): string
{
    return '<a class="dash-mini-link" href="' . htmlspecialchars($href, ENT_QUOTES, 'UTF-8') . '">' . htmlspecialchars($label, ENT_QUOTES, 'UTF-8') . '</a>';
}

$ordersTable = hub_table_exists($db, 'orders') ? 'orders' : null;
$productsTable = hub_table_exists($db, 'products') ? 'products' : null;
$customersTable = hub_table_exists($db, 'customers') ? 'customers' : null;
$influencersTable = hub_table_exists($db, 'influencers') ? 'influencers' : null;
$variantsTable = hub_table_exists($db, 'product_variants') ? 'product_variants' : null;
$brandsTable = hub_table_exists($db, 'brands') ? 'brands' : (hub_table_exists($db, 'companies') ? 'companies' : null);
$promoTable = hub_table_exists($db, 'promo_codes') ? 'promo_codes' : (hub_table_exists($db, 'promocodes') ? 'promocodes' : null);
$categoriesTable = hub_table_exists($db, 'categories') ? 'categories' : null;
$statusExpr = $ordersTable ? dash_order_status_expr('order_status') : '';

$todayOrders = $ordersTable && hub_column_exists($db, $ordersTable, 'created_at') ? hub_fetch_value($db, "SELECT COUNT(*) AS c FROM `{$ordersTable}` WHERE DATE(created_at)=CURDATE()") : 0;
$pendingOrders = $ordersTable && hub_column_exists($db, $ordersTable, 'order_status') ? hub_fetch_value($db, "SELECT COUNT(*) AS c FROM `{$ordersTable}` WHERE {$statusExpr}='pending'") : 0;
$readyOrders = $ordersTable && hub_column_exists($db, $ordersTable, 'order_status') ? hub_fetch_value($db, "SELECT COUNT(*) AS c FROM `{$ordersTable}` WHERE {$statusExpr}='ready'") : 0;
$postponedOrders = $ordersTable && hub_column_exists($db, $ordersTable, 'order_status') ? hub_fetch_value($db, "SELECT COUNT(*) AS c FROM `{$ordersTable}` WHERE {$statusExpr}='postponed'") : 0;
$deliveredTodaySales = $ordersTable && hub_column_exists($db, $ordersTable, 'created_at') && hub_column_exists($db, $ordersTable, 'total_amount') ? hub_fetch_value($db, "SELECT COALESCE(SUM(total_amount),0) AS c FROM `{$ordersTable}` WHERE DATE(created_at)=CURDATE() AND {$statusExpr}='delivered'", 'c', 0.0) : 0.0;
$paymentNeeds = $ordersTable && hub_column_exists($db, $ordersTable, 'payment_status') ? hub_fetch_value($db, "SELECT COUNT(*) AS c FROM `{$ordersTable}` WHERE payment_status IN ('pending_confirmation','unpaid') AND {$statusExpr} NOT IN ('delivered','cancelled')") : 0;
$deletionRequests = hub_table_exists($db, 'customer_deletion_requests') ? hub_fetch_value($db, "SELECT COUNT(*) AS c FROM customer_deletion_requests WHERE status IN ('pending','processing')") : 0;
$productLowStockLimitExpr = $productsTable && hub_column_exists($db, $productsTable, 'low_stock_alert') ? 'COALESCE(NULLIF(low_stock_alert,0),5)' : '5';
$variantLowStockLimitExpr = $variantsTable && hub_column_exists($db, $variantsTable, 'low_stock_alert') ? 'COALESCE(NULLIF(low_stock_alert,0),5)' : '5';
$lowStockSimple = $productsTable && hub_column_exists($db, $productsTable, 'stock_qty') ? hub_fetch_value($db, "SELECT COUNT(*) AS c FROM `{$productsTable}` WHERE stock_qty <= {$productLowStockLimitExpr}") : 0;
$lowStockVariants = $variantsTable && hub_column_exists($db, $variantsTable, 'stock_qty') ? hub_fetch_value($db, "SELECT COUNT(*) AS c FROM `{$variantsTable}` WHERE stock_qty <= {$variantLowStockLimitExpr}") : 0;
$imageColumn = $productsTable && hub_column_exists($db, $productsTable, 'main_image') ? 'main_image' : (hub_column_exists($db, $productsTable, 'image') ? 'image' : '');
$missingImages = $productsTable && $imageColumn !== '' ? hub_fetch_value($db, "SELECT COUNT(*) AS c FROM `{$productsTable}` WHERE COALESCE({$imageColumn},'')=''" ) : 0;
$missingBarcode = $productsTable && hub_column_exists($db, $productsTable, 'barcode') ? hub_fetch_value($db, "SELECT COUNT(*) AS c FROM `{$productsTable}` WHERE COALESCE(barcode,'')=''" ) : 0;

$stats = [
    ['title' => 'طلبات اليوم', 'value' => $todayOrders, 'note' => 'كل الطلبات المسجلة اليوم', 'href' => '/app/admin/orders/list.php?quick=today', 'tone' => 'primary'],
    ['title' => 'بحاجة للتجهيز', 'value' => $pendingOrders, 'note' => 'طلبات قيد الانتظار', 'href' => '/app/admin/orders/list.php?quick=needs_processing', 'tone' => 'warn'],
    ['title' => 'بحاجة لتأكيد الدفع', 'value' => $paymentNeeds, 'note' => 'تحويل/دفع غير مؤكد', 'href' => '/app/admin/orders/list.php?quick=needs_payment', 'tone' => 'danger'],
    ['title' => 'جاهزة', 'value' => $readyOrders, 'note' => 'للتسليم أو الاستلام', 'href' => '/app/admin/orders/list.php?quick=ready', 'tone' => 'info'],
    ['title' => 'مؤجلة', 'value' => $postponedOrders, 'note' => 'تحتاج متابعة لاحقة', 'href' => '/app/admin/orders/list.php?quick=postponed', 'tone' => 'soft'],
    ['title' => 'مبيعات اليوم', 'value' => hub_format_iqd((float)$deliveredTodaySales), 'note' => 'طلبات مسلّمة فقط', 'href' => '/app/admin/orders/list.php?date_from=' . date('Y-m-d') . '&date_to=' . date('Y-m-d') . '&status=delivered', 'tone' => 'success', 'money' => true],
    ['title' => 'طلبات حذف الحساب', 'value' => $deletionRequests, 'note' => 'قيد المراجعة أو التنفيذ', 'href' => '/app/admin/customers/deletion_requests.php', 'tone' => 'danger'],
    ['title' => 'تنبيه مخزون', 'value' => (int)$lowStockSimple + (int)$lowStockVariants, 'note' => 'منتجات/فاريانتات منخفضة', 'href' => '/app/admin/products/stock_monitor.php', 'tone' => 'warn'],
];

$catalogStats = [
    ['title' => 'المنتجات', 'value' => $productsTable ? hub_fetch_value($db, "SELECT COUNT(*) AS c FROM `{$productsTable}`") : 0, 'href' => '/app/admin/products/index.php'],
    ['title' => 'بدون صورة', 'value' => $missingImages, 'href' => '/app/admin/products/list.php?missing=image'],
    ['title' => 'بدون باركود', 'value' => $missingBarcode, 'href' => '/app/admin/products/list.php?missing=barcode'],
    ['title' => 'البراندات', 'value' => $brandsTable ? hub_fetch_value($db, "SELECT COUNT(*) AS c FROM `{$brandsTable}`") : 0, 'href' => '/app/admin/brands/index.php'],
    ['title' => 'الأقسام', 'value' => $categoriesTable ? hub_fetch_value($db, "SELECT COUNT(*) AS c FROM `{$categoriesTable}`") : 0, 'href' => '/app/admin/categories/index.php'],
    ['title' => 'الزبائن', 'value' => $customersTable ? hub_fetch_value($db, "SELECT COUNT(*) AS c FROM `{$customersTable}`") : 0, 'href' => '/app/admin/customers/index.php'],
    ['title' => 'المؤثرين', 'value' => $influencersTable ? hub_fetch_value($db, "SELECT COUNT(*) AS c FROM `{$influencersTable}`") : 0, 'href' => '/app/admin/influencers/index.php'],
    ['title' => 'أكواد الخصم', 'value' => $promoTable ? hub_fetch_value($db, "SELECT COUNT(*) AS c FROM `{$promoTable}`") : 0, 'href' => '/app/admin/promo_codes/index.php'],
];

$recentOrders = [];
if ($ordersTable) {
    $orderNo = hub_column_exists($db, $ordersTable, 'order_number') ? 'order_number' : 'id';
    $customerCol = hub_column_exists($db, $ordersTable, 'customer_name') ? 'customer_name' : (hub_column_exists($db, $ordersTable, 'customer_id') ? 'customer_id' : 'NULL');
    $statusCol = hub_column_exists($db, $ordersTable, 'order_status') ? 'order_status' : "'unknown'";
    $payCol = hub_column_exists($db, $ordersTable, 'payment_status') ? 'payment_status' : "''";
    $totalCol = hub_column_exists($db, $ordersTable, 'total_amount') ? 'total_amount' : (hub_column_exists($db, $ordersTable, 'total') ? 'total' : '0');
    $dateCol = hub_column_exists($db, $ordersTable, 'created_at') ? 'created_at' : 'NULL';
    $recentOrders = hub_fetch_all($db, "SELECT id, {$orderNo} AS order_number, {$customerCol} AS customer_name, {$statusCol} AS order_status, {$payCol} AS payment_status, {$totalCol} AS total_amount, {$dateCol} AS created_at FROM `{$ordersTable}` ORDER BY id DESC LIMIT 8");
}

$recentLogs = [];
if (hub_table_exists($db, 'admin_activity_logs')) {
    $adminNameExpr = hub_table_exists($db, 'admins') ? "COALESCE(a.full_name, a.username, CONCAT('Admin #', l.admin_id))" : "CONCAT('Admin #', l.admin_id)";
    $joinAdmins = hub_table_exists($db, 'admins') ? 'LEFT JOIN admins a ON a.id = l.admin_id' : '';
    $recentLogs = hub_fetch_all($db, "SELECT l.*, {$adminNameExpr} AS admin_name FROM admin_activity_logs l {$joinAdmins} ORDER BY l.id DESC LIMIT 8");
}

$quickLinks = [
    ['href' => '/app/admin/orders/list.php?quick=needs_processing', 'title' => 'طلبات تحتاج تجهيز', 'icon' => 'fa-solid fa-box-open'],
    ['href' => '/app/admin/orders/list.php?quick=needs_payment', 'title' => 'تأكيد الدفع', 'icon' => 'fa-solid fa-money-check'],
    ['href' => '/app/admin/products/stock_monitor.php', 'title' => 'مراقبة المخزون', 'icon' => 'fa-solid fa-warehouse'],
    ['href' => '/app/admin/activity_logs/index.php', 'title' => 'سجل العمليات', 'icon' => 'fa-solid fa-clock-rotate-left'],
    ['href' => '/app/admin/app_home/index.php', 'title' => 'واجهة التطبيق', 'icon' => 'fa-solid fa-mobile-screen-button'],
    ['href' => '/app/admin/customers/deletion_requests.php', 'title' => 'طلبات حذف الحساب', 'icon' => 'fa-solid fa-user-slash'],
];

$page_title = 'داشبورد التشغيل';
require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/includes/sidebar.php';
?>
<style>
.ops-page{padding:24px}.ops-hero,.ops-card{background:#fff;border-radius:24px;box-shadow:0 14px 36px rgba(25,68,107,.08);padding:22px;margin-bottom:18px}.ops-hero{display:flex;align-items:flex-start;justify-content:space-between;gap:20px;flex-wrap:wrap}.ops-hero h1{margin:0 0 8px;color:#183b56}.ops-hero p{margin:0;color:#648096;line-height:1.85;max-width:780px}.ops-actions{display:flex;gap:10px;flex-wrap:wrap}.ops-btn{display:inline-flex;align-items:center;gap:8px;background:#edf5fa;color:#183b56;text-decoration:none;border-radius:14px;padding:12px 15px;font-weight:900}.ops-btn.primary{background:#183b56;color:#fff}.ops-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:14px;margin-bottom:18px}.ops-stat{display:block;text-decoration:none;background:#fff;border:1px solid #e7eff6;border-radius:22px;padding:18px;box-shadow:0 12px 30px rgba(25,68,107,.06);transition:.16s ease}.ops-stat:hover{transform:translateY(-2px);box-shadow:0 16px 36px rgba(25,68,107,.10)}.ops-label{font-size:13px;font-weight:900;color:#638199}.ops-value{font-size:30px;font-weight:1000;color:#183b56;margin:8px 0}.ops-note{font-size:12px;color:#7b93a8;line-height:1.6}.ops-stat.primary{border-color:#cfe4f3}.ops-stat.warn{border-color:#ffe1bd}.ops-stat.danger{border-color:#ffd2d2}.ops-stat.success{border-color:#caefd7}.ops-stat.soft{border-color:#e6dcff}.ops-two{display:grid;grid-template-columns:1.15fr .85fr;gap:18px}.ops-table-wrap{overflow:auto;border:1px solid #e7eff6;border-radius:18px}.ops-table{width:100%;border-collapse:collapse;min-width:760px}.ops-table th,.ops-table td{padding:14px 12px;text-align:right;border-bottom:1px solid #eef4f8}.ops-table th{background:#f5f9fc;color:#607d95;font-size:12px}.ops-table td{color:#274860}.ops-mini-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:10px}.ops-mini{display:flex;align-items:center;justify-content:space-between;gap:10px;text-decoration:none;background:#f7fbfe;border:1px solid #e6eef5;border-radius:16px;padding:13px 14px;color:#183b56;font-weight:900}.ops-mini strong{font-size:20px}.ops-links{display:grid;grid-template-columns:repeat(2,1fr);gap:10px}.ops-link{display:flex;align-items:center;gap:10px;text-decoration:none;border-radius:16px;background:#f3f8fc;color:#183b56;font-weight:900;padding:14px}.badge{display:inline-flex;padding:6px 11px;border-radius:999px;font-size:12px;font-weight:900}.badge.info{background:#e8f3ff;color:#195f9d}.badge.success{background:#e8f8ef;color:#1e7c49}.badge.warn{background:#fff1eb;color:#aa5121}.badge.soft{background:#f4f0ff;color:#6f49bf}.badge.neutral{background:#eef5f9;color:#224760}.muted{color:#748ba0;font-size:12px}.dash-mini-link{display:inline-flex;margin-top:6px;color:#1d5f91;text-decoration:none;font-weight:900;font-size:12px}@media(max-width:1200px){.ops-grid{grid-template-columns:repeat(2,1fr)}.ops-two{grid-template-columns:1fr}}@media(max-width:720px){.ops-grid,.ops-mini-grid,.ops-links{grid-template-columns:1fr}.ops-page{padding:16px}}
</style>
<div class="ops-page">
  <div class="ops-hero">
    <div>
      <h1>داشبورد التشغيل</h1>
      <p>هاي الصفحة صارت نقطة متابعة يومية: الطلبات التي تحتاج إجراء، الدفع، المخزون، وطلبات حذف الحساب، مع اختصارات مباشرة بدل البحث اليدوي داخل اللوحة.</p>
    </div>
    <div class="ops-actions">
      <a class="ops-btn primary" href="/app/admin/orders/create.php"><i class="fa-solid fa-plus"></i> إنشاء طلب</a>
      <a class="ops-btn" href="/app/admin/orders/list.php"><i class="fa-solid fa-list-check"></i> قائمة الطلبات</a>
      <a class="ops-btn" href="/app/admin/activity_logs/index.php"><i class="fa-solid fa-clock-rotate-left"></i> سجل العمليات</a>
    </div>
  </div>

  <div class="ops-grid">
    <?php foreach ($stats as $card): ?>
      <a class="ops-stat <?= htmlspecialchars($card['tone']) ?>" href="<?= htmlspecialchars($card['href']) ?>">
        <div class="ops-label"><?= htmlspecialchars($card['title']) ?></div>
        <div class="ops-value"><?= htmlspecialchars((string)$card['value']) ?></div>
        <div class="ops-note"><?= htmlspecialchars($card['note']) ?></div>
      </a>
    <?php endforeach; ?>
  </div>

  <div class="ops-two">
    <div class="ops-card">
      <h3>آخر الطلبات</h3>
      <?php if (!$recentOrders): ?>
        <div class="muted">لا توجد طلبات للعرض حالياً.</div>
      <?php else: ?>
        <div class="ops-table-wrap"><table class="ops-table"><thead><tr><th>#</th><th>الزبون</th><th>الحالة</th><th>الدفع</th><th>المبلغ</th><th>التاريخ</th></tr></thead><tbody>
          <?php foreach ($recentOrders as $row): ?>
            <?php $normalized = (string)($row['order_status'] ?? 'pending'); ?>
            <tr>
              <td><a href="/app/admin/orders/view.php?id=<?= (int)$row['id'] ?>">N-B <?= str_pad((string)(int)$row['id'], 3, '0', STR_PAD_LEFT) ?></a></td>
              <td><?= htmlspecialchars((string)$row['customer_name']) ?></td>
              <td><span class="badge info"><?= htmlspecialchars($normalized) ?></span></td>
              <td><span class="badge <?= ($row['payment_status'] ?? '') === 'paid' ? 'success' : 'warn' ?>"><?= htmlspecialchars((string)($row['payment_status'] ?? '-')) ?></span></td>
              <td><?= hub_format_iqd((float)($row['total_amount'] ?? 0)) ?></td>
              <td><span class="muted"><?= htmlspecialchars((string)$row['created_at']) ?></span></td>
            </tr>
          <?php endforeach; ?>
        </tbody></table></div>
      <?php endif; ?>
    </div>

    <div class="ops-card">
      <h3>مؤشرات الكتالوك</h3>
      <div class="ops-mini-grid">
        <?php foreach ($catalogStats as $item): ?>
          <a class="ops-mini" href="<?= htmlspecialchars($item['href']) ?>"><span><?= htmlspecialchars($item['title']) ?></span><strong><?= number_format((int)$item['value']) ?></strong></a>
        <?php endforeach; ?>
      </div>
      <h3 style="margin-top:22px">اختصارات تشغيل</h3>
      <div class="ops-links">
        <?php foreach ($quickLinks as $link): ?>
          <a class="ops-link" href="<?= htmlspecialchars($link['href']) ?>"><i class="<?= htmlspecialchars($link['icon']) ?>"></i><?= htmlspecialchars($link['title']) ?></a>
        <?php endforeach; ?>
      </div>
    </div>
  </div>

  <div class="ops-card">
    <h3>آخر نشاطات المدراء</h3>
    <?php if (!$recentLogs): ?>
      <div class="muted">سجل العمليات فارغ حالياً أو لم يتم تفعيله بعد.</div>
    <?php else: ?>
      <div class="ops-table-wrap"><table class="ops-table"><thead><tr><th>المدير</th><th>العملية</th><th>الوصف</th><th>العنصر</th><th>IP</th><th>الوقت</th></tr></thead><tbody>
        <?php foreach ($recentLogs as $log): ?>
          <tr>
            <td><?= htmlspecialchars((string)($log['admin_name'] ?? '')) ?></td>
            <td><span class="badge neutral"><?= htmlspecialchars((string)($log['action_label'] ?? $log['event_key'] ?? '')) ?></span></td>
            <td><?= htmlspecialchars((string)($log['description'] ?? '')) ?></td>
            <td><span class="muted"><?= htmlspecialchars(trim((string)($log['target_type'] ?? '') . ' #' . (string)($log['target_id'] ?? ''))) ?></span></td>
            <td><span class="muted"><?= htmlspecialchars((string)($log['ip_address'] ?? '')) ?></span></td>
            <td><span class="muted"><?= htmlspecialchars((string)($log['created_at'] ?? '')) ?></span></td>
          </tr>
        <?php endforeach; ?>
      </tbody></table></div>
      <?= dash_link('/app/admin/activity_logs/index.php', 'عرض السجل الكامل') ?>
    <?php endif; ?>
  </div>
</div>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
