<?php
// dashboards/driver.php — included by dashboard.php (session already started)
include $_SERVER['DOCUMENT_ROOT'] . "/app/dashboard/classes/dashboard.class.php";
$username = $_SESSION['username'] ?? 'Driver';
$user_id  = (int) $_SESSION['user_id'];
$team_id  = (int) $_SESSION['team_id'];
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Driver Dashboard</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <link href="https://fonts.googleapis.com/css2?family=Bebas+Neue&family=DM+Sans:wght@300;400;500;600&family=DM+Mono:wght@400;500&display=swap" rel="stylesheet">
    <style>
        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
        :root {
            --bg:         #f0f4fa;
            --surface:    #ffffff;
            --surface2:   #e8eef8;
            --border:     #d0daea;
            --blue:       #1a56c4;
            --blue-light: #e8f0fd;
            --orange:     #e8720a;
            --text:       #0f1e3d;
            --muted:      #6b7fa8;
            --white:      #ffffff;
            --radius:     8px;
        }
        html, body { height: 100%; background: var(--bg); color: var(--text);
            font-family: 'DM Sans', sans-serif; }
        .shell { display: grid; grid-template-rows: 52px 1fr; height: 100vh; }

        /* TOPBAR */
        .topbar { display:flex; align-items:center; justify-content:space-between;
            padding:0 24px; background:var(--blue); gap:16px; }
        .topbar-left { display:flex; align-items:center; gap:14px; }
        .logo-mark { width:28px; height:28px; background:var(--orange); flex-shrink:0;
            clip-path:polygon(50% 0%,100% 25%,100% 75%,50% 100%,0% 75%,0% 25%); }
        .page-title { font-family:'Bebas Neue'; font-size:20px; letter-spacing:2px; color:#fff; }
        .page-title span { color:var(--orange); }
        .divider-v { width:1px; height:24px; background:rgba(255,255,255,.25); }
        .role-badge { padding:3px 10px; border-radius:20px; background:var(--orange);
            font-size:11px; font-weight:700; letter-spacing:1px; color:#fff; text-transform:uppercase; }
        .user-name { font-size:13px; color:rgba(255,255,255,.85); font-weight:500; }
        .btn-logout { display:flex; align-items:center; gap:6px; padding:6px 14px;
            background:rgba(255,255,255,.12); border:1px solid rgba(255,255,255,.25);
            color:#fff; border-radius:var(--radius); font-family:'DM Sans'; font-size:12px;
            font-weight:600; cursor:pointer; text-decoration:none; transition:background .2s; }
        .btn-logout:hover { background:rgba(255,255,255,.22); }

        /* GRID: 3 columns, 2 rows */
        .main { display:grid;
            grid-template-columns: 1fr 1fr 1fr;
            grid-template-rows: 1fr 1fr;
            gap:12px; padding:12px; overflow:hidden; height:100%; }
        .span2 { grid-column: span 2; }

        /* PANEL */
        .panel { background:var(--white); border:1px solid var(--border);
            border-radius:var(--radius); display:flex; flex-direction:column;
            overflow:hidden; position:relative; box-shadow:0 1px 4px rgba(26,86,196,.07); }
        .panel::before { content:''; position:absolute; top:0; left:0; right:0; height:3px;
            background:linear-gradient(90deg,var(--blue),var(--orange));
            border-radius:var(--radius) var(--radius) 0 0; }
        .panel-head { display:flex; align-items:center; justify-content:space-between;
            padding:10px 14px; border-bottom:1px solid var(--border); flex-shrink:0; }
        .panel-label { font-size:10px; font-weight:700; text-transform:uppercase;
            letter-spacing:1.5px; color:var(--blue); }
        .badge { font-family:'DM Mono'; font-size:10px; padding:2px 8px; border-radius:20px;
            background:var(--blue-light); border:1px solid var(--border); color:var(--blue); font-weight:600; }
        .panel-body { flex:1; overflow:hidden; padding:12px 14px; display:flex; flex-direction:column; }

        /* CHART */
        .chart-wrap { flex:1; position:relative; min-height:0; }
        canvas { position:absolute; inset:0; }

        /* TABLE */
        .tbl-wrap { flex:1; overflow-y:auto; }
        .tbl-wrap::-webkit-scrollbar { width:4px; }
        .tbl-wrap::-webkit-scrollbar-thumb { background:var(--border); border-radius:4px; }
        table { width:100%; border-collapse:collapse; }
        thead th { position:sticky; top:0; background:var(--blue-light);
            padding:7px 10px; font-size:10px; font-weight:700; text-transform:uppercase;
            letter-spacing:1px; color:var(--blue); text-align:left; border-bottom:1px solid var(--border); }
        tbody tr { border-bottom:1px solid var(--border); transition:background .15s; }
        tbody tr:hover { background:var(--blue-light); }
        tbody td { padding:7px 10px; font-size:12px; color:var(--text); }
        .td-mono { font-family:'DM Mono'; font-size:11px; }
        .td-muted { color:var(--muted); font-size:11px; }

        /* STATUS PILL */
        .status-pill { display:inline-block; padding:2px 8px; border-radius:20px;
            font-size:10px; font-weight:700; text-transform:uppercase; letter-spacing:.5px; }
        .status-active    { background:#dbeafe; color:#1d4ed8; }
        .status-completed { background:#dcfce7; color:#15803d; }
        .status-other     { background:#f1f5f9; color:#64748b; }

        /* LOADING */
        .state-idle { display:flex; flex-direction:column; align-items:center;
            justify-content:center; height:100%; gap:8px; color:var(--muted); }
        .state-idle svg { opacity:.25; }
        .pulse { display:inline-block; width:8px; height:8px; background:var(--orange);
            border-radius:50%; animation:pulse 1.2s ease-in-out infinite; }
        @keyframes pulse { 0%,100%{opacity:1;transform:scale(1)} 50%{opacity:.4;transform:scale(.6)} }
        /* TIME STAT CARDS */
        .time-cards { display:flex; flex-direction:column; gap:8px; width:100%; }
        .time-card { display:flex; align-items:center; justify-content:space-between;
            padding:10px 14px; border-radius:6px; border:1px solid var(--border);
            background:var(--bg); transition:border-color .2s; }
        .time-card:hover { border-color:var(--blue); }
        .time-card-left { display:flex; align-items:center; gap:10px; }
        .time-dot { width:10px; height:10px; border-radius:50%; flex-shrink:0; }
        .dot-rieming  { background:#1a56c4; }
        .dot-drilling { background:#e8720a; }
        .dot-casing   { background:#2e6dd6; }
        .dot-blasting { background:#c2500a; }
        .time-card-name { font-size:11px; font-weight:700; text-transform:uppercase;
            letter-spacing:1px; color:var(--muted); }
        .time-card-value { font-family:'Bebas Neue'; font-size:26px; letter-spacing:1px; }
        .val-rieming  { color:#1a56c4; }
        .val-drilling { color:#e8720a; }
        .val-casing   { color:#2e6dd6; }
        .val-blasting { color:#c2500a; }
        .time-bar-track { height:4px; background:var(--border); border-radius:4px;
            margin-top:4px; overflow:hidden; }
        .time-bar-fill { height:100%; border-radius:4px; transition:width .6s ease; }

        /* ── MOBILE OVERRIDES ── */
        @media (max-width: 767px) {
            html, body      { overflow-x: hidden; }
            .shell, .shell-switcher { overflow-x: hidden; width: 100%; }

            /* Topbar */
            .topbar         { height: 80px; padding: 0 14px; }
            .page-title     { font-size: 40px !important; }
            .btn-refresh,
            .btn-logout     { font-size: 30px !important; padding: 10px 16px; }

            /* Switcher */
            .switcher       { overflow-x: auto; scrollbar-width: none; top: 80px; }
            .switcher::-webkit-scrollbar { display: none; }
            .switcher-btn   { font-size: 28px !important; padding: 0 18px; height: 56px; flex-shrink: 0; white-space: nowrap; min-width: max-content; }
            .sw-count       { font-size: 22px !important; height: 28px; min-width: 28px; }

            /* Dev tab bar */
            .tab-bar        { overflow-x: auto; scrollbar-width: none; }
            .tab-bar::-webkit-scrollbar { display: none; }
            .tab-btn        { font-size: 28px !important; padding: 0 18px; height: 56px; flex-shrink: 0; white-space: nowrap; }
            .tab-count      { font-size: 20px !important; }

            /* Stat tiles */
            .stat-strip     { grid-template-columns: repeat(2, 1fr) !important; gap: 10px; }
            .stat-tile      { padding: 16px; gap: 16px; }
            .stat-icon      { width: 50px; height: 50px; }
            .stat-icon svg  { width: 26px; height: 26px; }
            .stat-num       { font-size: 70px; }
            .stat-lbl       { font-size: 28px !important; }

            /* Panels */
            .panel          { min-height: 280px; }
            .panel-head     { padding: 16px 14px; }
            .panel-body     { padding: 16px; }
            .panel-label    { font-size: 40px !important; }
            .badge          { font-size: 28px !important; padding: 5px 12px; }

            /* Stat cards */
            .stat-card      { padding: 16px; min-height: 80px; }
            .stat-card-label { font-size: 28px !important; }
            .stat-card-sub  { font-size: 24px !important; }
            .stat-card-value { font-size: 56px !important; }

            /* Big stat */
            .big-stat-num   { font-size: 100px !important; }
            .big-stat-sub   { font-size: 28px !important; }

            /* KPI cards */
            .kpi-val        { font-size: 56px !important; }
            .kpi-lbl        { font-size: 26px !important; }
            .kpi-sub        { font-size: 24px !important; }

            /* Search / toolbar */
            .toolbar        { padding: 12px; gap: 10px; }
            .search-bar     { padding: 12px; }
            .search-input   { font-size: 35px !important; padding: 12px; }
            .filter-select  { font-size: 35px !important; padding: 10px 12px; }

            /* Tables */
            table           { min-width: 700px; }
            .tbl-wrap       { max-height: 500px; }
            thead th        { font-size: 30px !important; padding: 12px 10px; }
            tbody td        { font-size: 30px !important; padding: 12px 10px; }
            .td-mono        { font-size: 30px !important; }
            .td-muted       { font-size: 28px !important; }

            /* Qty badge & action buttons */
            .qty            { font-size: 28px !important; height: 48px; min-width: 48px; }
            .btn-in,
            .btn-out        { font-size: 28px !important; padding: 10px 16px; }
            .days-badge     { font-size: 28px !important; padding: 6px 12px; }
            .type-pill      { font-size: 26px !important; padding: 5px 12px; }
            .pill-repair    { font-size: 26px !important; padding: 5px 12px; }

            /* Team sections */
            .team-section   { padding: 14px 16px; }
            .team-section-name { font-size: 32px !important; }
            .team-open-count { font-size: 56px !important; }
            .bar-label      { font-size: 26px !important; width: 70px; }
            .bar-track      { height: 10px; }
            .bar-count      { font-size: 26px !important; width: 32px; }
            .team-done-note { font-size: 24px !important; }
            .team-scroll    { max-height: 500px; }

            /* Members */
            .member-row     { padding: 14px; gap: 14px; }
            .member-avatar  { width: 50px; height: 50px; font-size: 20px; }
            .member-name    { font-size: 32px !important; }

            /* Time cards */
            .time-cards     { gap: 10px; }
            .time-card      { padding: 14px 16px; }
            .time-card-name  { font-size: 28px !important; }
            .time-card-value { font-size: 48px !important; }
            .time-dot       { width: 14px; height: 14px; }
            .time-bar-track { height: 8px; }

            /* Transactions */
            .trans-list     { max-height: 500px; }
            .trans-item     { padding: 16px 14px; gap: 14px; }
            .trans-dot      { width: 14px; height: 14px; margin-top: 8px; }
            .trans-name     { font-size: 40px !important; white-space: normal; }
            .trans-meta     { font-size: 36px !important; }
            .trans-badge    { font-size: 36px !important; padding: 6px 14px; }

            /* Water cards */
            .water-card     { padding: 14px 16px; }
            .water-name     { font-size: 32px !important; }
            .water-addr     { font-size: 28px !important; }
            .water-badge    { font-size: 28px !important; padding: 5px 12px; }

            /* Dispatch panels */
            .panel-low, .panel-book { min-height: 360px; }

            /* Depth tag */
            .depth-tag      { font-size: 28px !important; }
        }
    </style>
    <link rel="stylesheet" href="/app/dashboard/dashboard_responsive.css">
</head>
<body>
<div class="shell">

    <header class="topbar">
        <div class="topbar-left">
            <div class="logo-mark"></div>
            <span class="page-title">MY <span>DASHBOARD</span></span>
            <div class="divider-v"></div>
            <span class="role-badge">Driver</span>
            <span class="user-name"><?= htmlspecialchars($username) ?></span>
        </div>
        <a class="btn-logout" href="/logout.php">
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>
            Logout
        </a>
    </header>

    <main class="main">

        <!-- ROW 1: Meters chart (spans 2 cols) -->
        <div class="panel panel-chart span2">
            <div class="panel-head">
                <span class="panel-label">My Meters This Month</span>
                <span class="badge" id="meters-total">Loading…</span>
            </div>
            <div class="panel-body">
                <div id="meters-state" class="state-idle"><span class="pulse"></span></div>
                <div class="chart-wrap" id="meters-chart-wrap" style="display:none">
                    <canvas id="metersChart"></canvas>
                </div>
            </div>
        </div>

        <!-- ROW 1 COL 3: Active jobcards count -->
        <div class="panel" style="justify-content:center;">
            <div class="panel-head">
                <span class="panel-label">Active Jobcards</span>
            </div>
            <div class="panel-body" style="align-items:center;justify-content:center;">
                <div id="active-count" style="font-family:'Bebas Neue';font-size:72px;line-height:1;color:var(--blue);letter-spacing:2px;">—</div>
                <div style="font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:1px;margin-top:4px;">Open Jobcards</div>
            </div>
        </div>

        <!-- ROW 2 LEFT: Drilling bits -->
        <div class="panel">
            <div class="panel-head">
                <span class="panel-label">Drilling Bit Meters</span>
                <span class="badge" id="drill-bits-count">—</span>
            </div>
            <div class="panel-body" style="padding:0">
                <div class="tbl-wrap">
                    <table>
                        <thead><tr><th>Bit Serial</th><th>Total Meters</th></tr></thead>
                        <tbody id="drill-bits-body">
                            <tr><td colspan="2" style="text-align:center;padding:20px"><span class="pulse"></span></td></tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- ROW 2 MID: Rieming bits -->
        <div class="panel">
            <div class="panel-head">
                <span class="panel-label">Rieming Bit Meters</span>
                <span class="badge" id="riem-bits-count">—</span>
            </div>
            <div class="panel-body" style="padding:0">
                <div class="tbl-wrap">
                    <table>
                        <thead><tr><th>Bit Serial</th><th>Total Meters</th></tr></thead>
                        <tbody id="riem-bits-body">
                            <tr><td colspan="2" style="text-align:center;padding:20px"><span class="pulse"></span></td></tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- ROW 2 RIGHT: Time spent per activity -->
        <div class="panel">
            <div class="panel-head">
                <span class="panel-label">Time Spent — All Time</span>
                <span class="badge" id="time-total-badge">Loading...</span>
            </div>
            <div class="panel-body" style="justify-content:center;gap:10px;" id="time-spent-body">
                <div class="state-idle"><span class="pulse"></span></div>
            </div>
        </div>

    </main>
</div>

<script>
const USER_ID = <?= $user_id ?>;
const TEAM_ID = <?= $team_id ?>;
const TICK = { color:'#1a3a6e', font:{ family:'DM Sans', size:11 } };
const TT   = { backgroundColor:'#fff', borderColor:'#d0daea', borderWidth:1,
               titleColor:'#0f1e3d', bodyColor:'#6b7fa8', padding:10 };

// ── METERS ───────────────────────────────────────────────
fetch(`/app/dashboard/ajax/meters_month.ajax.php?user_id=${USER_ID}`)
    .then(r => r.text())
    .then(csv => {
        const values = csv.split(',').map(Number);
        const total  = values.reduce((a,b) => a+b, 0);
        document.getElementById('meters-total').textContent = total.toLocaleString() + ' m';
        document.getElementById('meters-state').style.display = 'none';
        document.getElementById('meters-chart-wrap').style.display = 'block';

        new Chart(document.getElementById('metersChart'), {
            type: 'bar',
            data: {
                labels: ['RIEMING','DRILLING','CASING','BLASTING'],
                datasets:[{
                    data: values,
                    backgroundColor:['rgba(26,86,196,0.85)','rgba(232,114,10,0.85)',
                                     'rgba(26,86,196,0.45)','rgba(232,114,10,0.45)'],
                    borderColor:['#1a56c4','#e8720a','#1a56c4','#e8720a'],
                    borderWidth:2, borderRadius:5, borderSkipped:'bottom'
                }]
            },
            options:{
                responsive:true, maintainAspectRatio:false,
                plugins:{ legend:{display:false}, tooltip:{...TT,
                    callbacks:{ label: c => ` ${c.parsed.y.toLocaleString()} m` }}},
                scales:{
                    x:{ grid:{display:false}, ticks:TICK },
                    y:{ beginAtZero:true, grid:{color:'rgba(26,86,196,0.08)'}, ticks:TICK }
                }
            }
        });
    });

// ── ACTIVE JOBCARDS COUNT ─────────────────────────────────
fetch(`/app/dashboard/ajax/jobcards_list.ajax.php?team_id=${TEAM_ID}&status=active&count_only=1`)
    .then(r => r.text())
    .then(n => { document.getElementById('active-count').textContent = n || '0'; });

// ── TIME SPENT ────────────────────────────────────────────
fetch(`/app/dashboard/ajax/time_spent.ajax.php?user_id=${USER_ID}`)
    .then(r => r.json())
    .then(data => {
        const activities = [
            { key:'RIEMING',  label:'Rieming',  dotCls:'dot-rieming',  valCls:'val-rieming',  barColor:'#1a56c4' },
            { key:'DRILLING', label:'Drilling', dotCls:'dot-drilling', valCls:'val-drilling', barColor:'#e8720a' },
            { key:'CASING',   label:'Casing',   dotCls:'dot-casing',   valCls:'val-casing',   barColor:'#2e6dd6' },
            { key:'BLASTING', label:'Blasting', dotCls:'dot-blasting', valCls:'val-blasting', barColor:'#c2500a' },
        ];

        const maxSec = Math.max(...activities.map(a => data[a.key]?.seconds || 0), 1);
        const totalH = activities.reduce((s,a) => s + (data[a.key]?.hours || 0), 0);

        document.getElementById('time-total-badge').textContent =
            totalH.toFixed(1) + ' hrs total';

        const body = document.getElementById('time-spent-body');
        body.innerHTML = `<div class="time-cards">${
            activities.map(a => {
                const d    = data[a.key] || { label:'0h 00m', seconds:0 };
                const pct  = Math.round((d.seconds / maxSec) * 100);
                return `
                <div class="time-card">
                    <div style="flex:1">
                        <div class="time-card-left">
                            <span class="time-dot ${a.dotCls}"></span>
                            <span class="time-card-name">${a.label}</span>
                        </div>
                        <div class="time-bar-track">
                            <div class="time-bar-fill" style="width:${pct}%;background:${a.barColor}"></div>
                        </div>
                    </div>
                    <span class="time-card-value ${a.valCls}">${d.label}</span>
                </div>`;
            }).join('')
        }</div>`;
    });

// ── BIT TABLES ────────────────────────────────────────────
fetchBits(`/app/dashboard/ajax/bit_meters.ajax.php?type=DRILLING+BIT&user_id=${USER_ID}`, 'drill-bits-body', 'drill-bits-count');
fetchBits(`/app/dashboard/ajax/bit_meters.ajax.php?type=RIEMING+BIT&user_id=${USER_ID}`,  'riem-bits-body',  'riem-bits-count');

function fetchBits(url, bodyId, countId) {
    fetch(url).then(r => r.json()).then(rows => {
        document.getElementById(countId).textContent = rows.length + ' bits';
        const body = document.getElementById(bodyId);
        if (!rows.length) { body.innerHTML='<tr><td colspan="2" class="td-muted" style="text-align:center;padding:16px">No data</td></tr>'; return; }
        body.innerHTML = rows.map(r => `<tr>
            <td class="td-mono">${esc(r.serial)}</td>
            <td><strong>${r.meters.toLocaleString()}</strong> <span class="td-muted">m</span></td>
        </tr>`).join('');
    });
}

function esc(s) {
    return String(s ?? '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}
</script>
</body>
</html>