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

$quotationId = (int)($_GET['quotation_id'] ?? 0);

$stmt = $pdo->prepare("SELECT q.*, c.customer_name, c.email, c.phone FROM quotations q
                        JOIN sale_vendors c ON c.id=q.customer_id WHERE q.id=?");
$stmt->execute([$quotationId]);
$quotation = $stmt->fetch();

if (!$quotation) {
    setFlash('danger', 'Quotation not found.');
    header('Location: ../quotation/quotations.php'); exit;
}
if ($quotation['status'] !== 'accepted') {
    setFlash('danger', 'Only accepted quotations can have a delivery note created.');
    header('Location: ../quotation/quotation_view.php?id=' . $quotationId); exit;
}

// Already has a delivery note?
$check = $pdo->prepare("SELECT id FROM delivery_notes WHERE quotation_id=?");
$check->execute([$quotationId]);
if ($check->fetch()) {
    setFlash('info', 'Delivery note already exists for this quotation.');
    header('Location: ../quotation/quotation_view.php?id=' . $quotationId); exit;
}

$stmt = $pdo->prepare("SELECT qi.*, i.item_name, i.item_code, i.unit,
                        COALESCE(sl.available_qty,0) available_qty
                        FROM quotation_items qi
                        JOIN items i ON i.id=qi.item_id
                        LEFT JOIN stock_ledger sl ON sl.item_id = qi.item_id
                        WHERE qi.quotation_id=?");
$stmt->execute([$quotationId]);
$lineItems = $stmt->fetchAll();

// Handle creation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'create') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        setFlash('danger', 'Invalid request token.');
        header("Location: delivery_create.php?quotation_id=$quotationId"); exit;
    }

    // Validate stock availability
    foreach ($lineItems as $li) {
        if ($li['available_qty'] < $li['qty']) {
            setFlash('danger', "Insufficient stock for {$li['item_name']}. Available: {$li['available_qty']}, Required: {$li['qty']}");
            header("Location: delivery_create.php?quotation_id=$quotationId"); exit;
        }
    }

    try {
        $pdo->beginTransaction();

        $deliveryNo = generateDocNumber('delivery_notes', 'delivery_no', getSetting('delivery_prefix','DN'));
        $deliveryDate = $_POST['delivery_date'];
        $notes = trim($_POST['notes']);

        $stmt = $pdo->prepare("INSERT INTO delivery_notes (delivery_no, quotation_id, customer_id, delivery_date, notes, created_by)
                                VALUES (?,?,?,?,?,?)");
        $stmt->execute([$deliveryNo, $quotationId, $quotation['customer_id'], $deliveryDate, $notes, currentUserId()]);
        $deliveryNoteId = $pdo->lastInsertId();

        foreach ($lineItems as $li) {
            $pdo->prepare("INSERT INTO delivery_note_items (delivery_note_id, item_id, qty) VALUES (?,?,?)")
                ->execute([$deliveryNoteId, $li['item_id'], $li['qty']]);

            // FREEZE STOCK: move from available -> freeze
            freezeStock($li['item_id'], $li['qty'], $deliveryNoteId, currentUserId());
        }

        $pdo->commit();
        setFlash('success', "Delivery note $deliveryNo created. Stock moved to Freeze. You can now email it to the customer.");
        header("Location: delivery_view.php?id=$deliveryNoteId");
        exit;

    } catch (Exception $e) {
        $pdo->rollBack();
        setFlash('danger', 'Error: ' . $e->getMessage());
        header("Location: delivery_create.php?quotation_id=$quotationId"); exit;
    }
}

$csrf = generateCSRFToken();

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

<div class="page-header">
    <div>
        <div class="eyebrow">Delivery</div>
        <h2 class="mb-0">Create Delivery Note</h2>
    </div>
    <a href="../quotation/quotation_view.php?id=<?= $quotationId ?>" class="btn"><?= icon('arrow-left') ?> Back to Quotation</a>
</div>

<div class="card" style="max-width:800px; margin:0 auto;">
    <div class="card-title">For Quotation: <span class="mono"><?= sanitize($quotation['quotation_no']) ?></span></div>
    <div class="form-grid" style="margin-bottom:16px;">
        <div>
            <div class="text-sm text-muted">Customer</div>
            <strong><?= sanitize($quotation['customer_name']) ?></strong>
        </div>
        <div>
            <div class="text-sm text-muted">Email / Phone</div>
            <div><?= sanitize($quotation['email']) ?> / <?= sanitize($quotation['phone']) ?></div>
        </div>
        <div>
            <div class="text-sm text-muted">Quotation Amount</div>
            <strong class="mono"><?= formatMoney($quotation['grand_total']) ?></strong>
        </div>
    </div>

    <div class="alert alert-info"><?= icon('info-circle') ?> Creating this delivery note will move the listed quantities from <strong>Available</strong> stock to <strong>Freeze (Reserved)</strong> stock.</div>

    <div class="table-wrap">
        <table>
            <thead><tr><th>Item</th><th class="text-right">Qty to Deliver</th><th class="text-right">Currently Available</th><th>Stock Check</th></tr></thead>
            <tbody>
            <?php $insufficient = false; foreach ($lineItems as $li): $ok = $li['available_qty'] >= $li['qty']; if (!$ok) $insufficient = true; ?>
            <tr>
                <td><?= sanitize($li['item_name']) ?> <span class="text-faint mono">(<?= sanitize($li['item_code']) ?>)</span></td>
                <td class="num"><?= $li['qty'] ?></td>
                <td class="num"><?= $li['available_qty'] ?></td>
                <td><?= $ok ? '<span class="badge badge-success">OK</span>' : '<span class="badge badge-danger">Insufficient</span>' ?></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <?php if ($insufficient): ?>
    <div class="alert alert-danger mt-16"><?= icon('alert-triangle') ?> Cannot proceed - insufficient stock for one or more items. Please make a purchase entry to add stock first.</div>
    <?php else: ?>
    <form method="POST" class="mt-16">
        <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
        <input type="hidden" name="action" value="create">
        <div class="form-grid">
            <div class="form-group">
                <label>Delivery Date <span class="req">*</span></label>
                <input type="date" name="delivery_date" value="<?= date('Y-m-d') ?>" required>
            </div>
        </div>
        <div class="form-group full">
            <label>Notes</label>
            <textarea name="notes" rows="2" placeholder="Delivery instructions, courier details, etc."></textarea>
        </div>
        <div class="flex-end gap-8 mt-16">
            <button type="submit" class="btn btn-primary"><?= icon('truck') ?> Create Delivery Note & Reserve Stock</button>
        </div>
    </form>
    <?php endif; ?>
</div>

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