<?php
require 'auth_check.php';
require_once 'db.php';

$departments = $pdo->query("SELECT name FROM departments ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);
$years       = $pdo->query("SELECT DISTINCT YEAR(inv_date) AS year FROM transactions ORDER BY year DESC")->fetchAll(PDO::FETCH_ASSOC);
$currentYear = date('Y');
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Summary Report | Mei Hotel Penang</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<link rel="stylesheet" href="assets/style.css">
<style>
*, *::before, *::after { box-sizing: border-box; }
html, body { height: 100%; margin: 0; background: #f1f5f9; font-family: Inter, system-ui, sans-serif; overflow: hidden; }
.shell   { display: flex; height: 100vh; overflow: hidden; }
.content { flex: 1; min-width: 0; display: flex; flex-direction: column; overflow: hidden; }
.topbar  { flex-shrink:0; height:56px; display:flex; align-items:center; padding:0 28px; background:#fff; border-bottom:1px solid #e5e7eb; }
.topbar-title { font-size:16px; font-weight:700; color:#111827; }
.main-area { flex:1; min-height:0; display:flex; flex-direction:row; overflow:hidden; }

/* Left 80% — fixed flex column, no outer scroll */
.left-col { flex:4; min-width:0; overflow:hidden; padding:24px 24px 24px 28px; display:flex; flex-direction:column; gap:18px; }

/* Right 20% */
.right-col { width:240px; flex-shrink:0; background:#fff; border-left:1px solid #e5e7eb; overflow-y:auto; padding:20px 14px; display:flex; flex-direction:column; gap:10px; }
.rp-title  { font-size:10px; font-weight:700; letter-spacing:.08em; text-transform:uppercase; color:#9ca3af; padding-bottom:10px; border-bottom:1px solid #f1f5f9; margin-bottom:2px; }

/* Stat cards */
.stat-card { border-radius:14px; padding:16px 14px; position:relative; overflow:hidden; display:flex; flex-direction:column; gap:3px; }
.stat-card::after { content:''; position:absolute; bottom:-16px; right:-16px; width:72px; height:72px; border-radius:50%; background:rgba(255,255,255,.1); }
.stat-icon  { font-size:20px; margin-bottom:4px; }
.stat-label { font-size:12px; font-weight:600; letter-spacing:.07em; text-transform:uppercase; color:rgba(255,255,255,.7); }
.stat-value { font-size:18px; font-weight:800; color:#fff; line-height:1.2; word-break:break-word; }
.stat-sub   { font-size:12px; color:rgba(255,255,255,.55); margin-top:1px; }
/* Highest month value gets extra +3px */
#kpiPeak    { font-size:21px; }
.c1 { background:linear-gradient(135deg,#1e40af,#3b82f6); }
.c2 { background:linear-gradient(135deg,#065f46,#10b981); }
.c3 { background:linear-gradient(135deg,#92400e,#f59e0b); }
.c4 { background:linear-gradient(135deg,#581c87,#a855f7); }

/* Filter card */
.filter-card { background:#fff; border-radius:12px; border:1px solid #e5e7eb; padding:18px 20px; display:grid; grid-template-columns:1fr 1fr; gap:16px; }
.f-label { display:block; font-size:11px; font-weight:700; color:#6b7280; text-transform:uppercase; letter-spacing:.05em; margin-bottom:6px; }
.f-input, .f-select { width:100%; padding:8px 12px; font-size:13px; color:#111827; border:1.5px solid #e5e7eb; border-radius:8px; outline:none; transition:border-color .15s,box-shadow .15s; background:#fff; font-family:inherit; }
.f-input:focus, .f-select:focus { border-color:#6366f1; box-shadow:0 0 0 3px rgba(99,102,241,.1); }

/* Dept dropdown */
.dept-wrap { position:relative; }
.dept-list { position:absolute; top:calc(100% + 4px); left:0; right:0; z-index:200; background:#fff; border:1.5px solid #e5e7eb; border-radius:8px; box-shadow:0 8px 24px rgba(0,0,0,.1); max-height:200px; overflow-y:auto; display:none; }
.dept-list.open { display:block; }
.dept-opt { padding:8px 14px; font-size:13px; color:#374151; cursor:pointer; }
.dept-opt:hover { background:#eef2ff; color:#4f46e5; }

/* Chart card */
.chart-card { background:#fff; border-radius:12px; border:1px solid #e5e7eb; padding:18px 20px; }
.chart-card h2 { font-size:12px; font-weight:700; color:#374151; margin:0 0 14px; text-transform:uppercase; letter-spacing:.05em; }

/* Table card — flex column, fills remaining height, only tbody scrolls */
.table-card { background:#fff; border-radius:12px; border:1px solid #e5e7eb; overflow:hidden; flex:1; min-height:0; display:flex; flex-direction:column; }
.table-card table { width:100%; border-collapse:collapse; table-layout:fixed; }
.table-card .t-head { flex-shrink:0; }
.table-card .t-body { flex:1; overflow-y:auto; min-height:0; }
.table-card .t-foot { flex-shrink:0; border-top:2px solid #e5e7eb; }
.table-card thead th { padding:10px 20px; font-size:13px; font-weight:700; text-transform:uppercase; letter-spacing:.06em; color:#6b7280; background:#f8fafc; border-bottom:1px solid #e5e7eb; }
.table-card tbody tr { border-bottom:1px solid #f1f5f9; transition:background .1s; }
.table-card tbody tr:hover td { background:#f0f9ff; }
.table-card tbody tr.current td { background:#fffbeb; }
.table-card tbody td { padding:10px 20px; font-size:15px; color:#374151; }
.table-card tfoot td { padding:10px 20px; font-size:14px; }
.spend-bar { height:5px; border-radius:3px; background:#6366f1; transition:width .4s ease; }
.empty-state { text-align:center; padding:40px 20px; color:#9ca3af; font-size:14px; }
</style>
</head>
<body>
<div class="shell">
    <?php include 'sidebar.php'; ?>
    <div class="content">

        <div class="topbar">
            <span class="topbar-title">Summary Report</span>
        </div>

        <div class="main-area">

            <!-- LEFT 80% -->
            <div class="left-col">

                <!-- Filters -->
                <div class="filter-card">
                    <div>
                        <span class="f-label">Department</span>
                        <div class="dept-wrap">
                            <input type="text" id="deptSearch" class="f-input" autocomplete="off" placeholder="All departments…">
                            <input type="hidden" id="deptValue">
                            <div id="deptList" class="dept-list">
                                <div class="dept-opt" data-value="">— All Departments —</div>
                                <?php foreach ($departments as $d): ?>
                                <div class="dept-opt" data-value="<?= htmlspecialchars($d['name']) ?>"><?= htmlspecialchars($d['name']) ?></div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                    <div>
                        <span class="f-label">Year</span>
                        <select id="yearSelect" class="f-select">
                            <?php foreach ($years as $y): ?>
                            <option value="<?= $y['year'] ?>" <?= $y['year'] == $currentYear ? 'selected' : '' ?>><?= $y['year'] ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <!-- Chart -->
                <div class="chart-card" id="chartWrap" style="display:none">
                    <h2>Monthly Spending</h2>
                    <div style="height:180px"><canvas id="spendChart"></canvas></div>
                </div>

                <!-- Table -->
                <div class="table-card">
                    <div class="t-head">
                        <table>
                            <thead>
                                <tr>
                                    <th style="text-align:left">Month</th>
                                    <th style="text-align:right;width:180px">Amount (RM)</th>
                                    <th style="text-align:left;width:130px">Spend</th>
                                </tr>
                            </thead>
                        </table>
                    </div>
                    <div class="t-body">
                        <table>
                            <tbody id="summaryTbody">
                                <tr><td colspan="3" class="empty-state">Select a year to view the report.</td></tr>
                            </tbody>
                        </table>
                    </div>
                    <div class="t-foot" style="display:none">
                        <table>
                            <tbody id="summaryFooter"></tbody>
                        </table>
                    </div>
                </div>

            </div>

            <!-- RIGHT 20% -->
            <div class="right-col">
                <div class="rp-title">📊 Key Metrics</div>

                <div class="stat-card c1">
                    <div class="stat-icon">💰</div>
                    <div class="stat-label">Grand Total (YTD)</div>
                    <div class="stat-value" id="kpiGrand">—</div>
                    <div class="stat-sub">Year to date</div>
                </div>

                <div class="stat-card c2">
                    <div class="stat-icon">📈</div>
                    <div class="stat-label">Avg Monthly (YTD)</div>
                    <div class="stat-value" id="kpiAvg">—</div>
                    <div class="stat-sub">Per month average</div>
                </div>

                <div class="stat-card c3">
                    <div class="stat-icon">🏆</div>
                    <div class="stat-label">Highest Month</div>
                    <div class="stat-value" id="kpiPeak">—</div>
                    <div class="stat-sub" id="kpiPeakAmt">Record spend</div>
                </div>

                <div class="stat-card c4">
                    <div class="stat-icon">🕐</div>
                    <div class="stat-label">Prev 6-Month Avg</div>
                    <div class="stat-value" id="kpiPrev6">—</div>
                    <div class="stat-sub">Rolling average</div>
                </div>
            </div>

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

<script>
const monthNames = ['January','February','March','April','May','June','July','August','September','October','November','December'];
let chartInstance = null;

// Dept dropdown
const deptSearch = document.getElementById('deptSearch');
const deptValue  = document.getElementById('deptValue');
const deptList   = document.getElementById('deptList');
deptSearch.addEventListener('focus', () => deptList.classList.add('open'));
deptSearch.addEventListener('blur',  () => setTimeout(() => deptList.classList.remove('open'), 150));
deptSearch.addEventListener('input', function() {
    const q = this.value.toLowerCase();
    document.querySelectorAll('.dept-opt').forEach(o => { o.style.display = o.textContent.toLowerCase().includes(q) ? '' : 'none'; });
    deptList.classList.add('open');
});
document.querySelectorAll('.dept-opt').forEach(opt => {
    opt.addEventListener('click', function() {
        deptSearch.value = this.dataset.value ? this.textContent.trim() : '';
        deptValue.value  = this.dataset.value;
        deptList.classList.remove('open');
        loadReport();
    });
});
document.getElementById('yearSelect').addEventListener('change', loadReport);

function loadReport() {
    const dept = deptValue.value;
    const year = document.getElementById('yearSelect').value;
    if (!year) return;
    document.getElementById('summaryTbody').innerHTML = '<tr><td colspan="3" class="empty-state">Loading…</td></tr>';
    document.getElementById('summaryFooter').innerHTML = '';
    fetch(`summary_report_ajax.php?department=${encodeURIComponent(dept)}&year=${encodeURIComponent(year)}`)
        .then(r => r.json()).then(data => renderReport(data, year))
        .catch(() => { document.getElementById('summaryTbody').innerHTML = '<tr><td colspan="3" class="empty-state" style="color:#ef4444">Failed to load.</td></tr>'; });
}

function renderReport(data, year) {
    const curMonth = new Date().getMonth() + 1;
    const curYear  = new Date().getFullYear();
    const isCurYr  = parseInt(year) === curYear;
    const monthly  = data.monthly || {};
    const maxVal   = Math.max(...Object.values(monthly).filter(v=>v>0), 1);
    const grand    = data.grand_total     || 0;
    const avg      = data.average_monthly || 0;
    const prev6    = data.prev_six_avg    || 0;

    // Stat cards
    document.getElementById('kpiGrand').textContent = 'RM ' + fmt(grand);
    document.getElementById('kpiAvg').textContent   = 'RM ' + fmt(avg);
    document.getElementById('kpiPrev6').textContent = 'RM ' + fmt(prev6);
    const peak = Object.entries(monthly).filter(([,v])=>v>0).sort((a,b)=>b[1]-a[1])[0];
    document.getElementById('kpiPeak').textContent    = peak ? monthNames[parseInt(peak[0])-1] : '—';
    document.getElementById('kpiPeakAmt').textContent = peak ? 'RM ' + fmt(peak[1]) : 'Record spend';

    // Chart
    document.getElementById('chartWrap').style.display = '';
    const values = Array.from({length:12}, (_, i) => monthly[i+1] || 0);
    if (chartInstance) chartInstance.destroy();
    chartInstance = new Chart(document.getElementById('spendChart'), {
        type: 'bar',
        data: { labels: monthNames.map(m=>m.slice(0,3)), datasets: [{ label:'RM', data:values,
            backgroundColor: values.map(v => v > 0 ? 'rgba(99,102,241,0.8)' : 'rgba(226,232,240,0.5)'),
            borderRadius: 5 }] },
        options: { responsive:true, maintainAspectRatio:false, plugins:{ legend:{display:false} },
            scales: { y:{ ticks:{ callback: v => 'RM '+(v>=1000?(v/1000).toFixed(0)+'k':v), font:{size:11} }, grid:{color:'#f1f5f9'} },
                      x:{ grid:{display:false}, ticks:{font:{size:11}} } } }
    });

    // Table
    let rows = '';
    for (let m = 1; m <= 12; m++) {
        const amt    = monthly[m] || 0;
        const has    = amt > 0;
        const isCur  = isCurYr && m === curMonth;
        const future = isCurYr && m > curMonth;
        const barW   = has ? Math.round((amt / maxVal) * 100) : 0;
        rows += `<tr class="${isCur?'current':''}">
            <td>${monthNames[m-1]}${isCur?' <span style="font-size:10px;background:#fef9c3;color:#854d0e;padding:2px 7px;border-radius:99px;font-weight:600;margin-left:6px;">current</span>':''}</td>
            <td style="text-align:right;font-weight:${has?'600':'400'};color:${has?'#111827':'#9ca3af'}">${future?'—':fmt(amt)}</td>
            <td>${has&&!future?`<div class="spend-bar" style="width:${barW}%"></div>`:''}</td>
        </tr>`;
    }
    document.getElementById('summaryTbody').innerHTML = rows;

    // Footer
    document.getElementById('summaryFooter').innerHTML = `
        <tr style="background:#f8fafc">
            <td style="font-weight:700;color:#111827">Grand Total</td>
            <td style="text-align:right;font-weight:700;color:#111827;width:180px">RM ${fmt(grand)}</td><td></td></tr>
        <tr style="background:#eff6ff">
            <td style="font-size:14px;color:#1d4ed8">Avg Monthly (YTD)</td>
            <td style="text-align:right;font-size:14px;color:#1d4ed8;width:180px">RM ${fmt(avg)}</td><td></td></tr>
        <tr style="background:#f5f3ff">
            <td style="font-size:14px;color:#7c3aed">Prev 6-Month Avg</td>
            <td style="text-align:right;font-size:14px;color:#7c3aed;width:180px">RM ${fmt(prev6)}</td><td></td></tr>`;
}

function fmt(n) { return parseFloat(n).toLocaleString('en-MY',{minimumFractionDigits:2,maximumFractionDigits:2}); }

document.addEventListener('DOMContentLoaded', loadReport);
</script>
</body>
</html>
