<?php
if (!defined('ADMIN_PATH')) {
    define('ADMIN_PATH', ROOT_PATH . '/admin');
}

/* ── حماية المتغيرات ── */
$online_users    = $online_users    ?? 0;
$today_views     = $today_views     ?? 0;
$today_unique    = $today_unique    ?? 0;
$engagement      = $engagement      ?? 0;
$compare         = $compare         ?? 0;
$returning       = $returning       ?? 0;
$last7days       = $last7days       ?? [];
$top_pages_list  = $top_pages_list  ?? [];
$chart14         = $chart14         ?? [];
$recentOrders    = $recentOrders    ?? [];
$todayOrders     = $todayOrders     ?? [];
$yesterdayOrders = $yesterdayOrders ?? [];
$pendingNow      = $pendingNow      ?? 0;
$confirmRate     = $confirmRate     ?? 0;
$callbacksCount  = $callbacksCount  ?? 0;
$currency        = $currency        ?? 'DZD';
$top_page        = $top_page        ?? ['page_url' => '-', 'product_name' => '—'];

/* ── URL فلترة ── */
function dashboard_hidden_url(string $url): bool
{
    $path = parse_url($url, PHP_URL_PATH) ?? $url;
    $path = rtrim($path, '/');
    if ($path === '') $path = '/';

    $hidden = [
        '/robots.txt', '/sitemap.xml', '/order/success',
        '/submit-order', '/shell', '/cron',
    ];
    foreach ($hidden as $h) {
        if ($path === $h || str_starts_with($path, $h . '/') || str_starts_with($path, $h . '?')) {
            return true;
        }
    }
    // مسارات تقنية أخرى
    if (preg_match('~^/(cron|api|admin|shell|submit|webhook)~', $path)) return true;
    return false;
}

function pretty_page_label(string $url): string
{
    $path = parse_url($url, PHP_URL_PATH) ?? $url;
    $path = rtrim($path, '/');
    if ($path === '' || $path === '/') return __('dashboard.home', 'Home Page');

    if (preg_match('~^/product/([^/]+)$~', $path, $m)) {
        try {
            $identifier = rawurldecode((string)$m[1]);
            $_pm = new \Core\App\Models\ProductModel();
            $product = ctype_digit($identifier)
                ? ($_pm->getById((int)$identifier) ?? $_pm->getBySlug($identifier))
                : $_pm->getBySlug($identifier);
            $title = is_array($product) ? (string)($product['title'] ?? '') : '';
            if ($title) return __('dashboard.product', 'Product') . ': ' . $title;
        } catch (\Throwable $e) {}
        $readable = str_replace('-', ' ', rawurldecode($identifier));
        return __('dashboard.product', 'Product') . ': ' . $readable;
    }

    return $path;
}

/* ── حسابات المقارنة ── */
$todayTotal     = (int)($todayOrders['total']     ?? 0);
$todayConfirmed = (int)($todayOrders['confirmed']  ?? 0);
$todayRevenue   = (float)($todayOrders['revenue']  ?? 0);
$todayPending   = (int)($todayOrders['pending']    ?? 0);
$yesterTotal    = (int)($yesterdayOrders['total']  ?? 0);
$yesterRevenue  = (float)($yesterdayOrders['revenue'] ?? 0);

$ordersChange  = $yesterTotal > 0
    ? round((($todayTotal - $yesterTotal) / $yesterTotal) * 100, 1)
    : ($todayTotal > 0 ? 100 : 0);

$revenueChange = $yesterRevenue > 0
    ? round((($todayRevenue - $yesterRevenue) / $yesterRevenue) * 100, 1)
    : ($todayRevenue > 0 ? 100 : 0);

/* ── ألوان الحالة ── */
$statusColors = [
    'confirmed' => 'success',
    'pending'   => 'warning',
    'rejected'  => 'danger',
];
$statusLabels = [
    'confirmed' => __('orders.status_confirmed', 'Confirmed'),
    'pending'   => __('orders.status_pending',   'Pending'),
    'rejected'  => __('orders.status_rejected',  'Rejected'),
];

include ADMIN_PATH . '/templates/header.php';
?>

<div class="content-wrapper">
<section class="content pt-3">
<div class="container-fluid pb-5">

    <!-- ═══════════════════════════════════════
         HEADER
    ═══════════════════════════════════════ -->
    <div class="d-flex flex-wrap justify-content-between align-items-center gap-3 mb-4">
        <div>
            <h3 class="mb-0 fw-bold">
                <i class="bi bi-speedometer2 me-2 text-primary"></i>
                <?= __('dashboard.title', 'Dashboard') ?>
            </h3>
            <small class="text-muted">
                <?= __('dashboard.subtitle', 'Your store at a glance') ?> —
                <?= date('l, d F Y') ?>
            </small>
        </div>
        <div class="d-flex gap-2">
            <?php if ($pendingNow > 0): ?>
            <a href="/admin/orders?status=pending" class="btn btn-warning btn-sm fw-semibold">
                <i class="bi bi-hourglass-split me-1"></i>
                <?= $pendingNow ?> <?= __('dashboard.pending_orders', 'Pending Orders') ?>
            </a>
            <?php endif; ?>
            <?php if ($callbacksCount > 0): ?>
            <a href="/admin/orders/call-attempts" class="btn btn-info btn-sm text-white fw-semibold">
                <i class="bi bi-telephone-fill me-1"></i>
                <?= $callbacksCount ?> <?= __('dashboard.callbacks', 'Callbacks Due') ?>
            </a>
            <?php endif; ?>
        </div>
    </div>

    <!-- ═══════════════════════════════════════
         KPI CARDS — صف 1: طلبات اليوم
    ═══════════════════════════════════════ -->
    <div class="row g-3 mb-4">

        <!-- طلبات اليوم -->
        <div class="col-6 col-lg-3">
            <a href="/admin/orders" class="text-decoration-none">
            <div class="card border-0 shadow-sm h-100" style="border-top:3px solid #0d6efd !important">
                <div class="card-body px-4 py-3">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <div class="rounded-circle d-flex align-items-center justify-content-center bg-primary-subtle"
                             style="width:42px;height:42px">
                            <i class="bi bi-cart-check fs-5 text-primary"></i>
                        </div>
                        <?php if ($ordersChange != 0): ?>
                        <span class="badge <?= $ordersChange > 0 ? 'bg-success-subtle text-success' : 'bg-danger-subtle text-danger' ?> small">
                            <i class="bi bi-arrow-<?= $ordersChange > 0 ? 'up' : 'down' ?>"></i>
                            <?= abs($ordersChange) ?>%
                        </span>
                        <?php endif; ?>
                    </div>
                    <div class="fw-bold fs-2 lh-1 mb-1"><?= $todayTotal ?></div>
                    <div class="text-muted small"><?= __('dashboard.orders_today', 'Orders Today') ?></div>
                    <div class="text-muted" style="font-size:.72rem">
                        <?= $yesterTotal ?> <?= __('dashboard.yesterday', 'yesterday') ?>
                    </div>
                </div>
            </div>
            </a>
        </div>

        <!-- إيرادات اليوم -->
        <div class="col-6 col-lg-3">
            <div class="card border-0 shadow-sm h-100" style="border-top:3px solid #198754 !important">
                <div class="card-body px-4 py-3">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <div class="rounded-circle d-flex align-items-center justify-content-center bg-success-subtle"
                             style="width:42px;height:42px">
                            <i class="bi bi-cash-stack fs-5 text-success"></i>
                        </div>
                        <?php if ($revenueChange != 0): ?>
                        <span class="badge <?= $revenueChange > 0 ? 'bg-success-subtle text-success' : 'bg-danger-subtle text-danger' ?> small">
                            <i class="bi bi-arrow-<?= $revenueChange > 0 ? 'up' : 'down' ?>"></i>
                            <?= abs($revenueChange) ?>%
                        </span>
                        <?php endif; ?>
                    </div>
                    <div class="fw-bold fs-2 lh-1 mb-1"><?= number_format($todayRevenue) ?></div>
                    <div class="text-muted small"><?= __('dashboard.revenue_today', 'Revenue Today') ?> (<?= $currency ?>)</div>
                    <div class="text-muted" style="font-size:.72rem">
                        <?= number_format($yesterRevenue) ?> <?= __('dashboard.yesterday', 'yesterday') ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- معدل التأكيد -->
        <div class="col-6 col-lg-3">
            <a href="/admin/finance" class="text-decoration-none">
            <div class="card border-0 shadow-sm h-100" style="border-top:3px solid #0dcaf0 !important">
                <div class="card-body px-4 py-3">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <div class="rounded-circle d-flex align-items-center justify-content-center bg-info-subtle"
                             style="width:42px;height:42px">
                            <i class="bi bi-check-circle fs-5 text-info"></i>
                        </div>
                        <span class="badge <?= $confirmRate >= 50 ? 'bg-success-subtle text-success' : ($confirmRate >= 30 ? 'bg-warning-subtle text-warning' : 'bg-danger-subtle text-danger') ?>">
                            <?= $confirmRate >= 50 ? '✓ ' . __('dashboard.good','Good') : ($confirmRate >= 30 ? __('dashboard.average','Average') : __('dashboard.low','Low')) ?>
                        </span>
                    </div>
                    <div class="fw-bold fs-2 lh-1 mb-1"><?= $confirmRate ?>%</div>
                    <div class="text-muted small"><?= __('dashboard.confirm_rate', 'Confirm Rate') ?></div>
                    <div class="text-muted" style="font-size:.72rem"><?= __('dashboard.last_30_days','Last 30 days') ?></div>
                </div>
            </div>
            </a>
        </div>

        <!-- زوار اليوم -->
        <div class="col-6 col-lg-3">
            <div class="card border-0 shadow-sm h-100" style="border-top:3px solid #6f42c1 !important">
                <div class="card-body px-4 py-3">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <div class="rounded-circle d-flex align-items-center justify-content-center"
                             style="width:42px;height:42px;background:#6f42c120">
                            <i class="bi bi-people fs-5" style="color:#6f42c1"></i>
                        </div>
                        <?php if ($compare != 0): ?>
                        <span class="badge <?= $compare > 0 ? 'bg-success-subtle text-success' : 'bg-danger-subtle text-danger' ?> small">
                            <i class="bi bi-arrow-<?= $compare > 0 ? 'up' : 'down' ?>"></i>
                            <?= abs($compare) ?>%
                        </span>
                        <?php endif; ?>
                    </div>
                    <div class="fw-bold fs-2 lh-1 mb-1"><?= $today_unique ?></div>
                    <div class="text-muted small"><?= __('dashboard.today_visitors','Visitors Today') ?></div>
                    <div class="text-muted" style="font-size:.72rem">
                        <?= $online_users ?> <?= __('dashboard.online_now','online now') ?>
                    </div>
                </div>
            </div>
        </div>

    </div>

    <!-- ═══════════════════════════════════════
         CHARTS ROW
    ═══════════════════════════════════════ -->
    <div class="row g-3 mb-4">

        <!-- مخطط الطلبات والإيرادات — 14 يوم -->
        <div class="col-xl-8">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
                    <h6 class="mb-0 fw-semibold">
                        <i class="bi bi-graph-up me-2 text-muted"></i>
                        <?= __('dashboard.orders_14_days','Orders & Revenue — Last 14 Days') ?>
                    </h6>
                    <div class="d-flex gap-3 small text-muted">
                        <span><span class="d-inline-block rounded-circle me-1" style="width:8px;height:8px;background:#0d6efd"></span><?= __('dashboard.orders','Orders') ?></span>
                        <span><span class="d-inline-block rounded-circle me-1" style="width:8px;height:8px;background:#198754"></span><?= __('dashboard.revenue','Revenue') ?></span>
                    </div>
                </div>
                <div class="card-body">
                    <canvas id="ordersChart" height="120"></canvas>
                </div>
            </div>
        </div>

        <!-- حالة الطلبات اليوم -->
        <div class="col-xl-4">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-header bg-white border-bottom py-3">
                    <h6 class="mb-0 fw-semibold">
                        <i class="bi bi-pie-chart me-2 text-muted"></i>
                        <?= __('dashboard.today_orders_status','Today Orders Status') ?>
                    </h6>
                </div>
                <div class="card-body d-flex flex-column justify-content-center">
                    <?php if ($todayTotal > 0): ?>
                        <?php
                        $statuses = [
                            'confirmed' => ['count' => $todayConfirmed, 'color' => '#198754', 'icon' => 'bi-check-circle-fill'],
                            'pending'   => ['count' => $todayPending,   'color' => '#fd7e14', 'icon' => 'bi-hourglass-split'],
                            'rejected'  => ['count' => (int)($todayOrders['rejected'] ?? 0), 'color' => '#dc3545', 'icon' => 'bi-x-circle-fill'],
                        ];
                        foreach ($statuses as $key => $s): ?>
                        <div class="d-flex align-items-center gap-3 mb-3">
                            <i class="bi <?= $s['icon'] ?> fs-5" style="color:<?= $s['color'] ?>"></i>
                            <div class="flex-grow-1">
                                <div class="d-flex justify-content-between mb-1">
                                    <span class="small fw-semibold"><?= $statusLabels[$key] ?></span>
                                    <span class="small fw-bold"><?= $s['count'] ?></span>
                                </div>
                                <div class="progress" style="height:5px">
                                    <div class="progress-bar" style="width:<?= $todayTotal > 0 ? round($s['count']/$todayTotal*100) : 0 ?>%;background:<?= $s['color'] ?>"></div>
                                </div>
                            </div>
                            <span class="small text-muted" style="min-width:32px;text-align:right">
                                <?= $todayTotal > 0 ? round($s['count']/$todayTotal*100) : 0 ?>%
                            </span>
                        </div>
                        <?php endforeach; ?>

                        <div class="pt-3 mt-1 border-top text-center">
                            <div class="fw-bold fs-4"><?= number_format($todayRevenue) ?> <?= $currency ?></div>
                            <div class="text-muted small"><?= __('dashboard.confirmed_revenue','Confirmed Revenue Today') ?></div>
                        </div>
                    <?php else: ?>
                        <div class="text-center text-muted py-4">
                            <i class="bi bi-inbox fs-1 d-block mb-2 opacity-50"></i>
                            <?= __('dashboard.no_orders_today','No orders today yet') ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

    </div>

    <!-- ═══════════════════════════════════════
         RECENT ORDERS + TOP PAGES
    ═══════════════════════════════════════ -->
    <div class="row g-3">

        <!-- أحدث الطلبات -->
        <div class="col-xl-7">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
                    <h6 class="mb-0 fw-semibold">
                        <i class="bi bi-receipt me-2 text-muted"></i>
                        <?= __('dashboard.recent_orders','Recent Orders') ?>
                    </h6>
                    <a href="/admin/orders" class="btn btn-sm btn-outline-primary">
                        <?= __('dashboard.view_all','View All') ?>
                        <i class="bi bi-arrow-left ms-1"></i>
                    </a>
                </div>
                <div class="card-body p-0">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th class="ps-3">#</th>
                                <th><?= __('orders.customer','Customer') ?></th>
                                <th><?= __('orders.product','Product') ?></th>
                                <th><?= __('orders.total','Total') ?></th>
                                <th><?= __('orders.status','Status') ?></th>
                                <th class="text-muted small"><?= __('orders.time','Time') ?></th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php if (empty($recentOrders)): ?>
                            <tr><td colspan="6" class="text-center text-muted py-4">
                                <?= __('dashboard.no_orders','No orders yet') ?>
                            </td></tr>
                        <?php else: ?>
                            <?php foreach ($recentOrders as $o): ?>
                            <tr style="cursor:pointer" onclick="location.href='/admin/orders/view/<?= (int)$o['id'] ?>'">
                                <td class="ps-3 fw-semibold text-primary">#<?= (int)$o['id'] ?></td>
                                <td>
                                    <div class="fw-semibold small"><?= htmlspecialchars($o['full_name']) ?></div>
                                    <div class="text-muted" style="font-size:.72rem"><?= htmlspecialchars($o['phone']) ?></div>
                                </td>
                                <td class="small text-muted">
                                    <?= htmlspecialchars(mb_substr($o['product_name'] ?? '—', 0, 25)) ?>
                                </td>
                                <td class="fw-semibold small"><?= number_format((float)$o['total_amount']) ?></td>
                                <td>
                                    <span class="badge bg-<?= $statusColors[$o['order_status']] ?? 'secondary' ?>-subtle
                                                       text-<?= $statusColors[$o['order_status']] ?? 'secondary' ?>">
                                        <?= $statusLabels[$o['order_status']] ?? $o['order_status'] ?>
                                    </span>
                                </td>
                                <td class="text-muted" style="font-size:.72rem;white-space:nowrap">
                                    <?= date('H:i', strtotime($o['created_local'])) ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- أكثر الصفحات زيارة -->
        <div class="col-xl-5">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-header bg-white border-bottom py-3">
                    <h6 class="mb-0 fw-semibold">
                        <i class="bi bi-bar-chart-steps me-2 text-muted"></i>
                        <?= __('dashboard.top_products','Top Visited Products') ?>
                    </h6>
                </div>
                <div class="card-body">
                    <?php
                    $maxViews = 0;
                    $visiblePages = [];
                    foreach ($top_pages_list as $p) {
                        $u = (string)($p['page_url'] ?? '');
                        if ($u === '' || dashboard_hidden_url($u)) continue;
                        $visiblePages[] = $p;
                        if ((int)$p['views'] > $maxViews) $maxViews = (int)$p['views'];
                    }
                    ?>
                    <?php if (empty($visiblePages)): ?>
                        <div class="text-center text-muted py-4">
                            <i class="bi bi-bar-chart fs-2 d-block mb-2 opacity-50"></i>
                            <?= __('dashboard.no_data','No data yet') ?>
                        </div>
                    <?php else: ?>
                        <div class="d-flex flex-column gap-3">
                        <?php foreach ($visiblePages as $p):
                            $label = (string)($p['product_name'] ?? '');
                            if ($label === '') {
                                $label = pretty_page_label((string)$p['page_url']);
                            }
                            $views = (int)$p['views'];
                            $pct   = $maxViews > 0 ? round($views / $maxViews * 100) : 0;
                        ?>
                            <div>
                                <div class="d-flex justify-content-between mb-1">
                                    <span class="small fw-semibold text-truncate" style="max-width:220px">
                                        <?= htmlspecialchars($label) ?>
                                    </span>
                                    <span class="small text-muted ms-2 flex-shrink-0">
                                        <?= number_format($views) ?> <?= __('dashboard.views','views') ?>
                                    </span>
                                </div>
                                <div class="progress" style="height:4px;border-radius:2px">
                                    <div class="progress-bar bg-primary" style="width:<?= $pct ?>%"></div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                        </div>

                        <!-- Insight صغير -->
                        <div class="mt-4 pt-3 border-top d-flex align-items-center gap-2">
                            <i class="bi bi-info-circle text-muted"></i>
                            <span class="small text-muted">
                                <?= $compare >= 0
                                    ? __('dashboard.better_than_yesterday','Better than yesterday') . ' +' . abs($compare) . '%'
                                    : __('dashboard.worse_than_yesterday','Worse than yesterday') . ' -' . abs($compare) . '%' ?>
                                &nbsp;·&nbsp;
                                <?= $returning ?> <?= __('dashboard.returning_visitors','returning') ?>
                            </span>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

    </div>

</div>
</section>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js@4/dist/chart.umd.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {

    const chart14 = <?= json_encode($chart14) ?>;

    // نملأ الأيام الناقصة في آخر 14 يوم
    const today = new Date();
    const labels = [], ordersData = [], revenueData = [];
    for (let i = 13; i >= 0; i--) {
        const d = new Date(today);
        d.setDate(d.getDate() - i);
        const key = d.toISOString().slice(0, 10);
        labels.push(d.toLocaleDateString('<?= \Core\System\Language::code() === 'ar' ? 'ar-DZ' : 'en-GB' ?>', { day: 'numeric', month: 'short' }));
        const row = chart14.find(r => r.day === key);
        ordersData.push(row ? parseInt(row.orders) : 0);
        revenueData.push(row ? parseFloat(row.revenue) : 0);
    }

    const isDark = document.documentElement.classList.contains('dark-mode') ||
                   window.matchMedia('(prefers-color-scheme: dark)').matches;
    const gridColor  = isDark ? 'rgba(255,255,255,.08)' : 'rgba(0,0,0,.06)';
    const tickColor  = isDark ? '#9ca3af' : '#6b7280';

    new Chart(document.getElementById('ordersChart'), {
        type: 'bar',
        data: {
            labels,
            datasets: [
                {
                    label: '<?= __('dashboard.orders','Orders') ?>',
                    data: ordersData,
                    backgroundColor: 'rgba(13,110,253,.75)',
                    borderRadius: 5,
                    yAxisID: 'y',
                    order: 2,
                },
                {
                    label: '<?= __('dashboard.revenue','Revenue') ?> (<?= $currency ?>)',
                    data: revenueData,
                    type: 'line',
                    borderColor: '#198754',
                    backgroundColor: 'rgba(25,135,84,.1)',
                    borderWidth: 2.5,
                    pointRadius: 3,
                    fill: true,
                    tension: .35,
                    yAxisID: 'y2',
                    order: 1,
                }
            ]
        },
        options: {
            responsive: true,
            interaction: { mode: 'index', intersect: false },
            plugins: {
                legend: { display: true, labels: { boxWidth: 10, font: { size: 11 }, color: tickColor } }
            },
            scales: {
                x: { grid: { color: gridColor }, ticks: { color: tickColor, font: { size: 10 } } },
                y:  { grid: { color: gridColor }, ticks: { color: tickColor, font: { size: 10 } }, beginAtZero: true, position: 'right' },
                y2: { grid: { display: false },   ticks: { color: '#198754', font: { size: 10 } }, beginAtZero: true, position: 'left' }
            }
        }
    });
});
</script>

<?php include ADMIN_PATH . '/templates/footer.php'; ?>