<?php
$pageTitle = 'Dashboard';
require_once __DIR__ . '/../app/includes/header.php';

$role = current_user()['role'] ?? 'visitor';
$userId = (int)current_user()['id'];

if ($role === 'admin') {
    $stats = [
        'total' => (int)db()->query('SELECT COUNT(*) FROM quotations')->fetchColumn(),
        'pending' => (int)db()->query("SELECT COUNT(*) FROM quotations WHERE status IN ('draft','sent')")->fetchColumn(),
        'sales' => (float)db()->query("SELECT COALESCE(SUM(grand_total),0) FROM quotations WHERE MONTH(created_at)=MONTH(CURRENT_DATE()) AND YEAR(created_at)=YEAR(CURRENT_DATE()) AND status IN ('final','sent','accepted')")->fetchColumn(),
        'customers' => (int)db()->query('SELECT COUNT(*) FROM customers')->fetchColumn(),
    ];
    $recent = db()->query("SELECT q.*, c.customer_name FROM quotations q JOIN customers c ON c.id=q.customer_id ORDER BY q.id DESC LIMIT 8")->fetchAll();
    
    // User-wise performance metrics for Admin
    $userStats = db()->query("
        SELECT u.name, u.role, 
               COUNT(q.id) as total_quotes,
               SUM(CASE WHEN q.status IN ('final','sent','accepted') THEN q.grand_total ELSE 0 END) as total_sales
        FROM users u 
        LEFT JOIN quotations q ON u.id = q.created_by
        WHERE u.role IN ('engineer', 'sales', 'visitor')
        GROUP BY u.id
        ORDER BY total_sales DESC
    ")->fetchAll();

} else {
    // Engineer, Sales, Visitor only see their own stats
    $stats = [
        'total' => (int)db()->query("SELECT COUNT(*) FROM quotations WHERE created_by=$userId")->fetchColumn(),
        'drafts' => (int)db()->query("SELECT COUNT(*) FROM quotations WHERE created_by=$userId AND status='draft'")->fetchColumn(),
        'sales' => (float)db()->query("SELECT COALESCE(SUM(grand_total),0) FROM quotations WHERE created_by=$userId AND MONTH(created_at)=MONTH(CURRENT_DATE()) AND YEAR(created_at)=YEAR(CURRENT_DATE()) AND status IN ('final','sent','accepted')")->fetchColumn(),
    ];
    $recent = db()->query("SELECT q.*, c.customer_name FROM quotations q JOIN customers c ON c.id=q.customer_id WHERE q.created_by=$userId ORDER BY q.id DESC LIMIT 8")->fetchAll();
}
?>
<div class="page-head">
    <div><h1>Dashboard</h1><p>Quotation performance and recent activity.</p></div>
    <a class="btn btn-primary" href="<?= APP_BASE ?>/quotations/create.php"><i class="bi bi-plus-lg me-1"></i>New Quotation</a>
</div>
<div class="row g-3 mb-4">
    <?php if ($role === 'admin'): ?>
        <div class="col-md-3"><div class="metric-card"><i class="bi bi-files"></i><span>Total Quotations</span><strong><?= $stats['total'] ?></strong></div></div>
        <div class="col-md-3"><div class="metric-card"><i class="bi bi-hourglass-split"></i><span>Pending Follow-up</span><strong><?= $stats['pending'] ?></strong></div></div>
        <div class="col-md-3"><div class="metric-card"><i class="bi bi-cash-stack"></i><span>This Month Sales</span><strong><?= money($stats['sales']) ?></strong></div></div>
        <div class="col-md-3"><div class="metric-card"><i class="bi bi-person-plus"></i><span>Total Customers</span><strong><?= $stats['customers'] ?></strong></div></div>
    <?php else: ?>
        <div class="col-md-4"><div class="metric-card"><i class="bi bi-files"></i><span>My Quotations</span><strong><?= $stats['total'] ?></strong></div></div>
        <div class="col-md-4"><div class="metric-card"><i class="bi bi-file-earmark-text"></i><span>My Drafts</span><strong><?= $stats['drafts'] ?></strong></div></div>
        <div class="col-md-4"><div class="metric-card"><i class="bi bi-cash-stack"></i><span>My Monthly Sales</span><strong><?= money($stats['sales']) ?></strong></div></div>
    <?php endif; ?>
</div>

<?php if ($role === 'admin' && !empty($userStats)): ?>
<div class="card app-card mb-4">
    <div class="card-header bg-white"><strong>User Performance Metrics</strong></div>
    <div class="table-responsive">
        <table class="table align-middle mb-0">
            <thead><tr><th>User</th><th>Role</th><th>Total Quotations</th><th>Total Sales Generated</th></tr></thead>
            <tbody>
            <?php foreach ($userStats as $u): ?>
                <tr>
                    <td><?= e($u['name']) ?></td>
                    <td><span class="badge bg-secondary"><?= e(ucfirst($u['role'])) ?></span></td>
                    <td><?= (int)$u['total_quotes'] ?></td>
                    <td class="text-success fw-bold"><?= money((float)$u['total_sales']) ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<div class="card app-card">
    <div class="card-header bg-white"><strong>Recent Quotations</strong></div>
    <div class="table-responsive">
        <table class="table align-middle mb-0">
            <thead><tr><th>Quotation No</th><th>Customer</th><th>System Type</th><th>Total</th><th>Status</th><th>Date</th><th>Action</th></tr></thead>
            <tbody>
            <?php foreach ($recent as $row): ?>
                <tr>
                    <td><?= e($row['quotation_no']) ?></td><td><?= e($row['customer_name']) ?></td><td><?= e($row['system_type']) ?></td>
                    <td><?= money((float)$row['grand_total']) ?></td><td><?= status_badge($row['status']) ?></td><td><?= e(date('Y-m-d', strtotime($row['created_at']))) ?></td>
                    <td><a class="btn btn-sm btn-outline-primary" href="<?= APP_BASE ?>/quotations/view.php?id=<?= (int)$row['id'] ?>">View</a></td>
                </tr>
            <?php endforeach; ?>
            <?php if (!$recent): ?><tr><td colspan="7" class="text-center text-muted py-4">No quotations yet.</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
<?php require_once __DIR__ . '/../app/includes/footer.php'; ?>
