<?php $__env->startSection('title'); ?>داشبورد<?php $__env->stopSection(); ?>

<?php $__env->startSection('content'); ?>
<div class="container-xxl flex-grow-1 container-p-y">

    
    <div class="d-flex flex-wrap justify-content-between align-items-center mb-4 gap-2">
        <div>
            <h4 class="mb-1">داشبورد مدیریت</h4>
            <p class="text-muted mb-0">خوش آمدید، <?php echo e(Auth::user()->first_name); ?> — <?php echo e(\App\Models\Order::toJalaliString(now())); ?></p>
        </div>
        <button type="button" class="btn btn-outline-primary btn-sm" id="statsRefreshBtn">
            <i class="ti ti-refresh ti-xs me-1"></i>به‌روزرسانی آمار
        </button>
    </div>

    <?php if(!$cronActive): ?>
    <div class="alert alert-warning alert-dismissible fade show border-warning mb-4 cron-alert" role="alert">
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="بستن"></button>
        <div class="d-flex align-items-start gap-2">
            <i class="ti ti-alert-triangle ti-md mt-1 text-warning flex-shrink-0"></i>
            <div class="flex-grow-1 min-w-0">
                <h6 class="mb-1 fw-bold">Cron Job تنظیم نشده است</h6>
                <p class="mb-2 small">زمان‌بند Laravel اجرا نمی‌شود. بدون آن، سفارش‌های پرداخت‌نشده به‌صورت خودکار لغو نخواهند شد.</p>
                <pre class="bg-dark text-white rounded p-2 small mb-0 user-select-all cron-snippet">* * * * * cd <?php echo e(base_path()); ?> && php artisan schedule:run >> /dev/null 2>&1</pre>
            </div>
        </div>
    </div>
    <?php endif; ?>

    
    <?php if($stats['pending_orders'] || $stats['pending_reviews'] || $stats['open_tickets'] || $stats['low_stock']): ?>
    <div class="row g-3 mb-4">
        <?php if($stats['pending_orders'] > 0): ?>
        <div class="col-md-3 col-sm-6">
            <a href="<?php echo e(route('admin.orders.index', ['status' => 'paid'])); ?>" class="text-decoration-none">
                <div class="card border-warning h-100 mb-0">
                    <div class="card-body d-flex align-items-center gap-3 py-3">
                        <span class="badge bg-label-warning rounded p-2"><i class="ti ti-truck ti-sm"></i></span>
                        <div>
                            <h5 class="mb-0 text-warning" data-stat="pending_orders"><?php echo e($stats['pending_orders']); ?></h5>
                            <small class="text-muted">در انتظار ارسال</small>
                        </div>
                    </div>
                </div>
            </a>
        </div>
        <?php endif; ?>
        <?php if($stats['pending_reviews'] > 0): ?>
        <div class="col-md-3 col-sm-6">
            <a href="<?php echo e(route('admin.reviews.index', ['status' => 'pending'])); ?>" class="text-decoration-none">
                <div class="card border-danger h-100 mb-0">
                    <div class="card-body d-flex align-items-center gap-3 py-3">
                        <span class="badge bg-label-danger rounded p-2"><i class="ti ti-message-dots ti-sm"></i></span>
                        <div>
                            <h5 class="mb-0 text-danger" data-stat="pending_reviews"><?php echo e($stats['pending_reviews']); ?></h5>
                            <small class="text-muted">دیدگاه در انتظار</small>
                        </div>
                    </div>
                </div>
            </a>
        </div>
        <?php endif; ?>
        <?php if($stats['open_tickets'] > 0): ?>
        <div class="col-md-3 col-sm-6">
            <a href="<?php echo e(route('admin.tickets.index')); ?>" class="text-decoration-none">
                <div class="card border-info h-100 mb-0">
                    <div class="card-body d-flex align-items-center gap-3 py-3">
                        <span class="badge bg-label-info rounded p-2"><i class="ti ti-headset ti-sm"></i></span>
                        <div>
                            <h5 class="mb-0 text-info" data-stat="open_tickets"><?php echo e($stats['open_tickets']); ?></h5>
                            <small class="text-muted">تیکت باز</small>
                        </div>
                    </div>
                </div>
            </a>
        </div>
        <?php endif; ?>
        <?php if($stats['low_stock'] > 0): ?>
        <div class="col-md-3 col-sm-6">
            <a href="<?php echo e(route('admin.products.index')); ?>" class="text-decoration-none">
                <div class="card border-secondary h-100 mb-0">
                    <div class="card-body d-flex align-items-center gap-3 py-3">
                        <span class="badge bg-label-secondary rounded p-2"><i class="ti ti-package ti-sm"></i></span>
                        <div>
                            <h5 class="mb-0" data-stat="low_stock"><?php echo e($stats['low_stock']); ?></h5>
                            <small class="text-muted">موجودی کم (≤۵)</small>
                        </div>
                    </div>
                </div>
            </a>
        </div>
        <?php endif; ?>
    </div>
    <?php endif; ?>

    
    <div class="row g-3 mb-4" id="statsCard">
        <div class="col-xl-3 col-sm-6">
            <div class="card h-100">
                <div class="card-body">
                    <div class="d-flex align-items-start justify-content-between">
                        <div class="content-left">
                            <span class="fw-medium d-block mb-1">درآمد (۳۰ روز)</span>
                            <div class="d-flex align-items-center mb-1">
                                <h4 class="mb-0 me-1"><span data-stat="revenue"><?php echo e(number_format($stats['revenue'])); ?></span></h4>
                                <small class="text-muted">تومان</small>
                            </div>
                            <small class="text-success">
                                امروز: <span data-stat="today_revenue"><?php echo e(number_format($stats['today_revenue'])); ?></span> تومان
                            </small>
                        </div>
                        <span class="badge bg-label-success rounded p-2"><i class="ti ti-coins ti-md"></i></span>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-sm-6">
            <div class="card h-100">
                <div class="card-body">
                    <div class="d-flex align-items-start justify-content-between">
                        <div class="content-left">
                            <span class="fw-medium d-block mb-1">سفارش (۳۰ روز)</span>
                            <h4 class="mb-1" data-stat="sales"><?php echo e(number_format($stats['sales'])); ?></h4>
                            <small class="text-primary">
                                امروز: <span data-stat="today_sales"><?php echo e(number_format($stats['today_sales'])); ?></span> سفارش
                            </small>
                        </div>
                        <span class="badge bg-label-primary rounded p-2"><i class="ti ti-chart-pie-2 ti-md"></i></span>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-sm-6">
            <div class="card h-100">
                <div class="card-body">
                    <div class="d-flex align-items-start justify-content-between">
                        <div class="content-left">
                            <span class="fw-medium d-block mb-1">مشتریان</span>
                            <h4 class="mb-1" data-stat="customers"><?php echo e(number_format($stats['customers'])); ?></h4>
                            <small class="text-muted">کاربر ثبت‌نام شده</small>
                        </div>
                        <span class="badge bg-label-info rounded p-2"><i class="ti ti-users ti-md"></i></span>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-sm-6">
            <div class="card h-100">
                <div class="card-body">
                    <div class="d-flex align-items-start justify-content-between">
                        <div class="content-left">
                            <span class="fw-medium d-block mb-1">محصولات فعال</span>
                            <h4 class="mb-1" data-stat="products"><?php echo e(number_format($stats['products'])); ?></h4>
                            <small class="text-muted">در فروشگاه</small>
                        </div>
                        <span class="badge bg-label-danger rounded p-2"><i class="ti ti-shopping-cart ti-md"></i></span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    
    <div class="row g-3 mb-4">
        <div class="col-lg-8">
            <div class="card h-100">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="card-title mb-0">روند فروش (۳۰ روز گذشته)</h5>
                    <small class="text-muted">به‌روزرسانی: <span id="statsUpdatedAt">هم اکنون</span></small>
                </div>
                <div class="card-body">
                    <div id="revenueChart"></div>
                </div>
            </div>
        </div>
        <div class="col-lg-4">
            <div class="card h-100">
                <div class="card-header">
                    <h5 class="card-title mb-0">وضعیت سفارشات</h5>
                </div>
                <div class="card-body d-flex flex-column justify-content-center">
                    <?php if(count($statusBreakdown['values'])): ?>
                    <div id="statusChart"></div>
                    <?php else: ?>
                    <p class="text-muted text-center mb-0 py-5">هنوز سفارشی ثبت نشده است.</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    
    <div class="row g-3">
        <div class="col-lg-8">
            <div class="card h-100">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="card-title mb-0">آخرین سفارشات</h5>
                    <a href="<?php echo e(route('admin.orders.index')); ?>" class="btn btn-sm btn-outline-primary">مشاهده همه</a>
                </div>
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>شماره</th>
                                <th>مشتری</th>
                                <th>مبلغ</th>
                                <th>وضعیت</th>
                                <th>تاریخ</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $__empty_1 = true; $__currentLoopData = $recentOrders; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $order): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                            <tr>
                                <td class="font-monospace small" dir="ltr"><?php echo e($order->order_number); ?></td>
                                <td>
                                    <div class="fw-medium small"><?php echo e($order->user->first_name ?? ''); ?> <?php echo e($order->user->last_name ?? ''); ?></div>
                                    <div class="text-muted small" dir="ltr"><?php echo e($order->user->mobile ?? '—'); ?></div>
                                </td>
                                <td class="small fw-bold"><?php echo e(number_format($order->payable_amount)); ?> ت</td>
                                <td>
                                    <span class="badge bg-label-<?php echo e($order->statusColor()); ?>"><?php echo e($order->statusLabel()); ?></span>
                                </td>
                                <td class="text-muted small"><?php echo e($order->shamsi_date ?? \App\Models\Order::toJalaliString($order->created_at)); ?></td>
                                <td>
                                    <a href="<?php echo e(route('admin.orders.show', $order->order_number)); ?>" class="btn btn-sm btn-icon btn-outline-secondary">
                                        <i class="ti ti-eye ti-xs"></i>
                                    </a>
                                </td>
                            </tr>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                            <tr>
                                <td colspan="6" class="text-center text-muted py-4">سفارشی ثبت نشده است.</td>
                            </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="col-lg-4">
            <div class="card h-100">
                <div class="card-header">
                    <h5 class="card-title mb-0">دسترسی سریع</h5>
                </div>
                <div class="card-body">
                    <div class="d-grid gap-2">
                        <a href="<?php echo e(route('admin.orders.index', ['status' => 'paid'])); ?>" class="btn btn-outline-warning justify-content-start">
                            <i class="ti ti-truck me-2"></i>سفارشات در انتظار ارسال
                            <?php if($stats['pending_orders'] > 0): ?>
                            <span class="badge bg-warning text-dark ms-auto"><?php echo e($stats['pending_orders']); ?></span>
                            <?php endif; ?>
                        </a>
                        <a href="<?php echo e(route('admin.products.create')); ?>" class="btn btn-outline-primary justify-content-start">
                            <i class="ti ti-plus me-2"></i>محصول جدید
                        </a>
                        <a href="<?php echo e(route('admin.announcements.create')); ?>" class="btn btn-outline-info justify-content-start">
                            <i class="ti ti-bell me-2"></i>اطلاعیه جدید
                        </a>
                        <a href="<?php echo e(route('admin.reviews.index')); ?>" class="btn btn-outline-danger justify-content-start">
                            <i class="ti ti-message-dots me-2"></i>مدیریت دیدگاه‌ها
                            <?php if($stats['pending_reviews'] > 0): ?>
                            <span class="badge bg-danger ms-auto"><?php echo e($stats['pending_reviews']); ?></span>
                            <?php endif; ?>
                        </a>
                        <a href="<?php echo e(route('admin.users.index')); ?>" class="btn btn-outline-secondary justify-content-start">
                            <i class="ti ti-users me-2"></i>لیست کاربران
                        </a>
                        <a href="<?php echo e(route('admin.settings.main')); ?>" class="btn btn-outline-secondary justify-content-start">
                            <i class="ti ti-settings me-2"></i>تنظیمات اصلی
                        </a>
                        <a href="<?php echo e(route('admin.settings.appearance')); ?>" class="btn btn-outline-secondary justify-content-start">
                            <i class="ti ti-palette me-2"></i>تنظیمات ظاهری
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('customjs'); ?>
<script>
(function () {
    var chartLabels  = <?php echo json_encode($chart['labels'], 15, 512) ?>;
    var chartRevenue = <?php echo json_encode($chart['revenue'], 15, 512) ?>;
    var chartOrders  = <?php echo json_encode($chart['orders'], 15, 512) ?>;
    var statusLabels = <?php echo json_encode($statusBreakdown['labels'], 15, 512) ?>;
    var statusValues = <?php echo json_encode($statusBreakdown['values'], 15, 512) ?>;
    var statusColors = <?php echo json_encode($statusBreakdown['colors'], 15, 512) ?>;
    var endpoint     = <?php echo json_encode(route('admin.stats.json'), 15, 512) ?>;

    // Revenue & orders line chart
    if (document.querySelector('#revenueChart') && typeof ApexCharts !== 'undefined') {
        new ApexCharts(document.querySelector('#revenueChart'), {
            chart: { type: 'area', height: 320, toolbar: { show: false }, fontFamily: 'inherit' },
            series: [
                { name: 'درآمد (تومان)', data: chartRevenue },
                { name: 'تعداد سفارش', data: chartOrders },
            ],
            colors: ['#696cff', '#03c3ec'],
            dataLabels: { enabled: false },
            stroke: { curve: 'smooth', width: 2 },
            fill: { type: 'gradient', gradient: { opacityFrom: 0.4, opacityTo: 0.05 } },
            xaxis: { categories: chartLabels, labels: { rotate: -45, style: { fontSize: '11px' } } },
            yaxis: [
                { title: { text: 'تومان' }, labels: { formatter: function (v) { return new Intl.NumberFormat('en-US').format(Math.round(v)); } } },
                { opposite: true, title: { text: 'سفارش' }, labels: { formatter: function (v) { return Math.round(v); } } },
            ],
            tooltip: {
                shared: true,
                y: { formatter: function (v, opts) { return opts.seriesIndex === 0 ? new Intl.NumberFormat('en-US').format(v) + ' تومان' : v + ' سفارش'; } },
            },
            legend: { position: 'top', horizontalAlign: 'right' },
            grid: { borderColor: '#f1f1f1' },
        }).render();
    }

    // Order status donut
    if (document.querySelector('#statusChart') && statusValues.length && typeof ApexCharts !== 'undefined') {
        new ApexCharts(document.querySelector('#statusChart'), {
            chart: { type: 'donut', height: 280, fontFamily: 'inherit' },
            series: statusValues,
            labels: statusLabels,
            colors: statusColors,
            legend: { position: 'bottom' },
            plotOptions: { pie: { donut: { size: '65%', labels: { show: true, total: { show: true, label: 'کل سفارشات' } } } } },
            dataLabels: { enabled: true },
        }).render();
    }

    // Refresh stats via AJAX
    var btn       = document.getElementById('statsRefreshBtn');
    var updatedEl = document.getElementById('statsUpdatedAt');
    if (btn) {
        btn.addEventListener('click', function () {
            var icon = btn.querySelector('i');
            if (btn.disabled) return;
            btn.disabled = true;
            if (icon) icon.classList.add('ti-spin');

            fetch(endpoint, {
                headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
                credentials: 'same-origin',
            })
            .then(function (r) { return r.json(); })
            .then(function (j) {
                if (!j || !j.ok || !j.stats) throw new Error('invalid');
                Object.keys(j.stats).forEach(function (key) {
                    document.querySelectorAll('[data-stat="' + key + '"]').forEach(function (el) {
                        el.textContent = new Intl.NumberFormat('en-US').format(j.stats[key]);
                    });
                });
                if (updatedEl) updatedEl.textContent = j.updated_at || 'هم اکنون';
            })
            .catch(function () {
                if (typeof Swal !== 'undefined') {
                    Swal.fire({ icon: 'error', title: 'خطا', text: 'به‌روزرسانی آمار با خطا مواجه شد.', timer: 2000, showConfirmButton: false });
                }
            })
            .finally(function () {
                btn.disabled = false;
                if (icon) icon.classList.remove('ti-spin');
            });
        });
    }
})();
</script>
<style>
.ti-spin { animation: tiSpin 0.9s linear infinite; }
@keyframes tiSpin { from { transform: rotate(0); } to { transform: rotate(360deg); } }
.cron-alert .min-w-0 { min-width: 0; }
.cron-alert .cron-snippet {
    white-space: pre-wrap;
    word-break: break-all;
    overflow-wrap: anywhere;
    direction: ltr;
    text-align: left;
    max-width: 100%;
}
</style>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('admin.layouts.layout', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /home/louishop/public_html/engine/resources/views/admin/index.blade.php ENDPATH**/ ?>