<?php
require_once __DIR__ . '/../../includes/functions.php';
requireLogin();

$stmt = $pdo->query("SELECT d.*, c.customer_name, q.quotation_no, q.grand_total
                      FROM delivery_notes d
                      JOIN sale_vendors c ON c.id=d.customer_id
                      JOIN quotations q ON q.id=d.quotation_id
                      ORDER BY d.id DESC");
$deliveries = $stmt->fetchAll();

// All logic/redirects above are done - safe to render layout now
$pageTitle = 'Delivery Notes';
require_once __DIR__ . '/../../includes/header.php';
?>

<div class="page-header">
    <div>
        <div class="eyebrow">Sales Flow</div>
        <h2 class="mb-0">Delivery Notes</h2>
    </div>
</div>

<div class="card">
    <?php if ($deliveries): ?>
    <div class="table-wrap">
        <table>
            <thead>
                <tr><th>Delivery #</th><th>Quotation #</th><th>Customer</th><th>Delivery Date</th>
                    <th class="text-right">Amount</th><th>Status</th><th>Email</th><th>Actions</th></tr>
            </thead>
            <tbody>
            <?php foreach ($deliveries as $d): ?>
            <tr>
                <td class="mono"><?= sanitize($d['delivery_no']) ?></td>
                <td><a href="../quotation/quotation_view.php?id=<?= $d['quotation_id'] ?>" class="mono"><?= sanitize($d['quotation_no']) ?></a></td>
                <td><?= sanitize($d['customer_name']) ?></td>
                <td><?= formatDate($d['delivery_date']) ?></td>
                <td class="num"><?= formatMoney($d['grand_total']) ?></td>
                <td><span class="badge badge-<?= $d['status']=='delivered'?'success':'warning' ?>"><?= $d['status'] ?></span></td>
                <td><?php if ($d['email_sent']): ?><span class="badge badge-success"><?= icon('mail-forward') ?> Sent</span><?php else: ?><span class="badge badge-muted">Not sent</span><?php endif; ?></td>
                <td>
                    <a href="delivery_view.php?id=<?= $d['id'] ?>" class="btn btn-icon btn-sm" title="View"><?= icon('eye') ?></a>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
    <div class="empty-state"><?= icon('truck') ?>No delivery notes yet. They are created from accepted quotations.</div>
    <?php endif; ?>
</div>

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