<?php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/module_hub_helpers.php';

$db = hub_db();
$page_title = 'مركز التنبيهات';

function n_datetime_value(array $row): int {
    foreach (['created_at', 'updated_at', 'paid_at', 'read_at'] as $key) {
        if (!empty($row[$key])) {
            $ts = strtotime((string)$row[$key]);
            if ($ts) return $ts;
        }
    }
    return time();
}

function n_datetime_label(array $row): string {
    foreach (['created_at', 'updated_at', 'paid_at', 'read_at'] as $key) {
        if (!empty($row[$key])) {
            return (string)$row[$key];
        }
    }
    return date('Y-m-d H:i:s');
}

function n_order_number(array $row): string {
    foreach (['order_number', 'invoice_number', 'reference_number'] as $key) {
        if (!empty($row[$key])) return (string)$row[$key];
    }
    return '#' . (int)($row['id'] ?? 0);
}

function n_customer_name(array $row): string {
    foreach (['full_name', 'customer_name', 'name'] as $key) {
        if (!empty($row[$key])) return (string)$row[$key];
    }
    return 'زبون #' . (int)($row['id'] ?? 0);
}

function n_customer_phone(array $row): string {
    foreach (['phone', 'mobile', 'customer_phone'] as $key) {
        if (!empty($row[$key])) return (string)$row[$key];
    }
    return '';
}

function n_order_payment_method(array $row): string {
    foreach (['payment_method_name', 'payment_method', 'payment_method_code'] as $key) {
        if (!empty($row[$key])) return (string)$row[$key];
    }
    return '';
}

function n_order_payment_status(array $row): string {
    foreach (['payment_status', 'financial_status'] as $key) {
        if (!empty($row[$key])) return strtolower(trim((string)$row[$key]));
    }
    if (isset($row['is_paid'])) return ((int)$row['is_paid'] === 1) ? 'paid' : 'pending';
    return '';
}

$settings = hub_settings_map($db);
$notificationsEnabled = hub_setting_enabled($db, 'notifications_internal_admin_enabled', true);
$enableNewUser = hub_setting_enabled($db, 'notifications_new_user_enabled', true);
$enableNewOrder = hub_setting_enabled($db, 'notifications_new_order_enabled', true);
$enableLowStock = hub_setting_enabled($db, 'notifications_low_stock_enabled', true);

$events = [];
$stats = [
    'new_customers' => 0,
    'pending_activation' => 0,
    'new_orders' => 0,
    'card_pending' => 0,
    'influencer_pending' => 0,
    'low_stock' => 0,
];

if ($notificationsEnabled && $db) {
    if ($enableNewUser && hub_table_exists($db, 'customers')) {
        $customerRows = hub_fetch_all($db, "SELECT * FROM customers ORDER BY id DESC LIMIT 40");
        foreach ($customerRows as $row) {
            $status = isset($row['status']) ? (int)$row['status'] : 1;
            $isVerified = isset($row['is_verified']) ? (int)$row['is_verified'] : 1;
            $name = n_customer_name($row);
            $phone = n_customer_phone($row);
            if ($status === 1) {
                $stats['new_customers']++;
                $events[] = [
                    'type' => 'new_customer',
                    'severity' => 'info',
                    'title' => 'تسجيل زبون جديد',
                    'message' => $name . ($phone !== '' ? ' - ' . $phone : ''),
                    'time' => n_datetime_value($row),
                    'time_label' => n_datetime_label($row),
                    'link' => '/app/admin/customers/edit.php?id=' . (int)($row['id'] ?? 0),
                    'badge' => 'زبون جديد',
                ];
            }
            if ($status === 1 && $isVerified === 0) {
                $stats['pending_activation']++;
                $events[] = [
                    'type' => 'pending_activation',
                    'severity' => 'warn',
                    'title' => 'زبون بانتظار التفعيل',
                    'message' => $name . ($phone !== '' ? ' - ' . $phone : ''),
                    'time' => n_datetime_value($row),
                    'time_label' => n_datetime_label($row),
                    'link' => '/app/admin/customers/edit.php?id=' . (int)($row['id'] ?? 0),
                    'badge' => 'OTP',
                ];
            }
        }
    }

    if ($enableNewOrder && hub_table_exists($db, 'orders')) {
        $orderRows = hub_fetch_all($db, "SELECT * FROM orders ORDER BY id DESC LIMIT 50");
        foreach ($orderRows as $row) {
            $orderNumber = n_order_number($row);
            $customerName = n_customer_name($row);
            $paymentMethod = strtolower(n_order_payment_method($row));
            $paymentStatus = n_order_payment_status($row);
            $orderStatus = strtolower(trim((string)($row['order_status'] ?? '')));
            $stats['new_orders']++;
            $events[] = [
                'type' => 'new_order',
                'severity' => 'success',
                'title' => 'طلب جديد',
                'message' => $orderNumber . ' — ' . $customerName,
                'time' => n_datetime_value($row),
                'time_label' => n_datetime_label($row),
                'link' => '/app/admin/orders/index.php',
                'badge' => $orderStatus !== '' ? $orderStatus : 'طلب',
            ];
            $isCard = str_contains($paymentMethod, 'card') || str_contains($paymentMethod, 'master') || str_contains($paymentMethod, 'visa');
            $needsConfirm = $paymentStatus === '' || in_array($paymentStatus, ['pending', 'unpaid', 'waiting', 'awaiting_confirmation'], true);
            if ($isCard && $needsConfirm) {
                $stats['card_pending']++;
                $events[] = [
                    'type' => 'card_pending',
                    'severity' => 'warn',
                    'title' => 'دفعة كارد تحتاج تأكيد',
                    'message' => $orderNumber . ' — ' . $customerName,
                    'time' => n_datetime_value($row),
                    'time_label' => n_datetime_label($row),
                    'link' => '/app/admin/orders/index.php',
                    'badge' => 'دفع معلّق',
                ];
            }
        }
    }

    if (hub_table_exists($db, 'influencers')) {
        $influencerRows = hub_fetch_all($db, "SELECT * FROM influencers ORDER BY id DESC LIMIT 30");
        foreach ($influencerRows as $row) {
            $status = strtolower(trim((string)($row['status'] ?? '')));
            $isPending = $status === '2' || $status === 'pending' || $status === 'wait';
            if (!$isPending && isset($row['status']) && (int)$row['status'] === 2) {
                $isPending = true;
            }
            if (!$isPending) continue;
            $stats['influencer_pending']++;
            $name = (string)($row['name'] ?? ('مؤثر #' . (int)($row['id'] ?? 0)));
            $events[] = [
                'type' => 'influencer_pending',
                'severity' => 'info',
                'title' => 'طلب تسجيل مؤثر',
                'message' => $name . (!empty($row['phone']) ? ' - ' . $row['phone'] : ''),
                'time' => n_datetime_value($row),
                'time_label' => n_datetime_label($row),
                'link' => '/app/admin/influencers/list.php?status=2',
                'badge' => 'مؤثر',
            ];
        }
    }

    if ($enableLowStock && hub_table_exists($db, 'products')) {
        $threshold = max(1, (int)hub_setting($db, 'inventory_low_stock_threshold', '5'));
        $productRows = hub_fetch_all($db, "SELECT * FROM products WHERE status = 1 ORDER BY stock_qty ASC, id DESC LIMIT 50");
        foreach ($productRows as $row) {
            $qty = isset($row['stock_qty']) ? (int)$row['stock_qty'] : 0;
            if ($qty > $threshold) continue;
            $stats['low_stock']++;
            $events[] = [
                'type' => 'low_stock',
                'severity' => $qty <= 0 ? 'danger' : 'warn',
                'title' => $qty <= 0 ? 'نفد مخزون منتج' : 'انخفاض مخزون منتج',
                'message' => (string)($row['name'] ?? 'منتج') . ' — المتبقي: ' . $qty,
                'time' => n_datetime_value($row),
                'time_label' => n_datetime_label($row),
                'link' => '/app/admin/products/list.php',
                'badge' => 'مخزون',
            ];
        }
        if (hub_table_exists($db, 'product_variants')) {
            $variantRows = hub_fetch_all($db, "SELECT pv.*, p.name AS product_name FROM product_variants pv LEFT JOIN products p ON p.id = pv.product_id WHERE pv.status = 1 ORDER BY pv.stock_qty ASC, pv.id DESC LIMIT 50");
            foreach ($variantRows as $row) {
                $qty = isset($row['stock_qty']) ? (int)$row['stock_qty'] : 0;
                if ($qty > $threshold) continue;
                $stats['low_stock']++;
                $events[] = [
                    'type' => 'variant_low_stock',
                    'severity' => $qty <= 0 ? 'danger' : 'warn',
                    'title' => $qty <= 0 ? 'نفد مخزون فاريانت' : 'انخفاض مخزون فاريانت',
                    'message' => (string)($row['product_name'] ?? 'منتج') . ' / ' . (string)($row['variant_name'] ?? 'فاريانت') . ' — المتبقي: ' . $qty,
                    'time' => n_datetime_value($row),
                    'time_label' => n_datetime_label($row),
                    'link' => '/app/admin/products/variants.php',
                    'badge' => 'فاريانت',
                ];
            }
        }
    }
}

usort($events, fn($a, $b) => $b['time'] <=> $a['time']);
$events = array_slice($events, 0, 100);
$stats['total'] = count($events);

require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/../includes/sidebar.php';
?>
<div class="nay-dashboard-page">
    <div class="nay-dashboard-main">
        <div class="nay-dashboard-hero">
            <div>
                <h1>مركز التنبيهات</h1>
                <p>مراجعة أحدث الأحداث التشغيلية من مكان واحد: زبائن جدد، تفعيل OTP، طلبات جديدة، دفعات كارد معلّقة، طلبات مؤثرين، وتنبيهات المخزون.</p>
            </div>
            <div class="nay-actions">
                <a class="nay-btn primary" href="/app/admin/orders/index.php"><i class="fa-solid fa-cart-shopping"></i> الطلبات</a>
                <a class="nay-btn" href="/app/admin/customers/index.php"><i class="fa-solid fa-users"></i> الزبائن</a>
                <a class="nay-btn" href="/app/admin/products/list.php"><i class="fa-solid fa-box-open"></i> المخزون</a>
            </div>
        </div>

        <div class="nay-stats-grid">
            <div class="nay-card"><div class="nay-stat-label">كل التنبيهات</div><div class="nay-stat-value"><?= number_format((int)$stats['total']) ?></div><div class="nay-stat-sub">آخر الأحداث المجتمعة</div></div>
            <div class="nay-card"><div class="nay-stat-label">زبائن جدد</div><div class="nay-stat-value"><?= number_format((int)$stats['new_customers']) ?></div><div class="nay-stat-sub">آخر الحسابات النشطة</div></div>
            <div class="nay-card"><div class="nay-stat-label">بانتظار OTP</div><div class="nay-stat-value"><?= number_format((int)$stats['pending_activation']) ?></div><div class="nay-stat-sub">نشط لكن غير مفعل</div></div>
            <div class="nay-card"><div class="nay-stat-label">طلبات جديدة</div><div class="nay-stat-value"><?= number_format((int)$stats['new_orders']) ?></div><div class="nay-stat-sub">من جدول الطلبات</div></div>
            <div class="nay-card"><div class="nay-stat-label">دفعات كارد معلّقة</div><div class="nay-stat-value"><?= number_format((int)$stats['card_pending']) ?></div><div class="nay-stat-sub">تحتاج مراجعة</div></div>
            <div class="nay-card"><div class="nay-stat-label">مؤثرون بانتظار الموافقة</div><div class="nay-stat-value"><?= number_format((int)$stats['influencer_pending']) ?></div><div class="nay-stat-sub">طلبات التسجيل</div></div>
            <div class="nay-card"><div class="nay-stat-label">تنبيهات المخزون</div><div class="nay-stat-value"><?= number_format((int)$stats['low_stock']) ?></div><div class="nay-stat-sub">حسب العتبة المحددة</div></div>
            <div class="nay-card"><div class="nay-stat-label">إشعارات الأدمن</div><div class="nay-stat-value"><?= $notificationsEnabled ? 'ON' : 'OFF' ?></div><div class="nay-stat-sub">من الإعدادات</div></div>
        </div>

        <div class="nay-grid-two">
            <div class="nay-card">
                <h3>مفاتيح التشغيل الحالية</h3>
                <div class="nay-list">
                    <div class="nay-list-item"><span>إشعارات داخلية للإدارة</span><strong><?= $notificationsEnabled ? 'مفعلة' : 'موقوفة' ?></strong></div>
                    <div class="nay-list-item"><span>إشعار تسجيل مستخدم جديد</span><strong><?= $enableNewUser ? 'مفعّل' : 'موقوف' ?></strong></div>
                    <div class="nay-list-item"><span>إشعار طلب جديد</span><strong><?= $enableNewOrder ? 'مفعّل' : 'موقوف' ?></strong></div>
                    <div class="nay-list-item"><span>إشعار انخفاض المخزون</span><strong><?= $enableLowStock ? 'مفعّل' : 'موقوف' ?></strong></div>
                </div>
            </div>
            <div class="nay-card">
                <h3>اختصارات سريعة</h3>
                <div class="nay-links-grid">
                    <a class="nay-quick-link" href="/app/admin/settings/notifications.php">إعدادات الإشعارات<small>تشغيل وإيقاف مفاتيح التنبيه</small></a>
                    <a class="nay-quick-link" href="/app/admin/customers/index.php">الزبائن<small>مراجعة التسجيلات والتفعيل</small></a>
                    <a class="nay-quick-link" href="/app/admin/orders/index.php">الطلبات<small>متابعة الطلبات والدفعات</small></a>
                    <a class="nay-quick-link" href="/app/admin/influencers/list.php?status=2">طلبات المؤثرين<small>عرض المعلّق منها مباشرة</small></a>
                </div>
            </div>
        </div>

        <div class="nay-card">
            <div class="nay-card-header-inline">
                <h3>آخر الأحداث</h3>
                <span><?= number_format(count($events)) ?> عنصر</span>
            </div>
            <?php if (!$notificationsEnabled): ?>
                <div class="nay-empty">إشعارات الإدارة الداخلية متوقفة من الإعدادات حالياً.</div>
            <?php elseif (!$events): ?>
                <div class="nay-empty">حالياً ماكو أحداث ظاهرة بالمركز.</div>
            <?php else: ?>
                <div class="nay-table-wrap">
                    <table class="nay-table">
                        <thead>
                            <tr>
                                <th>النوع</th>
                                <th>العنوان</th>
                                <th>التفاصيل</th>
                                <th>الوقت</th>
                                <th>الانتقال</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($events as $event): ?>
                            <tr>
                                <td>
                                    <?php
                                    $badgeType = 'info';
                                    if (($event['severity'] ?? '') === 'success') $badgeType = 'success';
                                    elseif (($event['severity'] ?? '') === 'warn') $badgeType = 'warn';
                                    elseif (($event['severity'] ?? '') === 'danger') $badgeType = 'warn';
                                    echo hub_status_badge((string)$event['badge'], $badgeType);
                                    ?>
                                </td>
                                <td><strong><?= hub_h($event['title']) ?></strong></td>
                                <td><?= hub_h($event['message']) ?></td>
                                <td><?= hub_h($event['time_label']) ?></td>
                                <td><a class="nay-btn" href="<?= hub_h($event['link']) ?>">فتح</a></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
