<?php
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/../includes/header.php';

$bolId = $_GET['id'] ?? null;
if (!$bolId) {
    die('Missing BOL ID');
}

/* =========================
   DOCUMENT STATUS
========================= */
$stmt = $pdo->prepare("SELECT status FROM bol_documents WHERE id = ?");
$stmt->execute([$bolId]);
$docStatus = $stmt->fetchColumn();

if (!$docStatus) {
    die('Invalid document');
}

$isLocked = ($docStatus === 'completed');

/* =========================
   TEMPLATE FIELDS
========================= */
$fields = $pdo->query("
    SELECT id, code, label, field_type
    FROM bol_fields
    WHERE template_id = 1
    ORDER BY sort_order
")->fetchAll(PDO::FETCH_ASSOC);

/* =========================
   DOCUMENT VALUES
========================= */
$stmt = $pdo->prepare("
    SELECT field_id, value
    FROM bol_values
    WHERE bol_id = ?
");
$stmt->execute([$bolId]);
$valuesByFieldId = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

/* =========================
   PRESETS (DOCUMENT ONLY)
========================= */
$presets = $pdo->query("
    SELECT id, name, values_json
    FROM bol_value_presets
    ORDER BY name
")->fetchAll(PDO::FETCH_ASSOC);
?>

<h4>Bill of Lading – Document</h4>

<?php if ($isLocked): ?>
    <div class="alert alert-secondary">
        This document is <strong>COMPLETED</strong>. Editing is disabled.
    </div>
<?php endif; ?>

<!-- APPLY PRESET -->
<div class="mb-3">
    <label>Apply Preset</label>
    <select id="applyPreset" class="form-control" <?= $isLocked ? 'disabled' : '' ?>>
        <option value="">— select preset —</option>
        <?php foreach ($presets as $p): ?>
            <option
                value="<?= $p['id'] ?>"
                data-json='<?= htmlspecialchars($p['values_json'], ENT_QUOTES) ?>'>
                <?= htmlspecialchars($p['name']) ?>
            </option>
        <?php endforeach; ?>
    </select>
</div>

<form id="bolForm">

<?php foreach ($fields as $f):
    $val = $valuesByFieldId[$f['id']] ?? '';
    $type = ($f['field_type'] === 'date') ? 'date' : 'text';
?>
    <div class="mb-2">
        <label><?= htmlspecialchars($f['label']) ?></label>
        <input
            type="<?= $type ?>"
            class="form-control bol-field"
            data-field-id="<?= $f['id'] ?>"
            data-code="<?= htmlspecialchars($f['code']) ?>"
            value="<?= htmlspecialchars($val) ?>"
            <?= $isLocked ? 'readonly' : '' ?>>
    </div>
<?php endforeach; ?>

</form>

<hr>

<h5>PDF Preview</h5>
<iframe
    id="pdfPreview"
    src="preview_bol_pdf.php?bol_id=<?= htmlspecialchars($bolId) ?>"
    style="width:100%;height:700px;border:1px solid #ccc;">
</iframe>

<script>
const bolId = <?= json_encode($bolId) ?>;
const isLocked = <?= json_encode($isLocked) ?>;
const preview = document.getElementById('pdfPreview');

/* =========================
   SAVE FIELD
========================= */
function saveField(fieldId, value) {
    return fetch('save_bol_value.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
            bol_id: bolId,
            field_id: fieldId,
            value: value
        })
    });
}

/* =========================
   AUTOSAVE (ONLY IF DRAFT)
========================= */
if (!isLocked) {
    document.querySelectorAll('.bol-field').forEach(el => {
        el.addEventListener('change', () => {
            saveField(el.dataset.fieldId, el.value)
                .then(refreshPreview);
        });
    });
}

/* =========================
   APPLY PRESET
========================= */
document.getElementById('applyPreset')?.addEventListener('change', e => {
    if (!e.target.value || isLocked) return;

    const values = JSON.parse(
        e.target.selectedOptions[0].dataset.json || '{}'
    );

    const promises = [];

    document.querySelectorAll('.bol-field').forEach(el => {
        const code = el.dataset.code;
        if (values[code] !== undefined) {
            el.value = values[code];
            promises.push(saveField(el.dataset.fieldId, values[code]));
        }
    });

    Promise.all(promises).then(refreshPreview);
});

/* =========================
   REFRESH PDF
========================= */
function refreshPreview() {
    preview.src =
        'preview_bol_pdf.php?bol_id=' + bolId + '&t=' + Date.now();
}
</script>

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