@extends('admin.layouts.layout')
@section('title', 'تجزیه و تحلیل')

@section('customhead')
<link rel="stylesheet" href="{{ url('theme/admin/vendor/libs/persian-datepicker/css/persian-datepicker.min.css') }}">
<style>
    .analytics-period .btn { border-radius: .5rem; }
    .analytics-kpi .card { height: 100%; }
    .analytics-kpi .kpi-value { font-size: 1.35rem; font-weight: 700; line-height: 1.2; }
    .analytics-kpi .kpi-label { font-size: .8rem; color: #a5a3ae; }
    #customRangeBox { display: none; }
    #customRangeBox.is-visible { display: block; }
    .chart-box { min-height: 320px; }
    .analytics-print-title { display: none; }

    @media print {
        @page { size: A4 landscape; margin: 10mm; }

        html, body {
            background: #fff !important;
            height: auto !important;
            overflow: visible !important;
            -webkit-print-color-adjust: exact !important;
            print-color-adjust: exact !important;
        }

        .layout-menu,
        .layout-navbar,
        .layout-footer,
        .content-backdrop,
        .layout-overlay,
        .drag-target,
        .analytics-filter-card,
        .analytics-screen-title {
            display: none !important;
        }

        .layout-wrapper,
        .layout-container,
        .layout-page,
        .content-wrapper {
            display: block !important;
            width: 100% !important;
            max-width: 100% !important;
            margin: 0 !important;
            padding: 0 !important;
            padding-top: 0 !important;
            padding-inline: 0 !important;
            min-height: 0 !important;
            height: auto !important;
            overflow: visible !important;
            position: static !important;
            background: #fff !important;
        }

        #analyticsPrintArea {
            display: block !important;
            width: 100% !important;
            max-width: 100% !important;
            margin: 0 !important;
            padding: 0 !important;
            position: static !important;
        }

        .analytics-print-title {
            display: block !important;
            margin-bottom: 10px !important;
            border-bottom: 1px solid #ccc;
            padding-bottom: 6px;
        }
        .analytics-print-title h3 { font-size: 14pt; margin: 0 0 4px; }
        .analytics-print-title p { font-size: 9pt; color: #555; margin: 0; }

        .card {
            box-shadow: none !important;
            border: 1px solid #ccc !important;
            background: #fff !important;
            height: auto !important;
            margin-bottom: 8px !important;
            overflow: hidden !important;
            break-inside: avoid;
            page-break-inside: avoid;
        }
        .card.h-100 { height: auto !important; }
        .card-header {
            padding: 6px 10px !important;
            background: #f3f3f3 !important;
        }
        .card-header .card-title { font-size: 10pt; margin: 0; }
        .card-body { padding: 8px !important; }

        /* ردیف‌ها: فلکس ساده بدون margin منفی بوت‌استرپ */
        #analyticsPrintArea .row {
            display: flex !important;
            flex-wrap: wrap !important;
            margin: 0 !important;
            width: 100% !important;
            --bs-gutter-x: 0.5rem;
            --bs-gutter-y: 0.5rem;
        }
        #analyticsPrintArea .row > [class*="col-"] {
            box-sizing: border-box !important;
            position: relative !important;
            float: none !important;
            left: auto !important;
            right: auto !important;
            padding-left: 0.25rem !important;
            padding-right: 0.25rem !important;
            margin: 0 0 0.5rem !important;
            min-width: 0 !important;
            /* پیش‌فرض: تمام‌عرض زیر هم */
            flex: 0 0 100% !important;
            width: 100% !important;
            max-width: 100% !important;
        }

        /* KPI: ۴تایی در یک ردیف */
        #analyticsPrintArea .analytics-kpi > [class*="col-"] {
            flex: 0 0 25% !important;
            width: 25% !important;
            max-width: 25% !important;
        }
        .analytics-kpi .kpi-value { font-size: 10pt !important; }
        .analytics-kpi .kpi-label,
        .analytics-kpi .small { font-size: 7pt !important; color: #666 !important; }
        .analytics-kpi .badge { display: none !important; }

        /* نمودارها: دو ستونه */
        #analyticsPrintArea .analytics-charts > [class*="col-"] {
            flex: 0 0 50% !important;
            width: 50% !important;
            max-width: 50% !important;
        }

        .chart-box {
            min-height: 160px !important;
            height: 160px !important;
            overflow: hidden !important;
        }

        .table {
            font-size: 8pt !important;
            width: 100% !important;
            table-layout: fixed !important;
        }
        .table th, .table td {
            padding: 3px 5px !important;
            border-color: #ddd !important;
            word-wrap: break-word !important;
            overflow-wrap: anywhere !important;
        }
        .table-responsive {
            display: block !important;
            overflow: visible !important;
            width: 100% !important;
        }

        .alert { padding: 6px 10px !important; font-size: 9pt !important; }
        a[href]::after { content: none !important; }
        .mb-4, .mb-2 { margin-bottom: 8px !important; }
    }
</style>
@endsection

@section('content')
@php
    $k = $data['kpis'];
    $c = $data['charts'];
    $t = $data['tables'];
    $r = $data['range'];
    $fmt = fn ($n) => number_format((int) $n);
@endphp

<div class="container-xxl flex-grow-1 container-p-y" id="analyticsPrintArea">

    <div class="d-flex flex-wrap justify-content-between align-items-center mb-4 gap-2 analytics-screen-title">
        <div>
            <h4 class="mb-1">تجزیه و تحلیل فروشگاه</h4>
            <p class="text-muted mb-0 small">
                بازه: <strong>{{ $r['label'] }}</strong>
                <span class="mx-1">·</span>
                {{ $r['from_jalali'] }} تا {{ $r['to_jalali'] }}
            </p>
        </div>
        <button type="button" class="btn btn-outline-secondary" id="btnPrintAnalytics">
            <i class="ti ti-printer me-1"></i>
            پرینت گزارش
        </button>
    </div>

    <div class="analytics-print-title mb-3">
        <h3 class="mb-1">گزارش تجزیه و تحلیل — بیاتوشاپ</h3>
        <p class="mb-0">بازه: {{ $r['label'] }} · {{ $r['from_jalali'] }} تا {{ $r['to_jalali'] }}</p>
    </div>

    @if($error)
    <div class="alert alert-warning mb-4">{{ $error }}</div>
    @endif

    {{-- Period filter --}}
    <div class="card mb-4 analytics-filter-card">
        <div class="card-body">
            <form method="GET" action="{{ route('admin.analytics.index') }}" id="analyticsFilterForm">
                <div class="d-flex flex-wrap gap-2 analytics-period mb-0">
                    @foreach($periods as $key => $label)
                        @if($key === 'custom')
                            <button type="button" id="btnCustomPeriod"
                                    class="btn btn-sm {{ $period === 'custom' ? 'btn-primary' : 'btn-outline-secondary' }}">
                                {{ $label }}
                            </button>
                        @else
                            <button type="submit" name="period" value="{{ $key }}"
                                    class="btn btn-sm period-preset-btn {{ $period === $key ? 'btn-primary' : 'btn-outline-secondary' }}">
                                {{ $label }}
                            </button>
                        @endif
                    @endforeach
                </div>

                <div id="customRangeBox" class="mt-3 {{ $period === 'custom' ? 'is-visible' : '' }}">
                    <div class="row g-2 align-items-end">
                        <div class="col-md-3">
                            <label class="form-label small">از تاریخ</label>
                            <input type="text" name="from" id="fromJalali" class="form-control"
                                   value="{{ $from }}" placeholder="۱۴۰۵/۰۱/۰۱" autocomplete="off">
                        </div>
                        <div class="col-md-3">
                            <label class="form-label small">تا تاریخ</label>
                            <input type="text" name="to" id="toJalali" class="form-control"
                                   value="{{ $to }}" placeholder="۱۴۰۵/۰۱/۳۱" autocomplete="off">
                        </div>
                        <div class="col-auto">
                            <button type="submit" name="period" value="custom" class="btn btn-primary">
                                <i class="ti ti-filter ti-xs me-1"></i>اعمال بازه
                            </button>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    {{-- KPIs --}}
    <div class="row g-3 mb-4 analytics-kpi">
        <div class="col-xl-3 col-sm-6">
            <div class="card"><div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="kpi-label mb-1">تعداد محصولات فروخته‌شده</div>
                        <div class="kpi-value text-primary">{{ $fmt($k['items_sold']) }}</div>
                    </div>
                    <span class="badge bg-label-primary p-2"><i class="ti ti-package"></i></span>
                </div>
                <div class="text-muted small mt-2">{{ $fmt($k['orders_count']) }} سفارش موفق</div>
            </div></div>
        </div>
        <div class="col-xl-3 col-sm-6">
            <div class="card"><div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="kpi-label mb-1">مبلغ کل فروش</div>
                        <div class="kpi-value text-muted">{{ $fmt($k['revenue']) }}</div>
                    </div>
                    <span class="badge bg-label-secondary p-2"><i class="ti ti-currency-dollar"></i></span>
                </div>
                <div class="text-muted small mt-2">شامل هزینه ارسال و استفاده از کیف پول</div>
            </div></div>
        </div>
        <div class="col-xl-3 col-sm-6">
            <div class="card"><div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="kpi-label mb-1">هزینه ارسال</div>
                        <div class="kpi-value text-info">{{ $fmt($k['shipping']) }}</div>
                    </div>
                    <span class="badge bg-label-info p-2"><i class="ti ti-truck"></i></span>
                </div>
                <div class="text-muted small mt-2">جمع تخفیف‌ها: {{ $fmt($k['discounts']) }} تومان</div>
            </div></div>
        </div>
        <div class="col-xl-3 col-sm-6">
            <div class="card"><div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="kpi-label mb-1">جمع خالص فروش</div>
                        <div class="kpi-value text-success">{{ $fmt($k['net_sales'] ?? 0) }} <small class="text-success fs-6">تومان</small></div>
                    </div>
                    <span class="badge bg-label-success p-2"><i class="ti ti-cash"></i></span>
                </div>
                <div class="text-muted small mt-2">مبلغ پرداخت‌شده منهای هزینه ارسال</div>
            </div></div>
        </div>
        <div class="col-xl-3 col-sm-6">
            <div class="card"><div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="kpi-label mb-1">جمع خالص فروش نقدی</div>
                        <div class="kpi-value text-success">{{ $fmt($k['net_sales_cash'] ?? 0) }} <small class="text-success fs-6">تومان</small></div>
                    </div>
                    <span class="badge bg-label-success p-2"><i class="ti ti-credit-card"></i></span>
                </div>
                <div class="text-muted small mt-2">درگاه‌های نقدی · پرداخت‌شده منهای هزینه ارسال</div>
            </div></div>
        </div>
        <div class="col-xl-3 col-sm-6">
            <div class="card"><div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="kpi-label mb-1">جمع خالص فروش قسطی</div>
                        <div class="kpi-value text-info">{{ $fmt($k['net_sales_installment'] ?? 0) }} <small class="text-info fs-6">تومان</small></div>
                    </div>
                    <span class="badge bg-label-info p-2"><i class="ti ti-calendar-dollar"></i></span>
                </div>
                <div class="text-muted small mt-2">درگاه‌های اقساطی · پرداخت‌شده منهای هزینه ارسال</div>
            </div></div>
        </div>
        <div class="col-xl-3 col-sm-6">
            <div class="card"><div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="kpi-label mb-1">مشتریان خریدار</div>
                        <div class="kpi-value text-warning">{{ $fmt($k['customers']) }}</div>
                    </div>
                    <span class="badge bg-label-warning p-2"><i class="ti ti-users"></i></span>
                </div>
                <div class="text-muted small mt-2">جدید {{ $fmt($k['new_customers']) }} · بازگشتی {{ $fmt($k['returning_customers']) }}</div>
            </div></div>
        </div>
        <div class="col-xl-3 col-sm-6">
            <div class="card"><div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="kpi-label mb-1">تخفیف کد کوپن</div>
                        <div class="kpi-value">{{ $fmt($k['coupon_discounts']) }} <small class="text-muted fs-6">تومان</small></div>
                    </div>
                    <span class="badge bg-label-danger p-2"><i class="ti ti-discount-2"></i></span>
                </div>
            </div></div>
        </div>
        <div class="col-xl-3 col-sm-6">
            <div class="card"><div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="kpi-label mb-1">استفاده از کیف پول</div>
                        <div class="kpi-value">{{ $fmt($k['wallet_used']) }} <small class="text-muted fs-6">تومان</small></div>
                    </div>
                    <span class="badge bg-label-primary p-2"><i class="ti ti-wallet"></i></span>
                </div>
            </div></div>
        </div>
        <div class="col-xl-3 col-sm-6">
            <div class="card"><div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="kpi-label mb-1">نرخ لغو سفارش</div>
                        <div class="kpi-value text-danger">{{ $k['cancel_rate'] }}٪</div>
                    </div>
                    <span class="badge bg-label-danger p-2"><i class="ti ti-ban"></i></span>
                </div>
                <div class="text-muted small mt-2">
                    لغو {{ $fmt($k['canceled_orders']) }} · مرجوع {{ $fmt($k['returned_orders']) }} · ناموفق {{ $fmt($k['failed_orders']) }}
                </div>
            </div></div>
        </div>
        <div class="col-xl-3 col-sm-6">
            <div class="card"><div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="kpi-label mb-1">بیشترین رفرر</div>
                        @if(!empty($k['top_referrer']))
                            <div class="kpi-value text-primary text-truncate" style="max-width:11rem" dir="ltr" title="{{ $k['top_referrer']['name'] }}">
                                {{ $k['top_referrer']['name'] }}
                            </div>
                        @else
                            <div class="kpi-value text-muted">—</div>
                        @endif
                    </div>
                    <span class="badge bg-label-primary p-2"><i class="ti ti-external-link"></i></span>
                </div>
                <div class="text-muted small mt-2">
                    @if(!empty($k['top_referrer']))
                        {{ $fmt($k['top_referrer']['orders']) }} سفارش · {{ $k['top_referrer']['share'] }}٪
                    @else
                        هنوز رفرری ثبت نشده
                    @endif
                </div>
            </div></div>
        </div>
        <div class="col-xl-3 col-sm-6">
            <div class="card"><div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="kpi-label mb-1">محبوب‌ترین شرکت پستی</div>
                        @if(!empty($k['top_courier']))
                            <div class="kpi-value text-info text-truncate" style="max-width:11rem" title="{{ $k['top_courier']['name'] }}">
                                {{ $k['top_courier']['name'] }}
                            </div>
                        @else
                            <div class="kpi-value text-muted">—</div>
                        @endif
                    </div>
                    <span class="badge bg-label-info p-2"><i class="ti ti-truck-delivery"></i></span>
                </div>
                <div class="text-muted small mt-2">
                    @if(!empty($k['top_courier']))
                        {{ $fmt($k['top_courier']['orders']) }} سفارش · {{ $k['top_courier']['share'] }}٪
                    @else
                        هنوز سفارشی با روش ارسال ثبت نشده
                    @endif
                </div>
            </div></div>
        </div>
    </div>

    {{-- Charts row 1 --}}
    <div class="row g-4 mb-4 analytics-charts">
        <div class="col-lg-8">
            <div class="card h-100">
                <div class="card-header"><h5 class="card-title mb-0">روند فروش و درآمد</h5></div>
                <div class="card-body"><div id="chartTimeline" class="chart-box"></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"><div id="chartStatus" class="chart-box"></div></div>
            </div>
        </div>
    </div>

    {{-- Charts row 2 --}}
    <div class="row g-4 mb-4 analytics-charts">
        <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 id="chartPayment" class="chart-box"></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"><div id="chartShipping" class="chart-box"></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"><div id="chartProducts" class="chart-box"></div></div>
            </div>
        </div>
    </div>

    {{-- Referrers --}}
    <div class="row g-4 mb-4 analytics-charts">
        <div class="col-lg-5">
            <div class="card h-100">
                <div class="card-header"><h5 class="card-title mb-0">توزیع رفرر سفارش‌ها</h5></div>
                <div class="card-body"><div id="chartReferrerPie" class="chart-box"></div></div>
            </div>
        </div>
        <div class="col-lg-7">
            <div class="card h-100">
                <div class="card-header"><h5 class="card-title mb-0">رتبه‌بندی رفرر بر اساس تعداد سفارش</h5></div>
                <div class="card-body"><div id="chartReferrerBar" class="chart-box"></div></div>
            </div>
        </div>
    </div>

    {{-- Tables --}}
    <div class="row g-4 mb-4 analytics-tables">
        <div class="col-lg-6">
            <div class="card h-100">
                <div class="card-header"><h5 class="card-title mb-0">جدول پرفروش‌ترین محصولات</h5></div>
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>#</th>
                                <th>محصول</th>
                                <th>تعداد</th>
                                <th>مبلغ فروش</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse($t['top_products'] as $i => $row)
                            <tr>
                                <td class="text-muted">{{ $i + 1 }}</td>
                                <td>{{ $row['title'] }}</td>
                                <td>{{ $fmt($row['qty']) }}</td>
                                <td>{{ $fmt($row['revenue']) }} تومان</td>
                            </tr>
                            @empty
                            <tr><td colspan="4" class="text-center text-muted py-4">داده‌ای نیست</td></tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <div class="col-lg-6">
            <div class="card h-100">
                <div class="card-header"><h5 class="card-title mb-0">برترین مشتریان</h5></div>
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>مشتری</th>
                                <th>موبایل</th>
                                <th>سفارش</th>
                                <th>مبلغ</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse($t['top_customers'] as $row)
                            <tr>
                                <td>
                                    @if(!empty($row['mobile']) && $row['mobile'] !== '—')
                                    <a href="{{ route('admin.users.show', $row['mobile']) }}">{{ $row['name'] }}</a>
                                    @else
                                    {{ $row['name'] }}
                                    @endif
                                </td>
                                <td dir="ltr" class="small">{{ $row['mobile'] }}</td>
                                <td>{{ $fmt($row['orders']) }}</td>
                                <td>{{ $fmt($row['revenue']) }} تومان</td>
                            </tr>
                            @empty
                            <tr><td colspan="4" class="text-center text-muted py-4">داده‌ای نیست</td></tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="row g-4 mb-4 analytics-tables">
        <div class="col-12">
            <div class="card h-100">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="card-title mb-0">رفررها به تفکیک منبع</h5>
                    <span class="text-muted small">بر اساس سفارش‌های موفق بازه</span>
                </div>
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>#</th>
                                <th>منبع / رفرر</th>
                                <th>تعداد سفارش</th>
                                <th>مبلغ فروش</th>
                                <th>سهم</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse(($t['referrers'] ?? []) as $i => $row)
                            <tr>
                                <td class="text-muted">{{ $i + 1 }}</td>
                                <td dir="ltr">{{ $row['name'] }}</td>
                                <td>{{ $fmt($row['orders']) }}</td>
                                <td>{{ $fmt($row['revenue']) }} تومان</td>
                                <td>
                                    <div class="d-flex align-items-center gap-2">
                                        <div class="progress flex-grow-1" style="height:6px;min-width:80px;max-width:140px">
                                            <div class="progress-bar bg-primary" style="width:{{ min(100, $row['share']) }}%"></div>
                                        </div>
                                        <span class="small text-muted">{{ $row['share'] }}٪</span>
                                    </div>
                                </td>
                            </tr>
                            @empty
                            <tr><td colspan="5" class="text-center text-muted py-4">در این بازه رفرری ثبت نشده است</td></tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="row g-4 mb-4 analytics-tables">
        <div class="col-lg-4">
            <div class="card h-100">
                <div class="card-header"><h5 class="card-title mb-0">خلاصه روش پرداخت</h5></div>
                <div class="table-responsive">
                    <table class="table mb-0">
                        <thead class="table-light"><tr><th>روش</th><th>سفارش</th><th>مبلغ</th></tr></thead>
                        <tbody>
                            @forelse($t['payment_methods'] as $row)
                            <tr>
                                <td>{{ $row['name'] }}</td>
                                <td>{{ $fmt($row['orders']) }}</td>
                                <td>{{ $fmt($row['revenue']) }}</td>
                            </tr>
                            @empty
                            <tr><td colspan="3" class="text-center text-muted py-3">—</td></tr>
                            @endforelse
                        </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="table-responsive">
                    <table class="table mb-0">
                        <thead class="table-light"><tr><th>روش</th><th>سفارش</th><th>هزینه ارسال</th></tr></thead>
                        <tbody>
                            @forelse($t['shipping_methods'] as $row)
                            <tr>
                                <td>{{ $row['name'] }}</td>
                                <td>{{ $fmt($row['orders']) }}</td>
                                <td>{{ $fmt($row['shipping']) }}</td>
                            </tr>
                            @empty
                            <tr><td colspan="3" class="text-center text-muted py-3">—</td></tr>
                            @endforelse
                        </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="table-responsive">
                    <table class="table mb-0">
                        <thead class="table-light"><tr><th>کد</th><th>دفعات</th><th>تخفیف</th></tr></thead>
                        <tbody>
                            @forelse($t['coupons'] as $row)
                            <tr>
                                <td class="font-monospace" dir="ltr">{{ $row['code'] }}</td>
                                <td>{{ $fmt($row['orders']) }}</td>
                                <td>{{ $fmt($row['discount']) }}</td>
                            </tr>
                            @empty
                            <tr><td colspan="3" class="text-center text-muted py-3">کد تخفیفی ثبت نشده</td></tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="card mb-4">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="card-title mb-0">خلاصه روزانه / ماهانه</h5>
            <span class="text-muted small">تاریخ‌ها شمسی</span>
        </div>
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead class="table-light">
                    <tr>
                        <th>تاریخ</th>
                        <th>تعداد سفارش</th>
                        <th>مبلغ فروش</th>
                        <th>هزینه ارسال</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($t['daily'] as $row)
                    <tr>
                        <td dir="ltr">{{ $row['date'] }}</td>
                        <td>{{ $fmt($row['orders']) }}</td>
                        <td>{{ $fmt($row['revenue']) }} تومان</td>
                        <td>{{ $fmt($row['shipping']) }} تومان</td>
                    </tr>
                    @empty
                    <tr><td colspan="4" class="text-center text-muted py-4">داده‌ای در این بازه نیست</td></tr>
                    @endforelse
                </tbody>
            </table>
        </div>
    </div>

    <div class="row g-3 mb-2">
        <div class="col-md-6">
            <div class="alert alert-secondary mb-0">
                <i class="ti ti-message-dots me-1"></i>
                دیدگاه‌های ثبت‌شده در بازه: <strong>{{ $fmt($k['reviews']) }}</strong>
            </div>
        </div>
        <div class="col-md-6">
            <div class="alert alert-secondary mb-0">
                <i class="ti ti-headset me-1"></i>
                تیکت‌های پشتیبانی ثبت‌شده در بازه: <strong>{{ $fmt($k['tickets']) }}</strong>
            </div>
        </div>
    </div>

</div>
@endsection

@section('customjs')
<script src="{{ url('theme/admin/vendor/libs/persian-date/persian-date.min.js') }}"></script>
<script src="{{ url('theme/admin/vendor/libs/persian-datepicker/js/persian-datepicker.min.js') }}"></script>
<script>
(function () {
    var chartData = @json($c);
    var period = @json($period);

    // Custom range: open fields without refreshing the page
    var customBtn = document.getElementById('btnCustomPeriod');
    var customBox = document.getElementById('customRangeBox');
    if (customBtn && customBox) {
        customBtn.addEventListener('click', function () {
            customBox.classList.add('is-visible');
            document.querySelectorAll('#analyticsFilterForm .period-preset-btn').forEach(function (btn) {
                btn.classList.remove('btn-primary');
                btn.classList.add('btn-outline-secondary');
            });
            customBtn.classList.remove('btn-outline-secondary');
            customBtn.classList.add('btn-primary');
            var fromInput = document.getElementById('fromJalali');
            if (fromInput) fromInput.focus();
        });
    }

    var dpOpts = {
        format: 'YYYY/MM/DD',
        autoClose: true,
        initialValue: false,
        calendar: { persian: { locale: 'fa' } },
    };
    if (window.jQuery && jQuery.fn.persianDatepicker) {
        jQuery('#fromJalali').persianDatepicker(dpOpts);
        jQuery('#toJalali').persianDatepicker(dpOpts);
    }

    function moneyTooltip(val) {
        return Number(val || 0).toLocaleString('fa-IR') + ' تومان';
    }

    if (typeof ApexCharts === 'undefined') return;

    var analyticsCharts = [];

    function pushChart(el, options) {
        var chart = new ApexCharts(el, options);
        analyticsCharts.push(chart);
        chart.render();
        return chart;
    }

    // Timeline
    if (document.querySelector('#chartTimeline')) {
        pushChart(document.querySelector('#chartTimeline'), {
            chart: { type: 'area', height: 340, toolbar: { show: false }, fontFamily: 'inherit' },
            series: [
                { name: 'درآمد', type: 'area', data: chartData.timeline.revenue || [] },
                { name: 'سفارش', type: 'line', data: chartData.timeline.orders || [] },
                { name: 'ارسال', type: 'line', data: chartData.timeline.shipping || [] },
            ],
            stroke: { curve: 'smooth', width: [0, 3, 2] },
            fill: { type: ['gradient', 'solid', 'solid'], gradient: { opacityFrom: 0.45, opacityTo: 0.05 } },
            colors: ['#28c76f', '#696cff', '#00cfe8'],
            xaxis: { categories: chartData.timeline.labels || [], labels: { rotate: -45, style: { fontSize: '11px' } } },
            yaxis: [
                { seriesName: 'درآمد', title: { text: 'تومان' }, labels: { formatter: function (v) { return Number(v).toLocaleString('fa-IR'); } } },
                { seriesName: 'سفارش', opposite: true, title: { text: 'تعداد' }, labels: { formatter: function (v) { return Number(v).toLocaleString('fa-IR'); } } },
                { seriesName: 'درآمد', show: false },
            ],
            dataLabels: { enabled: false },
            tooltip: {
                shared: true,
                y: {
                    formatter: function (val, opts) {
                        if (opts.seriesIndex === 1) return Number(val).toLocaleString('fa-IR') + ' سفارش';
                        return moneyTooltip(val);
                    }
                }
            },
            legend: { position: 'top' },
        });
    }

    // Status donut
    if (document.querySelector('#chartStatus') && (chartData.status.values || []).length) {
        pushChart(document.querySelector('#chartStatus'), {
            chart: { type: 'donut', height: 340, fontFamily: 'inherit' },
            labels: chartData.status.labels,
            series: chartData.status.values,
            colors: chartData.status.colors,
            legend: { position: 'bottom' },
            dataLabels: { formatter: function (val) { return Math.round(val) + '%'; } },
        });
    } else if (document.querySelector('#chartStatus')) {
        document.querySelector('#chartStatus').innerHTML = '<div class="text-muted text-center py-5">داده‌ای نیست</div>';
    }

    // Payment bar
    if (document.querySelector('#chartPayment') && (chartData.payment_methods.labels || []).length) {
        pushChart(document.querySelector('#chartPayment'), {
            chart: { type: 'bar', height: 340, toolbar: { show: false }, fontFamily: 'inherit' },
            series: [{ name: 'مبلغ', data: chartData.payment_methods.revenue }],
            xaxis: { categories: chartData.payment_methods.labels },
            colors: ['#7367f0'],
            plotOptions: { bar: { borderRadius: 6, columnWidth: '45%' } },
            dataLabels: { enabled: false },
            yaxis: { labels: { formatter: function (v) { return Number(v).toLocaleString('fa-IR'); } } },
            tooltip: { y: { formatter: moneyTooltip } },
        });
    } else if (document.querySelector('#chartPayment')) {
        document.querySelector('#chartPayment').innerHTML = '<div class="text-muted text-center py-5">داده‌ای نیست</div>';
    }

    // Shipping bar
    if (document.querySelector('#chartShipping') && (chartData.shipping_methods.labels || []).length) {
        pushChart(document.querySelector('#chartShipping'), {
            chart: { type: 'bar', height: 340, toolbar: { show: false }, fontFamily: 'inherit' },
            series: [{ name: 'هزینه ارسال', data: chartData.shipping_methods.shipping }],
            xaxis: { categories: chartData.shipping_methods.labels },
            colors: ['#00cfe8'],
            plotOptions: { bar: { borderRadius: 6, columnWidth: '45%' } },
            dataLabels: { enabled: false },
            yaxis: { labels: { formatter: function (v) { return Number(v).toLocaleString('fa-IR'); } } },
            tooltip: { y: { formatter: moneyTooltip } },
        });
    } else if (document.querySelector('#chartShipping')) {
        document.querySelector('#chartShipping').innerHTML = '<div class="text-muted text-center py-5">داده‌ای نیست</div>';
    }

    // Top products horizontal bar
    if (document.querySelector('#chartProducts') && (chartData.top_products.labels || []).length) {
        pushChart(document.querySelector('#chartProducts'), {
            chart: { type: 'bar', height: 340, toolbar: { show: false }, fontFamily: 'inherit' },
            series: [{ name: 'تعداد فروش', data: chartData.top_products.qty }],
            plotOptions: { bar: { horizontal: true, borderRadius: 4, barHeight: '60%' } },
            xaxis: { categories: chartData.top_products.labels },
            colors: ['#28c76f'],
            dataLabels: { enabled: false },
            tooltip: {
                y: { formatter: function (val) { return Number(val).toLocaleString('fa-IR') + ' عدد'; } }
            },
        });
    } else if (document.querySelector('#chartProducts')) {
        document.querySelector('#chartProducts').innerHTML = '<div class="text-muted text-center py-5">داده‌ای نیست</div>';
    }

    // Referrer pie
    var referrerData = chartData.referrers || {};
    if (document.querySelector('#chartReferrerPie') && (referrerData.labels || []).length) {
        pushChart(document.querySelector('#chartReferrerPie'), {
            chart: { type: 'pie', height: 340, fontFamily: 'inherit' },
            labels: referrerData.labels,
            series: referrerData.orders || [],
            colors: ['#7367f0', '#28c76f', '#00cfe8', '#ff9f43', '#ea5455', '#826af9', '#1e9ff2', '#fdac41', '#ff6384', '#4bc0c0'],
            legend: { position: 'bottom' },
            dataLabels: { formatter: function (val) { return Math.round(val) + '%'; } },
            tooltip: {
                y: {
                    formatter: function (val) {
                        return Number(val).toLocaleString('fa-IR') + ' سفارش';
                    }
                }
            },
        });
    } else if (document.querySelector('#chartReferrerPie')) {
        document.querySelector('#chartReferrerPie').innerHTML = '<div class="text-muted text-center py-5">داده‌ای نیست</div>';
    }

    // Referrer bar
    if (document.querySelector('#chartReferrerBar') && (referrerData.labels || []).length) {
        pushChart(document.querySelector('#chartReferrerBar'), {
            chart: { type: 'bar', height: 340, toolbar: { show: false }, fontFamily: 'inherit' },
            series: [
                { name: 'سفارش', data: referrerData.orders || [] },
                { name: 'مبلغ', data: referrerData.revenue || [] },
            ],
            plotOptions: { bar: { borderRadius: 6, columnWidth: '45%' } },
            xaxis: { categories: referrerData.labels || [], labels: { rotate: -30, style: { fontSize: '11px' } } },
            colors: ['#7367f0', '#28c76f'],
            dataLabels: { enabled: false },
            yaxis: [
                { seriesName: 'سفارش', title: { text: 'تعداد' }, labels: { formatter: function (v) { return Number(v).toLocaleString('fa-IR'); } } },
                { seriesName: 'مبلغ', opposite: true, title: { text: 'تومان' }, labels: { formatter: function (v) { return Number(v).toLocaleString('fa-IR'); } } },
            ],
            tooltip: {
                shared: true,
                y: {
                    formatter: function (val, opts) {
                        if (opts.seriesIndex === 0) return Number(val).toLocaleString('fa-IR') + ' سفارش';
                        return moneyTooltip(val);
                    }
                }
            },
            legend: { position: 'top' },
        });
    } else if (document.querySelector('#chartReferrerBar')) {
        document.querySelector('#chartReferrerBar').innerHTML = '<div class="text-muted text-center py-5">داده‌ای نیست</div>';
    }

    function setChartsHeight(h) {
        analyticsCharts.forEach(function (chart) {
            try {
                chart.updateOptions({ chart: { height: h } }, false, true);
            } catch (e) {}
        });
    }

    var btn = document.getElementById('btnPrintAnalytics');
    if (btn) {
        btn.addEventListener('click', function () {
            setChartsHeight(180);
            setTimeout(function () { window.print(); }, 350);
        });
    }

    window.addEventListener('beforeprint', function () { setChartsHeight(180); });
    window.addEventListener('afterprint', function () { setChartsHeight(340); });
})();
</script>
@endsection
