<?php
declare(strict_types=1);

require_once __DIR__ . '/includes/layout.php';
require_once __DIR__ . '/includes/dashboard-data.php';

require_login();
if (!crm_dashboard_role_allowed()) {
    header('Location: /dashboard.php');
    exit;
}

$context = console_user_context();
$displayName = (string)($context['displayName'] ?? 'CRM Administrator');
$errorMessage = '';
try {
    $data = crm_dashboard_data();
} catch (Throwable $error) {
    $errorMessage = $error->getMessage();
    $data = [
        'leads' => ['total' => 0, 'open' => 0, 'converted' => 0, 'lost' => 0, 'today' => 0, 'month' => 0],
        'followups' => ['overdue' => 0, 'today' => 0, 'upcoming' => 0],
        'quotations' => ['documents' => 0, 'approved' => 0, 'cancelled' => 0, 'open' => 0, 'subtotal' => 0, 'gst' => 0, 'total' => 0],
        'status_rows' => [], 'trend_rows' => [], 'top_users' => [], 'latest_leads' => [], 'due_leads' => [],
        'max_trend' => 1, 'max_status' => 1,
    ];
}

console_header('CRM Dashboard', 'dashboard.php');
?>
<link rel="stylesheet" href="<?= crm_e(crm_url('assets/css/crm.css')) ?>">
<div class="crm-module crm-dashboard page-content">
    <section class="crm-dashboard-hero">
        <div>
            <span class="crm-dashboard-eyebrow"><i class="fa-solid fa-chart-line"></i> CRM Command Center</span>
            <h1>Good <?= date('H') < 12 ? 'Morning' : (date('H') < 17 ? 'Afternoon' : 'Evening') ?>, <?= crm_e($displayName) ?></h1>
            <p>A complete live overview of leads, follow-ups, quotations and conversions.</p>
        </div>
        <div class="crm-dashboard-actions">
            <a class="button white" href="<?= crm_e(crm_url('reports/lead-map.php')) ?>"><i class="fa-solid fa-map-location-dot"></i> Lead Map</a>
            <a class="button white" href="<?= crm_e(crm_url('operations/quotations.php')) ?>"><i class="fa-solid fa-file-invoice-dollar"></i> Quotations</a>
            <a class="button accent" href="<?= crm_e(crm_url('operations/lead-entry.php')) ?>"><i class="fa-solid fa-plus"></i> New Lead</a>
        </div>
    </section>

    <?php if ($errorMessage !== ''): ?>
        <div class="report-notice"><i class="fa-solid fa-circle-info"></i> <?= crm_e($errorMessage) ?></div>
    <?php endif; ?>

    <section class="crm-dashboard-kpis">
        <a class="crm-dashboard-kpi blue" href="<?= crm_e(crm_url('operations/leads.php')) ?>">
            <span><i class="fa-solid fa-users"></i> Total Leads</span>
            <strong><?= crm_n($data['leads']['total']) ?></strong>
            <small><?= crm_n($data['leads']['month']) ?> this month · <?= crm_n($data['leads']['today']) ?> today</small>
        </a>
        <a class="crm-dashboard-kpi violet" href="<?= crm_e(crm_url('reports/status-summary.php')) ?>">
            <span><i class="fa-solid fa-filter-circle-dollar"></i> Open Pipeline</span>
            <strong><?= crm_n($data['leads']['open']) ?></strong>
            <small><?= crm_pct($data['leads']['open'], $data['leads']['total']) ?> of all leads</small>
        </a>
        <a class="crm-dashboard-kpi amber" href="<?= crm_e(crm_url('reports/follow-up.php?scope=overdue')) ?>">
            <span><i class="fa-solid fa-clock"></i> Follow-ups</span>
            <strong><?= crm_n($data['followups']['today']) ?></strong>
            <small><?= crm_n($data['followups']['overdue']) ?> overdue · <?= crm_n($data['followups']['upcoming']) ?> next 7 days</small>
        </a>
        <a class="crm-dashboard-kpi emerald" href="<?= crm_e(crm_url('reports/conversion-summary.php')) ?>">
            <span><i class="fa-solid fa-circle-check"></i> Converted Leads</span>
            <strong><?= crm_n($data['leads']['converted']) ?></strong>
            <small><?= crm_pct($data['leads']['converted'], $data['leads']['total']) ?> conversion rate</small>
        </a>
        <a class="crm-dashboard-kpi indigo" href="<?= crm_e(crm_url('operations/quotations.php')) ?>">
            <span><i class="fa-solid fa-file-invoice"></i> Quotations</span>
            <strong><?= crm_n($data['quotations']['documents']) ?></strong>
            <small><?= crm_n($data['quotations']['open']) ?> awaiting decision</small>
        </a>
        <a class="crm-dashboard-kpi rose" href="<?= crm_e(crm_url('reports/quotation-summary.php')) ?>">
            <span><i class="fa-solid fa-indian-rupee-sign"></i> Quotation Value</span>
            <strong><?= crm_money($data['quotations']['total']) ?></strong>
            <small><?= crm_money($data['quotations']['gst']) ?> GST included</small>
        </a>
    </section>

    <section class="crm-dashboard-grid crm-dashboard-grid-main">
        <article class="card crm-dashboard-panel crm-trend-panel">
            <div class="crm-panel-head">
                <div><span>Performance</span><h2>Leads & Quotations Trend</h2></div>
                <a href="<?= crm_e(crm_url('reports/yearly-summary.php')) ?>">Yearly report <i class="fa-solid fa-arrow-right"></i></a>
            </div>
            <div class="crm-trend-chart" aria-label="Last 12 months leads and quotations">
                <?php foreach ($data['trend_rows'] as $row): ?>
                    <?php
                    $leadHeight = max(2, (int)round((int)$row['leads'] * 100 / max(1, $data['max_trend'])));
                    $quoteHeight = max(2, (int)round((int)$row['quotes'] * 100 / max(1, $data['max_trend'])));
                    ?>
                    <div class="crm-trend-month" title="<?= crm_e($row['month_key'] . ': ' . $row['leads'] . ' leads, ' . $row['quotes'] . ' quotations') ?>">
                        <div class="crm-trend-bars">
                            <i class="leads" style="height:<?= $leadHeight ?>%"></i>
                            <i class="quotes" style="height:<?= $quoteHeight ?>%"></i>
                        </div>
                        <span><?= crm_e((string)$row['label']) ?></span>
                    </div>
                <?php endforeach; ?>
            </div>
            <div class="crm-chart-legend"><span><i class="leads"></i> Leads</span><span><i class="quotes"></i> Quotations</span></div>
        </article>

        <article class="card crm-dashboard-panel">
            <div class="crm-panel-head">
                <div><span>Pipeline</span><h2>Lead Status Overview</h2></div>
                <a href="<?= crm_e(crm_url('reports/status-summary.php')) ?>">Details <i class="fa-solid fa-arrow-right"></i></a>
            </div>
            <div class="crm-status-stack">
                <?php foreach (array_slice($data['status_rows'], 0, 8) as $row): ?>
                    <div class="crm-status-row">
                        <div><span><?= crm_e((string)$row['label']) ?></span><strong><?= crm_n($row['total']) ?></strong></div>
                        <div class="crm-status-track"><i style="width:<?= max(2, (int)round((int)$row['total'] * 100 / max(1, $data['max_status']))) ?>%"></i></div>
                    </div>
                <?php endforeach; ?>
            </div>
        </article>
    </section>

    <section class="crm-dashboard-grid crm-dashboard-grid-work">
        <article class="card crm-dashboard-panel">
            <div class="crm-panel-head">
                <div><span>Action Required</span><h2>Due & Overdue Follow-ups</h2></div>
                <a href="<?= crm_e(crm_url('reports/follow-up.php')) ?>">Open worklist <i class="fa-solid fa-arrow-right"></i></a>
            </div>
            <div class="crm-dashboard-list">
                <?php if ($data['due_leads'] === []): ?><p class="crm-dashboard-empty">No due follow-ups.</p><?php endif; ?>
                <?php foreach ($data['due_leads'] as $lead): ?>
                    <?php $isOverdue = strtotime((string)$lead['followupdate']) < strtotime(date('Y-m-d')); ?>
                    <a href="<?= crm_e(crm_url('operations/leads.php?search=' . urlencode((string)$lead['id']))) ?>">
                        <span class="crm-list-icon <?= $isOverdue ? 'overdue' : 'today' ?>"><i class="fa-solid <?= $isOverdue ? 'fa-triangle-exclamation' : 'fa-phone' ?>"></i></span>
                        <span class="crm-list-copy"><strong><?= crm_e((string)$lead['customer']) ?></strong><small><?= crm_e((string)$lead['owner']) ?> · <?= crm_e((string)$lead['status']) ?></small></span>
                        <span class="crm-list-date <?= $isOverdue ? 'overdue' : '' ?>"><?= crm_date($lead['followupdate']) ?></span>
                    </a>
                <?php endforeach; ?>
            </div>
        </article>

        <article class="card crm-dashboard-panel">
            <div class="crm-panel-head">
                <div><span>Latest Activity</span><h2>Recently Added Leads</h2></div>
                <a href="<?= crm_e(crm_url('operations/leads.php')) ?>">All leads <i class="fa-solid fa-arrow-right"></i></a>
            </div>
            <div class="crm-dashboard-list">
                <?php foreach ($data['latest_leads'] as $lead): ?>
                    <a href="<?= crm_e(crm_url('operations/leads.php?search=' . urlencode((string)$lead['id']))) ?>">
                        <span class="crm-list-icon lead"><i class="fa-solid fa-user-plus"></i></span>
                        <span class="crm-list-copy"><strong><?= crm_e((string)$lead['customer']) ?></strong><small><?= crm_e((string)$lead['owner']) ?> · <?= crm_e((string)$lead['status']) ?></small></span>
                        <span class="crm-list-date"><?= crm_date($lead['date']) ?></span>
                    </a>
                <?php endforeach; ?>
            </div>
        </article>
    </section>

    <section class="crm-dashboard-grid crm-dashboard-grid-bottom">
        <article class="card crm-dashboard-panel">
            <div class="crm-panel-head"><div><span>Quotation Funnel</span><h2>Commercial Overview</h2></div></div>
            <div class="crm-quote-funnel">
                <div><span>Total</span><strong><?= crm_n($data['quotations']['documents']) ?></strong><small><?= crm_money($data['quotations']['total']) ?></small></div>
                <div><span>Approved</span><strong><?= crm_n($data['quotations']['approved']) ?></strong><small><?= crm_pct($data['quotations']['approved'], $data['quotations']['documents']) ?></small></div>
                <div><span>Open</span><strong><?= crm_n($data['quotations']['open']) ?></strong><small>Awaiting decision</small></div>
                <div><span>Cancelled</span><strong><?= crm_n($data['quotations']['cancelled']) ?></strong><small><?= crm_pct($data['quotations']['cancelled'], $data['quotations']['documents']) ?></small></div>
            </div>
        </article>

        <article class="card crm-dashboard-panel">
            <div class="crm-panel-head">
                <div><span>This Month</span><h2>CRM User Performance</h2></div>
                <a href="<?= crm_e(crm_url('reports/user-wise-summary.php')) ?>">Full report <i class="fa-solid fa-arrow-right"></i></a>
            </div>
            <div class="crm-user-performance">
                <?php foreach ($data['top_users'] as $index => $user): ?>
                    <div>
                        <span class="crm-user-rank"><?= (int)$index + 1 ?></span>
                        <span class="crm-user-name"><strong><?= crm_e((string)$user['label']) ?></strong><small><?= crm_n($user['converted']) ?> converted</small></span>
                        <strong><?= crm_n($user['leads']) ?> leads</strong>
                    </div>
                <?php endforeach; ?>
            </div>
        </article>
    </section>
</div>
<?php console_footer(); ?>
