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

// Quick stats
$totalItems = $pdo->query("SELECT COUNT(*) c FROM items WHERE status=1")->fetch()['c'];
$lowStock = $pdo->query("SELECT COUNT(*) c FROM stock_ledger sl JOIN items i ON i.id=sl.item_id WHERE sl.available_qty <= i.min_stock_level")->fetch()['c'];

$pendingQuotes = $pdo->query("SELECT COUNT(*) c FROM quotations WHERE status IN ('draft','sent')")->fetch()['c'];
$pendingDeliveries = $pdo->query("SELECT COUNT(*) c FROM delivery_notes WHERE status='pending'")->fetch()['c'];
$pendingInvoices = $pdo->query("SELECT COUNT(*) c, COALESCE(SUM(grand_total - paid_amount),0) amt FROM invoices WHERE payment_status != 'paid'")->fetch();

$thisMonthSales = $pdo->query("SELECT COALESCE(SUM(grand_total),0) t FROM invoices WHERE MONTH(invoice_date)=MONTH(CURDATE()) AND YEAR(invoice_date)=YEAR(CURDATE())")->fetch()['t'];
$thisMonthPurchases = $pdo->query("SELECT COALESCE(SUM(grand_total),0) t FROM purchases WHERE MONTH(purchase_date)=MONTH(CURDATE()) AND YEAR(purchase_date)=YEAR(CURDATE())")->fetch()['t'];

$cashIn = $pdo->query("SELECT COALESCE(SUM(amount),0) t FROM payments WHERE payment_type='inflow' AND MONTH(payment_date)=MONTH(CURDATE()) AND YEAR(payment_date)=YEAR(CURDATE())")->fetch()['t'];
$cashOut = $pdo->query("SELECT COALESCE(SUM(amount),0) t FROM payments WHERE payment_type='outflow' AND MONTH(payment_date)=MONTH(CURDATE()) AND YEAR(payment_date)=YEAR(CURDATE())")->fetch()['t'];

// Recent activity
$recentQuotes = $pdo->query("SELECT q.*, c.customer_name FROM quotations q JOIN sale_vendors c ON c.id=q.customer_id ORDER BY q.id DESC LIMIT 5")->fetchAll();
$recentInvoices = $pdo->query("SELECT i.*, c.customer_name FROM invoices i JOIN sale_vendors c ON c.id=i.customer_id ORDER BY i.id DESC LIMIT 5")->fetchAll();
?>

<div class="page-header">
    <div>
        <div class="eyebrow">Overview · <?= date('F Y') ?></div>
        <h2 class="mb-0">Welcome back, <?= sanitize(currentUserName()) ?></h2>
    </div>
</div>

<div class="stat-grid">
    <div class="stat-card accent">
        <div class="stat-label">Sales this month</div>
        <div class="stat-value mono"><?= formatMoney($thisMonthSales) ?></div>
        <div class="stat-sub">Tax invoices generated</div>
    </div>
    <div class="stat-card info">
        <div class="stat-label">Purchases this month</div>
        <div class="stat-value mono"><?= formatMoney($thisMonthPurchases) ?></div>
        <div class="stat-sub">From all vendors</div>
    </div>
    <div class="stat-card success">
        <div class="stat-label">Cash inflow (month)</div>
        <div class="stat-value mono"><?= formatMoney($cashIn) ?></div>
        <div class="stat-sub">Received from customers</div>
    </div>
    <div class="stat-card danger">
        <div class="stat-label">Cash outflow (month)</div>
        <div class="stat-value mono"><?= formatMoney($cashOut) ?></div>
        <div class="stat-sub">Paid to vendors</div>
    </div>
</div>

<div class="stat-grid">
    <div class="stat-card">
        <div class="stat-label">Active items</div>
        <div class="stat-value"><?= $totalItems ?></div>
    </div>
    <div class="stat-card <?= $lowStock>0?'danger':'' ?>">
        <div class="stat-label">Low stock alerts</div>
        <div class="stat-value"><?= $lowStock ?></div>
        <?php if ($lowStock>0): ?><div class="stat-sub"><a href="modules/stock/stock_view.php">View items →</a></div><?php endif; ?>
    </div>
    <div class="stat-card">
        <div class="stat-label">Pending quotations</div>
        <div class="stat-value"><?= $pendingQuotes ?></div>
        <div class="stat-sub"><a href="modules/quotation/quotations.php">View all →</a></div>
    </div>
    <div class="stat-card">
        <div class="stat-label">Pending deliveries</div>
        <div class="stat-value"><?= $pendingDeliveries ?></div>
        <div class="stat-sub"><a href="modules/delivery/delivery_notes.php">View all →</a></div>
    </div>
    <div class="stat-card <?= $pendingInvoices['c']>0?'danger':'' ?>">
        <div class="stat-label">Outstanding receivables</div>
        <div class="stat-value mono" style="font-size:20px"><?= formatMoney($pendingInvoices['amt']) ?></div>
        <div class="stat-sub"><?= $pendingInvoices['c'] ?> unpaid invoice(s)</div>
    </div>
</div>

<div class="form-grid">
    <div class="card mb-0">
        <div class="card-title">
            Recent quotations
            <a href="modules/quotation/quotations.php" class="btn btn-sm">View all</a>
        </div>
        <?php if ($recentQuotes): ?>
        <div class="table-wrap">
            <table>
                <thead><tr><th>Quotation #</th><th>Customer</th><th>Date</th><th class="text-right">Amount</th><th>Status</th></tr></thead>
                <tbody>
                <?php foreach ($recentQuotes as $q): ?>
                <tr>
                    <td><a href="modules/quotation/quotation_view.php?id=<?= $q['id'] ?>"><?= sanitize($q['quotation_no']) ?></a></td>
                    <td><?= sanitize($q['customer_name']) ?></td>
                    <td><?= formatDate($q['quotation_date']) ?></td>
                    <td class="num"><?= formatMoney($q['grand_total']) ?></td>
                    <td><span class="badge badge-<?= $q['status']=='accepted'?'success':($q['status']=='rejected'?'danger':'info') ?>"><?= $q['status'] ?></span></td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php else: ?>
        <div class="empty-state"><?= icon('file-description') ?>No quotations yet</div>
        <?php endif; ?>
    </div>

    <div class="card mb-0">
        <div class="card-title">
            Recent invoices
            <a href="modules/invoice/invoices.php" class="btn btn-sm">View all</a>
        </div>
        <?php if ($recentInvoices): ?>
        <div class="table-wrap">
            <table>
                <thead><tr><th>Invoice #</th><th>Customer</th><th>Date</th><th class="text-right">Amount</th><th>Payment</th></tr></thead>
                <tbody>
                <?php foreach ($recentInvoices as $inv): ?>
                <tr>
                    <td><a href="modules/invoice/invoice_view.php?id=<?= $inv['id'] ?>"><?= sanitize($inv['invoice_no']) ?></a></td>
                    <td><?= sanitize($inv['customer_name']) ?></td>
                    <td><?= formatDate($inv['invoice_date']) ?></td>
                    <td class="num"><?= formatMoney($inv['grand_total']) ?></td>
                    <td><span class="badge badge-<?= $inv['payment_status']=='paid'?'success':($inv['payment_status']=='partial'?'warning':'danger') ?>"><?= $inv['payment_status'] ?></span></td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php else: ?>
        <div class="empty-state"><?= icon('receipt') ?>No invoices yet</div>
        <?php endif; ?>
    </div>
</div>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
