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

$bolId = $_GET['id'] ?? null;

if ($bolId) {
    $stmt = $pdo->prepare("SELECT * FROM bol_documents WHERE id = ?");
    $stmt->execute([$bolId]);
    $document = $stmt->fetch();
    if (!$document) {
        die('BOL document not found');
    }
} else {
    // UUID-like (non RFC) ma ok per char(36) se vuoi puoi usare ramsey/uuid.
    $bolId = sprintf(
        '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        random_int(0, 0xffff), random_int(0, 0xffff),
        random_int(0, 0xffff),
        random_int(0, 0x0fff) | 0x4000,
        random_int(0, 0x3fff) | 0x8000,
        random_int(0, 0xffff),
        random_int(0, 0xffff),
        random_int(0, 0xffff)
    );

    $pdo->prepare("
        INSERT INTO bol_documents (id, template_id, status, copies, template_code, version_number)
        VALUES (?, 1, 'draft', 1, 'bill_of_lading', 1)
    ")->execute([$bolId]);

    $document = [
        'id' => $bolId,
        'template_id' => 1,
        'copies' => 1,
        'status' => 'draft'
    ];
}

/* LOAD FIELDS */
$fields = $pdo->query("
    SELECT *
    FROM bol_fields
    WHERE template_id = 1
    ORDER BY sort_order
")->fetchAll();

/* LOAD VALUES */
$values = [];
$stmt = $pdo->prepare("SELECT field_id, value FROM bol_values WHERE bol_id = ?");
$stmt->execute([$bolId]);
foreach ($stmt as $v) {
    $values[(int)$v['field_id']] = $v['value'];
}

/* LOAD PRESETS LIST (for dropdowns) */
$presets = $pdo->query("
    SELECT id, name
    FROM bol_presets
    WHERE template_id = 1
    ORDER BY name
")->fetchAll();
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <h4 class="mb-0">Edit Bill of Lading</h4>
    <div class="d-flex gap-2">
        <a href="/smproduce/pages/bill_of_lading.php" class="btn btn-outline-secondary btn-sm">Back</a>
        <a href="/smproduce/pages/generate_bol_pdf.php?id=<?= urlencode($bolId) ?>"
           target="_blank"
           class="btn btn-primary btn-sm">
            Generate PDF
        </a>
    </div>
</div>

<form method="post" action="/smproduce/pages/save_bol_document.php" class="bg-white border p-3 rounded">
    <input type="hidden" name="bol_id" value="<?= htmlspecialchars($bolId) ?>">

    <div class="row">
        <?php foreach ($fields as $f): ?>
            <?php
                $fieldId = (int)$f['id'];
                $val = $values[$fieldId] ?? '';
                $type = $f['field_type'];
            ?>
            <div class="col-md-6 mb-3">
                <label class="form-label"><?= htmlspecialchars($f['label']) ?></label>

                <?php if ($type === 'date'): ?>
                    <input type="date"
                           class="form-control"
                           name="fields[<?= $fieldId ?>]"
                           value="<?= htmlspecialchars($val) ?>">

                <?php elseif ($type === 'number'): ?>
                    <input type="number"
                           class="form-control"
                           name="fields[<?= $fieldId ?>]"
                           value="<?= htmlspecialchars($val) ?>">

                <?php elseif ($type === 'checkbox'): ?>
                    <div class="form-check">
                        <input type="checkbox"
                               class="form-check-input"
                               name="fields[<?= $fieldId ?>]"
                               value="1" <?= ($val === '1' || $val === 1) ? 'checked' : '' ?>>
                        <label class="form-check-label">Checked</label>
                    </div>

                <?php elseif ($type === 'preset'): ?>
                    <select class="form-select"
                            name="fields[<?= $fieldId ?>]">
                        <option value="">— Select preset —</option>
                        <?php foreach ($presets as $p): ?>
                            <option value="<?= (int)$p['id'] ?>"
                                <?= ((string)$val === (string)$p['id']) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($p['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <div class="form-text">
                        Preset will auto-fill multiple fields in the PDF.
                    </div>

                <?php else: ?>
                    <input type="text"
                           class="form-control"
                           name="fields[<?= $fieldId ?>]"
                           value="<?= htmlspecialchars($val) ?>">
                <?php endif; ?>
            </div>
        <?php endforeach; ?>
    </div>

    <div class="row">
        <div class="col-md-3 mb-3">
            <label class="form-label">Copies</label>
            <input type="number" class="form-control" name="copies"
                   value="<?= (int)($document['copies'] ?? 1) ?>" min="1" max="50">
        </div>
    </div>

    <button class="btn btn-primary">Save</button>
</form>

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