<?php
require_once __DIR__ . '/../../vendor/autoload.php';
include '../../includes/header.php';

if (!$auth->isSuperAdmin($_SESSION['user_id']) &&
    !$auth->isWarehousePersonnel($_SESSION['user_id']) &&
    !$auth->isBranchManager($_SESSION['user_id']) &&
    !$auth->isAssistant($_SESSION['user_id'])) {
    header('Location: ../../unauthorized.php');
    exit;
}

$canViewAllBranches = $auth->isSuperAdmin($_SESSION['user_id']) || $auth->isWarehousePersonnel($_SESSION['user_id']);
$userBranchId = $auth->getUserBranch($_SESSION['user_id']);
$request = array_merge($_GET, $_POST);

$validSources = ['branch_stock', 'transfers', 'custom'];
$source = $request['source'] ?? 'branch_stock';
if (!in_array($source, $validSources, true)) {
    $source = 'branch_stock';
}

$selectedBranch = $request['branch_id'] ?? ($canViewAllBranches ? 'all' : (string)$userBranchId);
$selectedShipment = $request['shipment_id'] ?? 'all';
$search = trim($request['search'] ?? '');
$customCodes = trim($request['custom_codes'] ?? '');
$regenerate = isset($request['regenerate']) && $request['regenerate'] === '1';
$barcodeType = 'C128';

if (!$canViewAllBranches) {
    $selectedBranch = (string)$userBranchId;
}

$branchesSql = $canViewAllBranches
    ? "SELECT branch_id, branch_name FROM branches ORDER BY branch_name"
    : "SELECT branch_id, branch_name FROM branches WHERE branch_id = :branch_id ORDER BY branch_name";
$branchesStmt = $conn->prepare($branchesSql);
if (!$canViewAllBranches) {
    $branchesStmt->bindValue(':branch_id', $userBranchId, PDO::PARAM_INT);
}
$branchesStmt->execute();
$branches = $branchesStmt->fetchAll(PDO::FETCH_ASSOC);

$transfersSql = "SELECT s.shipment_id,
                        s.shipment_date,
                        s.status,
                        b_from.branch_name AS from_branch_name,
                        b_to.branch_name AS to_branch_name
                 FROM shipments s
                 LEFT JOIN branches b_from ON s.from_branch_id = b_from.branch_id
                 LEFT JOIN branches b_to ON s.to_branch_id = b_to.branch_id";
$transferParams = [];
if (!$canViewAllBranches) {
    $transfersSql .= " WHERE s.from_branch_id = :transfer_branch_id OR s.to_branch_id = :transfer_branch_id";
    $transferParams[':transfer_branch_id'] = (int)$userBranchId;
}
$transfersSql .= " ORDER BY s.shipment_date DESC LIMIT 100";
$transfersStmt = $conn->prepare($transfersSql);
foreach ($transferParams as $key => $value) {
    $transfersStmt->bindValue($key, $value, PDO::PARAM_INT);
}
$transfersStmt->execute();
$transfers = $transfersStmt->fetchAll(PDO::FETCH_ASSOC);

function barcodeRelativePathExists($relativePath) {
    if (empty($relativePath)) {
        return false;
    }

    $normalized = ltrim($relativePath, '/');
    return is_file(__DIR__ . '/../../' . $normalized);
}

function generateBarcodeForItem(PDO $conn, array $item, $barcodeType = 'C128') {
    $code = trim($item['unique_code'] ?? '');
    if ($code === '') {
        return '';
    }

    $barcodeDir = __DIR__ . '/../../assets/barcodes/';
    if (!is_dir($barcodeDir)) {
        mkdir($barcodeDir, 0755, true);
    }

    $safeCode = preg_replace('/[^a-zA-Z0-9_-]/', '_', $code);
    $fileName = $safeCode . '_' . substr(md5($code), 0, 10) . '.svg';
    $fullPath = $barcodeDir . $fileName;
    $relativePath = 'assets/barcodes/' . $fileName;

    try {
        $barcode = new TCPDFBarcode($code, $barcodeType);
        $svg = $barcode->getBarcodeSVGcode(1.5, 30, 'black');
        if (file_put_contents($fullPath, $svg) === false) {
            return '';
        }

        if (!empty($item['item_id'])) {
            $updateSql = "UPDATE items
                          SET barcode_type = :barcode_type,
                              barcode_data = :barcode_data,
                              barcode_image_path = :barcode_image_path
                          WHERE item_id = :item_id";
            $updateStmt = $conn->prepare($updateSql);
            $updateStmt->bindValue(':barcode_type', $barcodeType, PDO::PARAM_STR);
            $updateStmt->bindValue(':barcode_data', $code, PDO::PARAM_STR);
            $updateStmt->bindValue(':barcode_image_path', $relativePath, PDO::PARAM_STR);
            $updateStmt->bindValue(':item_id', (int)$item['item_id'], PDO::PARAM_INT);
            $updateStmt->execute();
        }

        return $relativePath;
    } catch (Exception $e) {
        error_log('Barcode label generation failed for item ' . ($item['item_id'] ?? 'custom') . ': ' . $e->getMessage());
        return '';
    }
}

function labelImagePath($relativePath) {
    if (empty($relativePath)) {
        return '';
    }

    $normalized = ltrim($relativePath, '/');
    $fullPath = __DIR__ . '/../../' . $normalized;
    if (!is_file($fullPath)) {
        return '';
    }

    return '../../' . $normalized;
}

$items = [];
$sourceNote = 'branch stock';

if ($source === 'branch_stock') {
    $itemsSql = "SELECT i.item_id,
                        i.item_name,
                        i.category,
                        i.unique_code,
                        i.barcode_type,
                        i.barcode_data,
                        i.barcode_image_path,
                        i.unit_price,
                        i.current_location_id,
                        b.branch_name,
                        NULL AS shipment_id
                 FROM items i
                 LEFT JOIN branches b ON i.current_location_id = b.branch_id
                 WHERE i.current_location_id IS NOT NULL
                 AND i.shelf_status = 'on_shelf'
                 AND i.unique_code IS NOT NULL
                 AND i.unique_code != ''
                 AND i.item_id NOT IN (SELECT item_id FROM sold_items WHERE transaction_id LIKE '%_VERIFIED_%')";

    $params = [];
    if ($selectedBranch !== 'all') {
        $itemsSql .= " AND i.current_location_id = :branch_id";
        $params[':branch_id'] = (int)$selectedBranch;
    }

    if ($search !== '') {
        $itemsSql .= " AND (i.item_name LIKE :search OR i.item_details LIKE :search OR i.unique_code LIKE :search OR i.barcode_data LIKE :search)";
        $params[':search'] = '%' . $search . '%';
    }

    $itemsSql .= " ORDER BY b.branch_name, i.item_name, i.unique_code LIMIT 500";
    $itemsStmt = $conn->prepare($itemsSql);
    foreach ($params as $key => $value) {
        $itemsStmt->bindValue($key, $value, is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR);
    }
    $itemsStmt->execute();
    $items = $itemsStmt->fetchAll(PDO::FETCH_ASSOC);
} elseif ($source === 'transfers') {
    $sourceNote = 'transfers';
    $itemsSql = "SELECT i.item_id,
                        i.item_name,
                        i.category,
                        i.unique_code,
                        i.barcode_type,
                        i.barcode_data,
                        i.barcode_image_path,
                        i.unit_price,
                        i.current_location_id,
                        CONCAT('Transfer #', s.shipment_id, ' - ', COALESCE(b_from.branch_name, 'Warehouse'), ' to ', COALESCE(b_to.branch_name, 'Unknown branch')) AS branch_name,
                        s.shipment_id
                 FROM shipment_items si
                 INNER JOIN shipments s ON si.shipment_id = s.shipment_id
                 INNER JOIN items i ON si.item_id = i.item_id
                 LEFT JOIN branches b_from ON s.from_branch_id = b_from.branch_id
                 LEFT JOIN branches b_to ON s.to_branch_id = b_to.branch_id
                 WHERE i.unique_code IS NOT NULL
                 AND i.unique_code != ''";

    $params = [];
    if (!$canViewAllBranches) {
        $itemsSql .= " AND (s.from_branch_id = :user_branch_id OR s.to_branch_id = :user_branch_id)";
        $params[':user_branch_id'] = (int)$userBranchId;
    }

    if ($selectedShipment !== 'all' && is_numeric($selectedShipment)) {
        $itemsSql .= " AND s.shipment_id = :shipment_id";
        $params[':shipment_id'] = (int)$selectedShipment;
    }

    if ($search !== '') {
        $itemsSql .= " AND (i.item_name LIKE :search OR i.item_details LIKE :search OR i.unique_code LIKE :search OR i.barcode_data LIKE :search)";
        $params[':search'] = '%' . $search . '%';
    }

    $itemsSql .= " ORDER BY s.shipment_date DESC, i.item_name, i.unique_code LIMIT 500";
    $itemsStmt = $conn->prepare($itemsSql);
    foreach ($params as $key => $value) {
        $itemsStmt->bindValue($key, $value, is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR);
    }
    $itemsStmt->execute();
    $items = $itemsStmt->fetchAll(PDO::FETCH_ASSOC);
} else {
    $sourceNote = 'custom codes';
    $rawCodes = preg_split('/[\r\n,;]+/', $customCodes);
    $seenCodes = [];

    foreach ($rawCodes as $rawCode) {
        $code = trim($rawCode);
        if ($code === '' || isset($seenCodes[$code])) {
            continue;
        }

        if ($search !== '' && stripos($code, $search) === false) {
            continue;
        }

        $seenCodes[$code] = true;
        $items[] = [
            'item_id' => null,
            'item_name' => 'Custom Code',
            'item_details' => '',
            'category' => 'Custom',
            'unique_code' => $code,
            'barcode_type' => $barcodeType,
            'barcode_data' => $code,
            'barcode_image_path' => '',
            'unit_price' => null,
            'current_location_id' => null,
            'branch_name' => 'Custom label',
            'shipment_id' => null,
        ];
    }
}

$generatedCount = 0;
foreach ($items as &$item) {
    $barcodeDoesNotMatchUniqueCode = trim($item['barcode_data'] ?? '') !== trim($item['unique_code'] ?? '');
    $barcodeTypeDoesNotMatch = strtoupper(trim($item['barcode_type'] ?? '')) !== $barcodeType;
    if ($regenerate || $barcodeDoesNotMatchUniqueCode || $barcodeTypeDoesNotMatch || !barcodeRelativePathExists($item['barcode_image_path'] ?? '')) {
        $generatedPath = generateBarcodeForItem($conn, $item, $barcodeType);
        if ($generatedPath !== '') {
            $item['barcode_image_path'] = $generatedPath;
            $item['barcode_type'] = $barcodeType;
            $item['barcode_data'] = $item['unique_code'];
            $generatedCount++;
        }
    }
}
unset($item);
?>

<style>
    .labels-page {
        --label-width: 1.2in;
        --label-height: 0.8in;
        --print-scale: 1.5;
        max-width: 1400px;
        margin: 0 auto;
    }

    .page-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        gap: 16px;
        margin-bottom: 20px;
    }

    .filter-card,
    .items-card {
        background: #fff;
        border: 1px solid #dee2e6;
        border-radius: 8px;
        box-shadow: 0 1px 4px rgba(0,0,0,0.06);
        margin-bottom: 18px;
    }

    .filter-card {
        padding: 18px;
    }

    .items-card {
        padding: 0;
        overflow: hidden;
    }

    .items-card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 14px 18px;
        border-bottom: 1px solid #dee2e6;
        background: #f8f9fa;
    }

    .labels-toolbar {
        display: flex;
        gap: 8px;
        flex-wrap: wrap;
    }

    .source-help {
        font-size: 12px;
        color: #6c757d;
    }

    .labels-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
        gap: 12px;
        padding: 18px;
    }

    .label-card {
        border: 1px solid #ced4da;
        border-radius: 6px;
        padding: 10px;
        background: #fff;
        min-height: 138px;
        display: flex;
        flex-direction: column;
        gap: 6px;
        box-sizing: border-box;
        overflow: hidden;
    }

    .label-print-content {
        display: flex;
        flex-direction: column; bbnnn b bn bn n
        gap: 6px;
        min-height: 0;
    }

    .label-select {
        display: flex;
        justify-content: space-between;
        gap: 8px;
        font-size: 12px;
        color: #6c757d;
    }

    .label-item-name {
        font-weight: 700;
        color: #212529;
        font-size: 13px;
        line-height: 1.25;
        min-height: 32px;
        overflow: hidden;
        overflow-wrap: anywhere;
        word-break: break-word;
    }

    .label-branch,
    .label-price {
        font-size: 11px;
        color: #495057;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    .label-barcode {
        min-height: 34px;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 1px dashed #adb5bd;
        background: transparent;
    }

    .label-barcode img {
        max-width: 100%;
        max-height: 42px;
    }

    .barcode-fallback {
        font-family: "Courier New", monospace;
        font-size: 14px;
        color: #111;
    }

    .label-code {
        text-align: center;
        font-family: "Courier New", monospace;
        font-weight: 700;
        font-size: 13px;
        overflow-wrap: anywhere;
        word-break: break-word;
        max-width: 100%;
    }

    .empty-state {
        padding: 42px 18px;
        text-align: center;
        color: #6c757d;
    }

    @media print {
        @page {
            size: 1.8in 1.2in;
            margin: 0;
        }

        html,
        body {
            background: #fff !important;
            width: 1.8in;
            margin: 0 !important;
            padding: 0 !important;
        }

        nav,
        .navbar,
        .page-header,
        .filter-card,
        .items-card-header,
        .label-select,
        .btn,
        .no-print {
            display: none !important;
        }

        .labels-page,
        .items-card {
            width: 1.8in;
            max-width: 1.8in;
            margin: 0;
            padding: 0;
            border: 0;
            box-shadow: none;
            overflow: visible;
        }

        .labels-grid {
            display: block;
            width: 1.8in;
            padding: 0;
            margin: 0;
        }

        .label-card {
            width: 1.8in;
            height: 1.2in;
            box-sizing: border-box;
            min-height: 0;
            border: 0;
            border-radius: 0;
            box-shadow: none;
            margin: 0;
            padding: 0;
            position: relative;
            display: block;
            page-break-inside: avoid;
            page-break-after: always;
            break-inside: avoid;
            break-after: page;
            overflow: hidden;
        }

        .label-print-content {
            position: absolute;
            top: 50%;
            left: 50%;
            width: 66.6667%;
            height: 66.6667%;
            box-sizing: border-box;
            padding: 0.016in 0.03in;
            display: flex;
            flex-direction: column;
            gap: 0;
            transform: translate(-50%, -50%) scale(1.5);
            transform-origin: center;
            overflow: hidden;
            isolation: isolate;
        }

        .label-card:last-child {
            page-break-after: auto;
            break-after: auto;
        }

        .label-card:not(.selected-for-print) {
            display: none !important;
        }

        .label-item-name {
            display: flex;
            align-items: flex-start;
            justify-content: center;
            position: relative;
            z-index: 2;
            font-size: 11px;
            line-height: 1.12;
            min-height: 0;
            height: 0.18in;
            margin-bottom: 0;
            max-height: none;
            overflow: hidden;
            text-align: center;
            overflow-wrap: anywhere;
            word-break: break-word;
        }

        .label-branch,
        .label-price {
            display: none;
        }

        .label-barcode {
            border: 0;
            background: transparent;
            position: absolute;
            top: 0.23in;
            left: 0.05in;
            right: 0.05in;
            bottom: auto;
            z-index: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            min-height: 0;
            height: 0.34in;
            max-height: none;
            overflow: hidden;
            opacity: 1;
        }

        .label-barcode img {
            width: 100%;
            max-width: 100%;
            height: 100%;
            max-height: 100%;
            object-fit: contain;
        }

        .barcode-fallback {
            font-size: 7.5pt;
        }

        .label-code {
            display: flex;
            align-items: flex-end;
            justify-content: center;
            position: relative;
            z-index: 2;
            flex: 1 1 auto;
            font-size: 13px;
            line-height: 1;
            margin-top: auto;
            height: 0.16in;
            padding-bottom: 0;
            max-height: none;
            overflow: hidden;
            overflow-wrap: anywhere;
            word-break: break-word;
        }
    }
</style>

<div class="labels-page">
    <div class="page-header">
        <div>
            <h2 class="mb-1"><i class="fas fa-barcode"></i> Barcode Labels</h2>
            <p class="text-muted mb-0">Generate 0.8&quot; x 1.2&quot; labels from branch stock, transfers, or custom codes.</p>
        </div>
        <a href="<?php echo htmlspecialchars(getDashboardLink()); ?>" class="btn btn-outline-secondary">
            <i class="fas fa-arrow-left"></i> Back
        </a>
    </div>

    <form method="POST" class="filter-card" id="labelsFilterForm">
        <div class="row g-3 align-items-end">
            <div class="col-lg-3 col-md-6">
                <label for="source" class="form-label">Print From</label>
                <select name="source" id="source" class="form-select">
                    <option value="branch_stock" <?php echo $source === 'branch_stock' ? 'selected' : ''; ?>>Branch stock</option>
                    <option value="transfers" <?php echo $source === 'transfers' ? 'selected' : ''; ?>>Transfers</option>
                    <option value="custom" <?php echo $source === 'custom' ? 'selected' : ''; ?>>Custom codes</option>
                </select>
            </div>
            <div class="col-lg-3 col-md-6 source-field" data-source-field="branch_stock">
                <label for="branch_id" class="form-label">Branch</label>
                <select name="branch_id" id="branch_id" class="form-select">
                    <?php if ($canViewAllBranches): ?>
                        <option value="all" <?php echo $selectedBranch === 'all' ? 'selected' : ''; ?>>All branches</option>
                    <?php endif; ?>
                    <?php foreach ($branches as $branch): ?>
                        <option value="<?php echo (int)$branch['branch_id']; ?>" <?php echo (string)$selectedBranch === (string)$branch['branch_id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($branch['branch_name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-lg-4 col-md-6 source-field" data-source-field="transfers">
                <label for="shipment_id" class="form-label">Transfer</label>
                <select name="shipment_id" id="shipment_id" class="form-select">
                    <option value="all" <?php echo $selectedShipment === 'all' ? 'selected' : ''; ?>>All recent transfers</option>
                    <?php foreach ($transfers as $transfer): ?>
                        <?php
                        $transferLabel = '#' . $transfer['shipment_id'] . ' - ' .
                            ($transfer['from_branch_name'] ?? 'Warehouse') . ' to ' .
                            ($transfer['to_branch_name'] ?? 'Unknown branch') . ' (' .
                            ucfirst($transfer['status'] ?? 'unknown') . ')';
                        ?>
                        <option value="<?php echo (int)$transfer['shipment_id']; ?>" <?php echo (string)$selectedShipment === (string)$transfer['shipment_id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($transferLabel); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-lg-3 col-md-6">
                <label for="search" class="form-label">Search</label>
                <input type="text" name="search" id="search" class="form-control" value="<?php echo htmlspecialchars($search); ?>" placeholder="Item name or code">
            </div>
            <div class="col-lg-2 col-md-12">
                <button type="submit" class="btn btn-primary w-100">
                    <i class="fas fa-filter"></i> Apply
                </button>
            </div>
            <div class="col-12 source-field" data-source-field="custom">
                <label for="custom_codes" class="form-label">Custom Codes</label>
                <textarea name="custom_codes" id="custom_codes" class="form-control" rows="4" placeholder="Enter one code per line, or separate codes with commas"><?php echo htmlspecialchars($customCodes); ?></textarea>
                <div class="source-help mt-1">Duplicate custom codes are printed once.</div>
            </div>
            <div class="col-12">
                <span class="badge bg-light text-dark border">Print size: 0.8&quot; x 1.2&quot;</span>
                <span class="badge bg-light text-dark border">Barcode: Code 128</span>
                <span class="source-help ms-2">Maximum 500 labels are loaded per filtered branch stock or transfer result.</span>
            </div>
        </div>
    </form>

    <?php if ($generatedCount > 0): ?>
        <div class="alert alert-success no-print">
            <i class="fas fa-check-circle"></i>
            Generated <?php echo (int)$generatedCount; ?> barcode<?php echo $generatedCount === 1 ? '' : 's'; ?> for the current list.
        </div>
    <?php endif; ?>

    <div class="items-card">
        <div class="items-card-header">
            <div>
                <strong><?php echo count($items); ?></strong> labels loaded
                <small class="text-muted">(<?php echo htmlspecialchars($sourceNote); ?>)</small>
            </div>
            <div class="labels-toolbar">
                <button type="button" class="btn btn-sm btn-outline-primary" onclick="setAllLabels(true)">
                    <i class="fas fa-check-square"></i> Select All
                </button>
                <button type="button" class="btn btn-sm btn-outline-secondary" onclick="setAllLabels(false)">
                    <i class="far fa-square"></i> Clear
                </button>
                <button type="button" class="btn btn-sm btn-outline-dark" onclick="submitRegenerate()">
                    <i class="fas fa-sync-alt"></i> Regenerate
                </button>
                <button type="button" class="btn btn-sm btn-success" onclick="printSelectedLabels()">
                    <i class="fas fa-print"></i> Print Selected
                </button>
            </div>
        </div>

        <?php if (empty($items)): ?>
            <div class="empty-state">
                <i class="fas fa-barcode fa-3x mb-3"></i>
                <h5>No labels found</h5>
                <p>Choose a source or adjust the filters above and try again.</p>
            </div>
        <?php else: ?>
            <div class="labels-grid">
                <?php foreach ($items as $item): ?>
                    <?php
                    $code = $item['unique_code'];
                    $imagePath = labelImagePath($item['barcode_image_path'] ?? '');
                    $itemIdLabel = !empty($item['item_id']) ? '#' . (int)$item['item_id'] : 'Custom';
                    ?>
                    <div class="label-card selected-for-print">
                        <div class="label-select no-print">
                            <label>
                                <input type="checkbox" class="label-checkbox" checked>
                                Print
                            </label>
                            <span><?php echo htmlspecialchars($itemIdLabel); ?></span>
                        </div>
                        <div class="label-print-content">
                            <div class="label-item-name"><?php echo htmlspecialchars($item['item_name'] ?? 'Unknown Item'); ?></div>
                            <div class="label-branch">Details: <?php echo htmlspecialchars($item['item_details'] ?? 'N/A'); ?></div>
                            <div class="label-branch"><?php echo htmlspecialchars($item['category'] ?? 'Uncategorized'); ?></div>
                            <div class="label-branch"><?php echo htmlspecialchars($item['branch_name'] ?? 'Unknown location'); ?></div>
                            <div class="label-barcode">
                                <?php if ($imagePath): ?>
                                    <img src="<?php echo htmlspecialchars($imagePath); ?>" alt="<?php echo htmlspecialchars($code); ?>">
                                <?php else: ?>
                                    <span class="barcode-fallback">Barcode unavailable</span>
                                <?php endif; ?>
                            </div>
                            <div class="label-code"><?php echo htmlspecialchars($code); ?></div>
                            <?php if ($item['unit_price'] !== null): ?>
                                <div class="label-price">MWK <?php echo number_format((float)$item['unit_price'], 2); ?></div>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
function updateSourceFields() {
    const selectedSource = document.getElementById('source').value;
    document.querySelectorAll('.source-field').forEach(function(field) {
        field.style.display = field.dataset.sourceField === selectedSource ? '' : 'none';
    });
}

function setAllLabels(checked) {
    document.querySelectorAll('.label-checkbox').forEach(function(checkbox) {
        checkbox.checked = checked;
        checkbox.closest('.label-card').classList.toggle('selected-for-print', checked);
    });
}

document.querySelectorAll('.label-checkbox').forEach(function(checkbox) {
    checkbox.addEventListener('change', function() {
        this.closest('.label-card').classList.toggle('selected-for-print', this.checked);
    });
});

document.getElementById('source').addEventListener('change', updateSourceFields);
updateSourceFields();

function submitRegenerate() {
    const form = document.getElementById('labelsFilterForm');
    let regenerate = form.querySelector('input[name="regenerate"]');
    if (!regenerate) {
        regenerate = document.createElement('input');
        regenerate.type = 'hidden';
        regenerate.name = 'regenerate';
        form.appendChild(regenerate);
    }
    regenerate.value = '1';
    form.submit();
}

function fitTextInsideLabels() {
    document.querySelectorAll('.selected-for-print .label-item-name, .selected-for-print .label-code').forEach(function(element) {
        element.style.fontSize = '';
        const computed = window.getComputedStyle(element);
        let size = parseFloat(computed.fontSize);
        const minSize = element.classList.contains('label-code') ? 5 : 4.5;

        while (size > minSize && (element.scrollHeight > element.clientHeight || element.scrollWidth > element.clientWidth)) {
            size -= 0.4;
            element.style.fontSize = size + 'px';
        }
    });
}

function printSelectedLabels() {
    const selected = document.querySelectorAll('.label-checkbox:checked').length;
    if (selected === 0) {
        alert('Please select at least one label to print.');
        return;
    }

    fitTextInsideLabels();
    window.print();
}

window.addEventListener('beforeprint', fitTextInsideLabels);
</script>
