<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>
<?php init_head(); ?>
<style>
    .sd-wrap { padding: 8px 0; }
    .sd-header { margin-bottom: 24px; }
    .sd-header h4 { font-size: 24px; font-weight: 700; color: #0f172a; margin: 0; }
    .sd-header p { color: #64748b; margin: 4px 0 0 0; font-size: 14px; }

    .sd-card { background: #fff; border-radius: 12px; padding: 20px; margin-bottom: 20px; box-shadow: 0 1px 3px rgba(0,0,0,0.05); border: 1px solid #e5e7eb; }
    .sd-card:hover { box-shadow: 0 4px 12px rgba(0,0,0,0.08); transition: box-shadow 0.2s; }

    .sd-stat-card { display: flex; align-items: center; gap: 14px; }
    .sd-stat-icon { width: 48px; height: 48px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 20px; flex-shrink: 0; }
    .sd-icon-blue { background: linear-gradient(135deg, #3b82f6, #2563eb); color: #fff; }
    .sd-icon-green { background: linear-gradient(135deg, #10b981, #059669); color: #fff; }
    .sd-icon-amber { background: linear-gradient(135deg, #f59e0b, #d97706); color: #fff; }
    .sd-icon-red { background: linear-gradient(135deg, #ef4444, #dc2626); color: #fff; }
    .sd-icon-purple { background: linear-gradient(135deg, #8b5cf6, #7c3aed); color: #fff; }
    .sd-icon-cyan { background: linear-gradient(135deg, #06b6d4, #0891b2); color: #fff; }

    .sd-stat-body { flex: 1; min-width: 0; }
    .sd-stat-label { color: #64748b; font-size: 12px; text-transform: uppercase; letter-spacing: 0.4px; font-weight: 600; margin-bottom: 4px; }
    .sd-stat-value { font-size: 26px; font-weight: 700; color: #0f172a; line-height: 1; }
    .sd-stat-sub { color: #94a3b8; font-size: 11px; margin-top: 4px; }

    .sd-card-title { font-size: 14px; font-weight: 600; color: #0f172a; margin: 0 0 6px 0; display: flex; justify-content: space-between; align-items: center; }
    .sd-card-subtitle { color: #94a3b8; font-size: 12px; margin: 0 0 16px 0; }

    .sd-table { width: 100%; border-collapse: collapse; }
    .sd-table th { font-size: 11px; text-transform: uppercase; letter-spacing: 0.4px; color: #64748b; font-weight: 600; padding: 8px 6px; border-bottom: 2px solid #f1f5f9; text-align: left; }
    .sd-table td { padding: 10px 6px; border-bottom: 1px solid #f1f5f9; font-size: 13px; color: #334155; }
    .sd-table td a { color: #2563eb; font-weight: 500; }
    .sd-table tr:last-child td { border-bottom: none; }

    .sd-badge { display: inline-block; padding: 2px 8px; border-radius: 4px; font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.3px; }
    .sd-badge-open { background: #fef3c7; color: #92400e; }
    .sd-badge-progress { background: #dbeafe; color: #1e40af; }
    .sd-empty { padding: 40px 20px; text-align: center; color: #94a3b8; font-size: 13px; }
    .sd-empty i { font-size: 32px; display: block; margin-bottom: 8px; opacity: 0.5; }

    .sd-sla-card { position: relative; overflow: hidden; }
    .sd-sla-card::before { content: ''; position: absolute; top: 0; right: 0; width: 120px; height: 120px; opacity: 0.05; background-position: center; background-repeat: no-repeat; }

    .chart-container { position: relative; height: 240px; }
    .chart-container-lg { position: relative; height: 300px; }
    .chart-container-sm { position: relative; height: 180px; }
</style>

<div id="wrapper">
    <div class="content">
        <div class="sd-wrap">
        <div class="sd-header">
            <h4><i class="fa-solid fa-chart-line" style="color:#3b82f6;margin-right:8px;"></i>Dashboard</h4>
            <p>Customer &amp; ticket metrics — last 30 days</p>
        </div>

        <!-- Row 1: Top stat cards -->
        <div class="row">
            <?php
            $cards = [
                ['label' => 'Total Customers',   'value' => (int)$total_customers,   'sub' => 'All time',        'icon' => 'fa-users',           'class' => 'sd-icon-blue'],
                ['label' => 'New (30d)',         'value' => (int)$new_customers_30,  'sub' => 'Customers added', 'icon' => 'fa-user-plus',       'class' => 'sd-icon-green'],
                ['label' => 'Open Tickets',      'value' => (int)$open_tickets,      'sub' => 'Awaiting action', 'icon' => 'fa-envelope-open',   'class' => 'sd-icon-amber'],
                ['label' => 'Overdue',           'value' => (int)$overdue_tickets,   'sub' => 'Open > 3 days',   'icon' => 'fa-triangle-exclamation','class' => 'sd-icon-red'],
                ['label' => 'Closed (30d)',      'value' => (int)$closed_30,         'sub' => 'Tickets resolved','icon' => 'fa-circle-check',    'class' => 'sd-icon-purple'],
            ];
            foreach ($cards as $c): ?>
                <div class="col-sm-6 col-xs-12" style="width:20%;float:left;">
                    <div class="sd-card sd-stat-card">
                        <div class="sd-stat-icon <?= $c['class']; ?>"><i class="fa-solid <?= $c['icon']; ?>"></i></div>
                        <div class="sd-stat-body">
                            <div class="sd-stat-label"><?= $c['label']; ?></div>
                            <div class="sd-stat-value"><?= number_format($c['value']); ?></div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <!-- Row 2: SLA + Big trend -->
        <div class="row">
            <div class="col-md-12">
                <div class="sd-card">
                    <h4 class="sd-card-title">Ticket Volume by Status
                        <span style="font-size:11px;font-weight:400;color:#94a3b8;">Last 30 days</span>
                    </h4>
                    <div class="chart-container"><canvas id="chart_status_bar"></canvas></div>
                </div>
            </div>
        </div>

        <!-- Row 3: Distribution charts -->
        <div class="row">
            <div class="col-md-4">
                <div class="sd-card">
                    <h4 class="sd-card-title">Status Distribution</h4>
                    <p class="sd-card-subtitle">Where tickets currently sit</p>
                    <div class="chart-container"><canvas id="chart_status"></canvas></div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="sd-card">
                    <h4 class="sd-card-title">By Priority</h4>
                    <p class="sd-card-subtitle">Urgency mix</p>
                    <div class="chart-container"><canvas id="chart_priority"></canvas></div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="sd-card">
                    <h4 class="sd-card-title">By Department</h4>
                    <p class="sd-card-subtitle">Team load</p>
                    <div class="chart-container"><canvas id="chart_department"></canvas></div>
                </div>
            </div>
        </div>

        <!-- Row 4: Trends -->
        <div class="row">
            <div class="col-md-6">
                <div class="sd-card">
                    <h4 class="sd-card-title">Tickets Opened
                        <span style="font-size:11px;font-weight:400;color:#94a3b8;">Daily, last 30 days</span>
                    </h4>
                    <div class="chart-container"><canvas id="chart_tickets_trend"></canvas></div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="sd-card">
                    <h4 class="sd-card-title">New Customers
                        <span style="font-size:11px;font-weight:400;color:#94a3b8;">Daily, last 30 days</span>
                    </h4>
                    <div class="chart-container"><canvas id="chart_customers_trend"></canvas></div>
                </div>
            </div>
        </div>

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

<script>
window.addEventListener('load', function() {
    var byStatus     = <?= json_encode($by_status); ?>;
    var byPriority   = <?= json_encode($by_priority); ?>;
    var byDepartment = <?= json_encode($by_department); ?>;
    var tTrend       = <?= json_encode($tickets_trend); ?>;
    var cTrend       = <?= json_encode($customers_trend); ?>;

    var palette      = ['#3b82f6', '#f59e0b', '#10b981', '#8b5cf6', '#ef4444', '#06b6d4', '#f97316', '#84cc16'];
    var gradientBlue = ['#60a5fa', '#3b82f6', '#2563eb'];

    function makeGradient(ctx, color) {
        var g = ctx.createLinearGradient(0, 0, 0, 240);
        g.addColorStop(0, color + 'cc');
        g.addColorStop(1, color + '10');
        return g;
    }

    Chart.defaults.global.defaultFontFamily = '-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
    Chart.defaults.global.defaultFontColor = '#64748b';
    Chart.defaults.global.defaultFontSize = 12;

    // Doughnut — status distribution
    if (byStatus && byStatus.length) {
        new Chart(document.getElementById('chart_status').getContext('2d'), {
            type: 'doughnut',
            data: {
                labels: byStatus.map(function(r){ return r.name; }),
                datasets: [{
                    data: byStatus.map(function(r){ return parseInt(r.c) || 0; }),
                    backgroundColor: palette,
                    borderWidth: 3, borderColor: '#fff'
                }]
            },
            options: {
                responsive: true, maintainAspectRatio: false,
                cutoutPercentage: 65,
                legend: { position: 'bottom', labels: { boxWidth: 12, padding: 12, fontSize: 11 } }
            }
        });
    }

    // Horizontal bar — priority
    if (byPriority && byPriority.length) {
        new Chart(document.getElementById('chart_priority').getContext('2d'), {
            type: 'horizontalBar',
            data: {
                labels: byPriority.map(function(r){ return r.name; }),
                datasets: [{
                    data: byPriority.map(function(r){ return parseInt(r.c) || 0; }),
                    backgroundColor: byPriority.map(function(_, i){ return palette[i % palette.length]; }),
                    borderRadius: 6, borderSkipped: false
                }]
            },
            options: {
                responsive: true, maintainAspectRatio: false,
                legend: { display: false },
                scales: {
                    xAxes: [{ ticks: { beginAtZero: true, precision: 0 }, gridLines: { color: '#f1f5f9', drawBorder: false } }],
                    yAxes: [{ gridLines: { display: false } }]
                }
            }
        });
    }

    // Vertical bar — department
    if (byDepartment && byDepartment.length) {
        var ctx = document.getElementById('chart_department').getContext('2d');
        new Chart(ctx, {
            type: 'bar',
            data: {
                labels: byDepartment.map(function(r){ return r.name; }),
                datasets: [{
                    data: byDepartment.map(function(r){ return parseInt(r.c) || 0; }),
                    backgroundColor: makeGradient(ctx, '#3b82f6'),
                    borderColor: '#3b82f6', borderWidth: 2, borderRadius: 6, borderSkipped: false
                }]
            },
            options: {
                responsive: true, maintainAspectRatio: false,
                legend: { display: false },
                scales: {
                    xAxes: [{ gridLines: { display: false } }],
                    yAxes: [{ ticks: { beginAtZero: true, precision: 0 }, gridLines: { color: '#f1f5f9', drawBorder: false } }]
                }
            }
        });
    }

    // Big bar — status (top of page)
    if (byStatus && byStatus.length) {
        var ctxS = document.getElementById('chart_status_bar').getContext('2d');
        new Chart(ctxS, {
            type: 'bar',
            data: {
                labels: byStatus.map(function(r){ return r.name; }),
                datasets: [{
                    label: 'Tickets',
                    data: byStatus.map(function(r){ return parseInt(r.c) || 0; }),
                    backgroundColor: byStatus.map(function(_, i){ return palette[i % palette.length]; }),
                    borderRadius: 6, borderSkipped: false, barThickness: 32
                }]
            },
            options: {
                responsive: true, maintainAspectRatio: false,
                legend: { display: false },
                scales: {
                    xAxes: [{ gridLines: { display: false } }],
                    yAxes: [{ ticks: { beginAtZero: true, precision: 0 }, gridLines: { color: '#f1f5f9', drawBorder: false } }]
                }
            }
        });
    }

    // Line — tickets trend
    var ctxT = document.getElementById('chart_tickets_trend').getContext('2d');
    new Chart(ctxT, {
        type: 'line',
        data: {
            labels: tTrend.map(function(s){ return s.date.substring(5); }),
            datasets: [{
                label: 'Opened',
                data: tTrend.map(function(s){ return parseInt(s.count) || 0; }),
                borderColor: '#3b82f6',
                backgroundColor: makeGradient(ctxT, '#3b82f6'),
                fill: true, tension: 0.4, pointRadius: 3, pointBackgroundColor: '#fff', pointBorderColor: '#3b82f6', pointBorderWidth: 2, borderWidth: 2.5
            }]
        },
        options: {
            responsive: true, maintainAspectRatio: false,
            legend: { display: false },
            scales: {
                xAxes: [{ gridLines: { display: false }, ticks: { maxTicksLimit: 10 } }],
                yAxes: [{ ticks: { beginAtZero: true, precision: 0 }, gridLines: { color: '#f1f5f9', drawBorder: false } }]
            }
        }
    });

    // Line — customers trend
    var ctxC = document.getElementById('chart_customers_trend').getContext('2d');
    new Chart(ctxC, {
        type: 'line',
        data: {
            labels: cTrend.map(function(s){ return s.date.substring(5); }),
            datasets: [{
                label: 'New',
                data: cTrend.map(function(s){ return parseInt(s.count) || 0; }),
                borderColor: '#10b981',
                backgroundColor: makeGradient(ctxC, '#10b981'),
                fill: true, tension: 0.4, pointRadius: 3, pointBackgroundColor: '#fff', pointBorderColor: '#10b981', pointBorderWidth: 2, borderWidth: 2.5
            }]
        },
        options: {
            responsive: true, maintainAspectRatio: false,
            legend: { display: false },
            scales: {
                xAxes: [{ gridLines: { display: false }, ticks: { maxTicksLimit: 10 } }],
                yAxes: [{ ticks: { beginAtZero: true, precision: 0 }, gridLines: { color: '#f1f5f9', drawBorder: false } }]
            }
        }
    });
});
</script>

<?php init_tail(); ?>
