<?php
$d = $dashboard;
$money = static fn($v) => 'KSh ' . number_format((float)$v, 0);
$sessionTotals = array_map(static fn($x) => (int)($x['total'] ?? 0), $d['monthSessions'] ?? []);
$maxSessions = max(1, ...($sessionTotals ?: [0]));
$statusMap = [];
foreach (($d['statusCounts'] ?? []) as $row) $statusMap[(string)$row['status']] = (int)$row['total'];
$icon = static function(string $name): string {
    $paths = [
        'patients'=>'<circle cx="9" cy="8" r="3"/><path d="M3.5 19a5.5 5.5 0 0 1 11 0"/><path d="M16 6.5a3 3 0 0 1 0 5.5M17 16a4 4 0 0 1 3 3"/>',
        'session'=>'<circle cx="12" cy="12" r="8.5"/><path d="M12 7v5l3 2"/>',
        'assessment'=>'<rect x="5" y="3" width="14" height="18" rx="2"/><path d="M8 8h8M8 12h8M8 16h5"/>',
        'plan'=>'<rect x="4" y="4" width="16" height="16" rx="2"/><path d="m8 12 2.5 2.5L16 9"/>',
        'calendar'=>'<rect x="4" y="5" width="16" height="15" rx="2"/><path d="M8 3v4M16 3v4M4 10h16"/>',
        'invoice'=>'<path d="M6 3h12v18l-6-3-6 3z"/><path d="M9 8h6M9 12h6"/>',
        'payment'=>'<rect x="3" y="6" width="18" height="12" rx="2"/><path d="M3 10h18M7 15h3"/>',
        'add'=>'<path d="M12 5v14M5 12h14"/>',
    ];
    return '<svg class="dashboard-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">'.($paths[$name]??$paths['session']).'</svg>';
};
?>
<?php require dirname(__DIR__) . '/components/page-header.php'; ?>

<?php if ($isTherapistDashboard): ?>
<section class="role-hero therapist-hero">
    <div><span class="eyebrow">My workspace</span><h1>Your clinical day</h1><p>Patients, appointments and clinical work in one place.</p></div>
    <div class="dashboard-actions">
        <?php if (\App\Core\Auth::hasPermission('sessions.create')): ?><a class="btn btn-primary" href="/crm/public/sessions/create"><?= $icon('add') ?> New session</a><?php endif; ?>
        <?php if (\App\Core\Auth::hasPermission('assessments.create')): ?><a class="btn btn-secondary" href="/crm/public/assessments/create"><?= $icon('add') ?> Assessment</a><?php endif; ?>
    </div>
</section>

<div class="dashboard-stat-grid therapist-stats">
    <a class="dashboard-stat" href="/crm/public/patients"><span class="stat-icon"><?= $icon('patients') ?></span><span><small>My patients</small><strong><?= number_format((int)($d['assignedPatients'] ?? 0)) ?></strong><em>active</em></span><b>›</b></a>
    <a class="dashboard-stat" href="/crm/public/appointments"><span class="stat-icon"><?= $icon('calendar') ?></span><span><small>Today</small><strong><?= number_format(count($d['todayAppointments'] ?? [])) ?></strong><em>appointments</em></span><b>›</b></a>
    <a class="dashboard-stat" href="/crm/public/assessments"><span class="stat-icon"><?= $icon('assessment') ?></span><span><small>Assessments</small><strong><?= number_format((int)($d['assessmentCount'] ?? 0)) ?></strong><em>clinical</em></span><b>›</b></a>
    <a class="dashboard-stat" href="/crm/public/treatment-plans"><span class="stat-icon"><?= $icon('plan') ?></span><span><small>Active plans</small><strong><?= number_format((int)($d['activePlans'] ?? 0)) ?></strong><em>treatment</em></span><b>›</b></a>
</div>

<div class="dashboard-two-col">
    <article class="card dashboard-list-card">
        <div class="card-header compact-header"><div><h2>Today</h2><small class="section-subtitle"><?= date('l, d M') ?></small></div><a class="text-link" href="/crm/public/appointments">View all</a></div>
        <div class="dashboard-list">
        <?php foreach (($d['todayAppointments'] ?? []) as $a): ?>
            <a class="dashboard-list-row" href="/crm/public/appointments?view=day&date=<?= htmlspecialchars($a['appointment_date']) ?>">
                <span class="list-time"><?= $a['start_time'] ? htmlspecialchars(date('g:i', strtotime($a['start_time']))) : '—' ?><small><?= $a['start_time'] ? htmlspecialchars(date('A', strtotime($a['start_time']))) : '' ?></small></span>
                <span class="list-main"><strong><?= htmlspecialchars($a['first_name'].' '.$a['last_name']) ?></strong><small><?= htmlspecialchars($a['service_name'] ?: 'Therapy appointment') ?></small></span>
                <span class="list-status <?= in_array($a['status'],['confirmed','completed'],true)?'done':'' ?>"><?= htmlspecialchars(ucfirst(str_replace('_',' ',$a['status']))) ?></span><b>›</b>
            </a>
        <?php endforeach; ?>
        <?php if (!($d['todayAppointments'] ?? [])): ?>
            <div class="clean-empty"><span><?= $icon('calendar') ?></span><strong>No appointments today</strong><small>Your calendar is clear. Your next appointments will appear here.</small><a class="text-link" href="/crm/public/appointments">Open calendar →</a></div>
        <?php endif; ?>
        </div>
    </article>
    <article class="card dashboard-list-card">
        <div class="card-header compact-header"><div><h2>Coming up</h2><small class="section-subtitle">Next appointments</small></div><a class="text-link" href="/crm/public/appointments">View calendar</a></div>
        <div class="dashboard-list">
        <?php foreach (($d['upcomingAppointments'] ?? []) as $a): ?><a class="dashboard-list-row" href="/crm/public/appointments?view=day&date=<?= htmlspecialchars($a['appointment_date']) ?>"><span class="date-tile"><b><?= date('d', strtotime($a['appointment_date'])) ?></b><small><?= date('M', strtotime($a['appointment_date'])) ?></small></span><span class="list-main"><strong><?= htmlspecialchars($a['first_name'].' '.$a['last_name']) ?></strong><small><?= htmlspecialchars($a['service_name'] ?: 'Therapy') ?><?= $a['start_time'] ? ' · '.date('g:i A', strtotime($a['start_time'])) : '' ?></small></span><span class="list-status"><?= htmlspecialchars(ucfirst(str_replace('_',' ',$a['status']))) ?></span><b>›</b></a><?php endforeach; ?>
        <?php if (!($d['upcomingAppointments'] ?? [])): ?><div class="clean-empty"><span><?= $icon('calendar') ?></span><strong>No upcoming appointments</strong><small>Your next scheduled visits will appear here.</small><a class="text-link" href="/crm/public/appointments">Open calendar →</a></div><?php endif; ?>
        </div>
    </article>
</div>

<div class="dashboard-quick-grid">
    <?php if (\App\Core\Auth::hasPermission('patients.view')): ?><a href="/crm/public/patients"><span><?= $icon('patients') ?></span><strong>My patients</strong><small>Assigned patients</small></a><?php endif; ?>
    <?php if (\App\Core\Auth::hasPermission('sessions.view')): ?><a href="/crm/public/sessions"><span><?= $icon('session') ?></span><strong>Sessions</strong><small>Clinical notes</small></a><?php endif; ?>
    <?php if (\App\Core\Auth::hasPermission('assessments.view')): ?><a href="/crm/public/assessments"><span><?= $icon('assessment') ?></span><strong>Assessments</strong><small>Clinical reviews</small></a><?php endif; ?>
    <?php if (\App\Core\Auth::hasPermission('treatment_plans.view')): ?><a href="/crm/public/treatment-plans"><span><?= $icon('plan') ?></span><strong>Treatment plans</strong><small>Goals & progress</small></a><?php endif; ?>
    <?php if (\App\Core\Auth::hasPermission('appointments.view')): ?><a href="/crm/public/appointments"><span><?= $icon('calendar') ?></span><strong>Appointments</strong><small>Your schedule</small></a><?php endif; ?>
</div>

<?php else: ?>
<section class="role-hero admin-hero">
    <div><span class="eyebrow">Business overview</span><h1>Good day</h1><p>A quick view of your clinic today.</p></div>
    <div class="dashboard-actions">
        <?php if (\App\Core\Auth::hasPermission('sessions.create')): ?><a class="btn btn-primary" href="/crm/public/sessions/create"><?= $icon('add') ?> Session</a><?php endif; ?>
        <?php if (\App\Core\Auth::hasPermission('invoice.create')): ?><a class="btn btn-secondary" href="/crm/public/invoices/from-sessions"><?= $icon('invoice') ?> Invoice</a><?php endif; ?>
    </div>
</section>

<div class="dashboard-stat-grid admin-stats">
    <a class="dashboard-stat" href="/crm/public/patients"><span class="stat-icon"><?= $icon('patients') ?></span><span><small>Patients</small><strong><?= number_format((int)($d['activePatients'] ?? 0)) ?></strong><em>active</em></span><b>›</b></a>
    <a class="dashboard-stat" href="/crm/public/sessions"><span class="stat-icon"><?= $icon('session') ?></span><span><small>Today</small><strong><?= number_format((int)($d['sessionsToday'] ?? 0)) ?></strong><em>sessions</em></span><b>›</b></a>
    <a class="dashboard-stat" href="/crm/public/invoices/from-sessions"><span class="stat-icon"><?= $icon('invoice') ?></span><span><small>To bill</small><strong><?= number_format((int)($d['billableUninvoiced'] ?? 0)) ?></strong><em>items</em></span><b>›</b></a>
    <a class="dashboard-stat" href="/crm/public/payments"><span class="stat-icon"><?= $icon('payment') ?></span><span><small>Outstanding</small><strong><?= $money($d['outstanding'] ?? 0) ?></strong><em><?= $money($d['overdue'] ?? 0) ?> overdue</em></span><b>›</b></a>
</div>

<div class="dashboard-two-col admin-main-grid">
    <article class="card dashboard-chart-card"><div class="card-header compact-header"><div><h2>Sessions</h2><small class="section-subtitle">Last 6 months</small></div></div><div class="bar-chart" aria-label="Session activity chart"><?php foreach (($d['monthSessions'] ?? []) as $row): $height=max(8,(int)round(((int)$row['total']/$maxSessions)*100)); ?><div class="bar-item"><div class="bar-value"><?= (int)$row['total'] ?></div><div class="bar-track"><div class="bar-fill" style="height:<?= $height ?>%"></div></div><span><?= htmlspecialchars($row['label']) ?></span></div><?php endforeach; ?><?php if (!($d['monthSessions'] ?? [])): ?><div class="empty-state"><strong>No data</strong></div><?php endif; ?></div></article>
    <article class="card dashboard-chart-card"><div class="card-header compact-header"><div><h2>Billing</h2><small class="section-subtitle">Invoice status</small></div></div><div class="invoice-status-list"><?php $labels=['unpaid'=>'Unpaid','partially_paid'=>'Partial','paid'=>'Paid','cancelled'=>'Cancelled']; foreach($labels as $key=>$label): $count=$statusMap[$key]??0; $total=max(1,array_sum($statusMap)); $pct=round(($count/$total)*100); ?><div class="status-row"><div><span><?= $label ?></span><strong><?= $count ?></strong></div><div class="status-track"><span style="width:<?= $pct ?>%"></span></div></div><?php endforeach; ?></div><div class="billing-summary"><div><span>Collected</span><strong><?= $money($d['paidMonth'] ?? 0) ?></strong></div><div><span>Overdue</span><strong><?= $money($d['overdue'] ?? 0) ?></strong></div></div></article>
</div>

<div class="dashboard-two-col">
    <article class="card dashboard-list-card"><div class="card-header compact-header"><div><h2>Upcoming</h2><small class="section-subtitle">Next clinical work</small></div><a class="text-link" href="/crm/public/appointments">All</a></div><div class="dashboard-list"><?php foreach (($d['upcoming'] ?? []) as $s): ?><a class="dashboard-list-row" href="/crm/public/sessions/<?= (int)$s['id'] ?>/edit"><span class="date-tile"><b><?= date('d',strtotime($s['session_date'])) ?></b><small><?= date('M',strtotime($s['session_date'])) ?></small></span><span class="list-main"><strong><?= htmlspecialchars($s['first_name'].' '.$s['last_name']) ?></strong><small><?= htmlspecialchars($s['service_name']?:'Therapy') ?><?= $s['start_time']?' · '.date('g:i A',strtotime($s['start_time'])):'' ?></small></span><b>›</b></a><?php endforeach; ?><?php if (!($d['upcoming'] ?? [])): ?><div class="clean-empty"><span>✓</span><strong>No upcoming sessions</strong></div><?php endif; ?></div></article>
    <article class="card dashboard-actions-card"><div class="card-header compact-header"><div><h2>Quick access</h2><small class="section-subtitle">Common tasks</small></div></div><div class="admin-quick-links"><?php if(\App\Core\Auth::hasPermission('patients.view')): ?><a href="/crm/public/patients"><?= $icon('patients') ?><span>Patients</span></a><?php endif; ?><?php if(\App\Core\Auth::hasPermission('appointments.view')): ?><a href="/crm/public/appointments"><?= $icon('calendar') ?><span>Appointments</span></a><?php endif; ?><?php if(\App\Core\Auth::hasPermission('invoice.view')): ?><a href="/crm/public/invoices"><?= $icon('invoice') ?><span>Invoices</span></a><?php endif; ?><?php if(\App\Core\Auth::hasPermission('payment.view')): ?><a href="/crm/public/payments"><?= $icon('payment') ?><span>Payments</span></a><?php endif; ?></div></article>
</div>
<?php endif; ?>
