<?php
require_once __DIR__ . '/../../classes/Branding.php';
$companyLogo = Branding::logoUrl();

session_start();
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Branch.php';
require_once __DIR__ . '/../../classes/DeliveryNote.php';

$database     = new Database();
$conn         = $database->getConnection();
$branch       = new Branch($conn);
$auth         = new Auth($conn);
$deliveryNote = new DeliveryNote($conn);

if (!isset($_SESSION['user_id'])) {
    header('Location: ../../login.php');
    exit();
}

/* ── Load data from session or database ── */
if (isset($_SESSION['delivery_note_data'])) {
    $noteData = $_SESSION['delivery_note_data'];
    $noteData['delivery_note_number'] = $noteData['delivery_note_number'] ?? '';
    $noteData['customer_name']        = $noteData['customer_name']        ?? '';
    $noteData['customer_contact']     = $noteData['customer_contact']     ?? '';
    $noteData['notes']                = $noteData['notes']                ?? '';
    $noteData['created_at']           = $noteData['created_at']           ?? date('Y-m-d H:i:s');
    $noteData['created_by']           = null;

    foreach ($noteData['items'] as &$item) {
        if (isset($item['qty'])) {
            $item['quantity'] = $item['qty'];
        }
    }
    unset($item);

    $creatorName = $noteData['created_by_name'] ?? 'Unknown';
    unset($_SESSION['delivery_note_data']);

} else {
    $noteId = isset($_GET['id']) ? (int)$_GET['id'] : null;
    if (!$noteId) {
        header('Location: create_d_note.php?error=' . urlencode('No delivery note found.'));
        exit();
    }

    $noteData = $deliveryNote->getDeliveryNoteById($noteId);
    if (!$noteData) {
        header('Location: create_d_note.php?error=' . urlencode('Delivery note not found.'));
        exit();
    }

    $creatorId   = $noteData['created_by'] ?? null;
    $creatorName = $creatorId ? ($auth->getUserName($creatorId) ?: 'Unknown') : 'Unknown';
}

$formattedDate  = (new DateTime($noteData['created_at'] ?? 'now'))->format('d M Y');

$documentBranch = $branch->getBranchById((int)($noteData['branch_id'] ?? 0));
$co = Branding::documentDetailsForBranch($documentBranch);

/* ── Letterhead variables ── */
$docType      = 'DELIVERY NOTE';
$docNumber    = $noteData['delivery_note_number'];
$docPageTitle = htmlspecialchars(Branding::pageTitle('Delivery Note #' . $docNumber));
$docNewLink   = 'create_d_note.php';
$docNewLabel  = 'New Delivery Note';

require __DIR__ . '/_lh_top.php';
?>

    <!-- ══ DOCUMENT TITLE ══ -->
    <div class="lh-doc-title">
        <div class="lh-doc-type">Delivery Note</div>
        <div class="lh-doc-refs">
            <div class="lh-doc-ref-row">
                <span class="lh-doc-ref-lbl">Note No</span>
                <span class="lh-doc-ref-val"><?php echo htmlspecialchars($noteData['delivery_note_number']); ?></span>
            </div>
            <div class="lh-doc-ref-row">
                <span class="lh-doc-ref-lbl">Date Issued</span>
                <span class="lh-doc-ref-val"><?php echo $formattedDate; ?></span>
            </div>
        </div>
    </div>

    <!-- ══ DELIVER TO ══ -->
    <div class="lh-parties">
        <div class="lh-party lh-pto">
            <div class="lh-plabel">Deliver To</div>
            <div class="lh-pname"><?php echo htmlspecialchars($noteData['customer_name']); ?></div>
            <?php if (!empty($noteData['customer_contact'])): ?>
            <div class="lh-pline">
                <i class="fas fa-phone-alt"></i>
                <span><?php echo htmlspecialchars($noteData['customer_contact']); ?></span>
            </div>
            <?php endif; ?>
        </div>
    </div>


    <!-- ══ ITEMS ══ -->
    <div class="lh-table-wrap">
        <table class="lh-table">
            <thead>
                <tr>
                    <th style="width:34px">#</th>
                    <th>Item / Description</th>
                    <th class="c" style="width:100px">Quantity</th>
                </tr>
            </thead>
            <tbody>
                <?php if (!empty($noteData['items'])): ?>
                    <?php foreach ($noteData['items'] as $i => $item): ?>
                    <tr>
                        <td><span class="lh-rn"><?php echo $i + 1; ?></span></td>
                        <td class="desc"><?php echo htmlspecialchars($item['item_name'] ?? ''); ?></td>
                        <td class="c"><?php echo htmlspecialchars($item['quantity'] ?? 0); ?></td>
                    </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr><td colspan="3" style="text-align:center;color:#a0aec0;padding:20px;">No items found.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <!-- ══ NOTES (no totals for delivery notes) ══ -->
    <div class="lh-bottom" style="grid-template-columns: 1fr;">
        <div class="lh-notes" style="border-right: none;">
            <div class="lh-notes-lbl">Notes</div>
            <div class="lh-notes-txt">
                <?php echo !empty($noteData['notes'])
                    ? nl2br(htmlspecialchars($noteData['notes']))
                    : 'Goods delivered in good condition.'; ?>
            </div>
        </div>
    </div>

    <!-- ══ SIGNATURES ══ -->
    <div class="lh-sig">
        <div class="lh-sig-slot">
            <div class="lh-sig-line"></div>
            <div class="lh-sig-lbl">Delivered By</div>
        </div>
        <div class="lh-sig-slot">
            <div class="lh-sig-line"></div>
            <div class="lh-sig-lbl">Received By</div>
        </div>
    </div>

<?php require __DIR__ . '/_lh_bottom.php'; ?>
