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

$bolId  = $_POST['bol_id'];
$fields = $_POST['fields'] ?? [];
$copies = (int)($_POST['copies'] ?? 1);

/* save copies */
$pdo->prepare("
    UPDATE bol_documents SET copies = ? WHERE id = ?
")->execute([$copies, $bolId]);

/* normalize checkboxes */
$meta = $pdo->query("
    SELECT id, field_type FROM bol_fields WHERE template_id = 1
")->fetchAll();

foreach ($meta as $m) {
    if ($m['field_type'] === 'checkbox' && !isset($fields[$m['id']])) {
        $fields[$m['id']] = '0';
    }
}

/* upsert values */
$stmt = $pdo->prepare("
    INSERT INTO bol_values (bol_id, field_id, value)
    VALUES (?, ?, ?)
    ON DUPLICATE KEY UPDATE value = VALUES(value)
");

foreach ($fields as $fid => $val) {
    $stmt->execute([$bolId, (int)$fid, (string)$val]);
}

header("Location: /smproduce/pages/bol_document_edit.php?id=" . urlencode($bolId));
exit;
