<?php include ADMIN_PATH . '/templates/header.php'; ?>

<div class="container-fluid py-3">

    <div class="mb-4">
        <h3 class="mb-1">
            <i class="bi bi-truck me-2"></i>
            <?= __('shipping.title', 'Shipping Settings') ?>
        </h3>
    </div>

    <?php if (isset($_GET['saved'])): ?>
        <div class="alert alert-success">
            <?= __('ui.success', 'Settings saved successfully!') ?>
        </div>
    <?php endif; ?>


    <form method="POST" action="/admin/settings/shipping/save" id="shippingForm">

        <?= \Core\System\Csrf::field(); ?>

    <?php
    $providerSelectionMode = $shipping['provider_selection_mode'] ?? 'manual_admin';
    $forcedProviderSetting = $shipping['forced_provider'] ?? '';
    $allowCustomerProviderChoice = !empty($shipping['allow_customer_provider_choice']);
    if (!$allowCustomerProviderChoice) {
        $providerSelectionMode = 'manual_admin';
        $forcedProviderSetting = '';
    } elseif (!in_array($providerSelectionMode, ['forced_provider', 'customer_choice'], true)) {
        $providerSelectionMode = 'customer_choice';
    }
    $activeProviderChoice = $shipping['pricing_provider'] ?? '';
    $activePricingSource = $shipping['pricing_source'] ?? 'manual';
    $fallbackToManual = !empty($shipping['pricing_fallback_manual']);
    $unavailableText = $shipping['shipping_unavailable_text'] ?? '';
    $activeProvidersForPricing = [];
    foreach ((new \Core\App\Models\ShippingIntegrationModel())->getAllIndexed() as $providerKey => $providerRow) {
        if ((int)($providerRow['is_active'] ?? 0) === 1) {
            $activeProvidersForPricing[$providerKey] = (string)($providerRow['display_name'] ?? $providerKey);
        }
    }
    ?>

    <div class="card mb-4">
        <div class="card-header">
            <strong><?= __('shipping.provider_selection_mode_title', 'Frontend shipping provider mode') ?></strong>
        </div>
        <div class="card-body">
            <div class="row g-3">
                <div class="col-12">
                    <div class="form-check form-switch mb-0">
                        <input class="form-check-input" type="checkbox" role="switch" name="allow_customer_provider_choice" id="allow-customer-provider-choice" value="1" <?= $allowCustomerProviderChoice ? 'checked' : '' ?>>
                        <label class="form-check-label fw-semibold" for="allow-customer-provider-choice"><?= __('shipping.allow_customer_provider_choice', 'Allow customer company choice in product page') ?></label>
                    </div>
                    <div class="form-text mt-1"><?= __('shipping.allow_customer_provider_choice_help', 'When disabled, the storefront keeps the current shipping flow exactly as it is now.') ?></div>
                </div>
            </div>

            <div id="provider-selection-mode-wrap" class="mt-3" style="<?= $allowCustomerProviderChoice ? '' : 'display:none' ?>">
                <div class="row g-3">
                    <div class="col-lg-6">
                        <label class="form-label" for="provider-selection-mode"><?= __('shipping.provider_selection_mode', 'Shipping company selection mode') ?></label>
                        <select class="form-select" name="provider_selection_mode" id="provider-selection-mode">
                            <option value="forced_provider" <?= $providerSelectionMode === 'forced_provider' ? 'selected' : '' ?>><?= __('shipping.provider_selection_mode_forced', 'Store forces one shipping company') ?></option>
                            <option value="customer_choice" <?= $providerSelectionMode === 'customer_choice' ? 'selected' : '' ?>><?= __('shipping.provider_selection_mode_customer', 'Customer chooses shipping company') ?></option>
                        </select>
                    </div>
                    <div class="col-lg-6" id="forced-provider-wrap" style="<?= $providerSelectionMode === 'forced_provider' ? '' : 'display:none' ?>">
                        <label class="form-label" for="forced-provider-select"><?= __('shipping.forced_provider', 'Forced / default provider') ?></label>
                        <select class="form-select" name="forced_provider" id="forced-provider-select">
                            <option value=""><?= __('actions.choose', 'Choose') ?></option>
                            <?php foreach (($activeProvidersForPricing ?? []) as $providerKey => $providerLabel): ?>
                                <option value="<?= htmlspecialchars($providerKey) ?>" <?= $forcedProviderSetting === $providerKey ? 'selected' : '' ?>><?= htmlspecialchars($providerLabel) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="form-text mt-2"><?= __('shipping.provider_selection_help', 'Choose how shipping companies appear on the product page without changing the current behavior of the other providers.') ?></div>
            </div>
        </div>
    </div>

    <div class="card mb-4">
        <div class="card-header">
            <strong><?= __('shipping.pricing_strategy_title', 'Shipping pricing strategy') ?></strong>
        </div>
        <div class="card-body">
            <div class="row g-3 align-items-end">
                <div class="col-xl-3 col-md-6">
                    <label class="form-label"><?= __('shipping.pricing_provider', 'Reference shipping provider') ?></label>
                    <select class="form-select" name="pricing_provider" id="pricing-provider-select">
                        <option value=""><?= __('actions.choose', 'Choose') ?></option>
                        <?php foreach (($activeProvidersForPricing ?? []) as $providerKey => $providerLabel): ?>
                            <option value="<?= htmlspecialchars($providerKey) ?>" <?= $activeProviderChoice === $providerKey ? 'selected' : '' ?>><?= htmlspecialchars($providerLabel) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-xl-3 col-md-6">
                    <label class="form-label"><?= __('shipping.price_source', 'Price source') ?></label>
                    <select class="form-select" name="pricing_source" id="pricing-source-select">
                        <option value="manual" <?= $activePricingSource === 'manual' ? 'selected' : '' ?>><?= __('shipping.price_source_manual', 'Manual prices') ?></option>
                        <option value="api" <?= $activePricingSource === 'api' ? 'selected' : '' ?>><?= __('shipping.price_source_api', 'Provider imported prices') ?></option>
                        <option value="reference" <?= $activePricingSource === 'reference' ? 'selected' : '' ?>><?= __('shipping.price_source_reference', 'Show imported prices as reference') ?></option>
                    </select>
                </div>
                <div class="col-xl-4 col-md-6">
                    <label class="form-label"><?= __('shipping.unavailable_text', 'Text when price is unavailable') ?></label>
                    <input type="text" class="form-control" name="shipping_unavailable_text" value="<?= htmlspecialchars($unavailableText) ?>" placeholder="<?= __('shipping.unavailable_text_placeholder', 'Calculated by wilaya (not free)') ?>">
                </div>
                <div class="col-xl-2 col-md-6">
                    <div class="form-check mt-md-4 pt-md-2">
                        <input class="form-check-input" type="checkbox" value="1" id="pricing-fallback-manual" name="pricing_fallback_manual" <?= $fallbackToManual ? 'checked' : '' ?>>
                        <label class="form-check-label" for="pricing-fallback-manual"><?= __('shipping.fallback_manual', 'Fallback to manual prices') ?></label>
                    </div>
                </div>
            </div>
            <div class="d-flex flex-wrap gap-2 justify-content-end mt-3">
                <button type="button" class="btn btn-outline-primary" id="sync-selected-provider-prices"><?= __('shipping.sync_selected_provider', 'Sync selected provider prices') ?></button>
                <button type="button" class="btn btn-outline-secondary" id="copy-selected-provider-prices"><?= __('shipping.apply_selected_provider', 'Copy selected provider prices into manual prices') ?></button>
            </div>
            <div class="form-text mt-2"><?= __('shipping.pricing_strategy_help_compact', 'If the provider price exists, it is used according to your selected source. A value of 0 means free shipping. Leave the price empty only when you want it treated as unavailable.') ?></div>
        </div>
    </div>

        <?php $mode = $shipping['mode'] ?? 'flat'; ?>

        <!-- MODE -->
        <div class="card mb-4">
            <div class="card-header">
                <strong><?= __('shipping.mode','Shipping Calculation Mode') ?></strong>
            </div>

            <div class="card-body row g-3">
                <?php
                $modes = [
                    'flat'  => ['shipping.flat','shipping.flat_desc'],
                    'state' => ['shipping.state','shipping.state_desc'],
                    'zones' => ['shipping.zones','shipping.zones_desc'],
                ];
                ?>
                <?php foreach ($modes as $value => $labels): ?>
                    <div class="col-md-4">
                        <label class="card p-3 h-100 cursor-pointer">
                            <input type="radio" name="mode" value="<?= $value ?>" <?= $mode === $value ? 'checked' : '' ?>>
                            <h6 class="mt-2"><?= __($labels[0]) ?></h6>
                            <small class="text-muted"><?= __($labels[1]) ?></small>
                        </label>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- FLAT -->
        <div class="card mb-4 shipping-box" data-mode="flat">
            <div class="card-header">
                <?= __('shipping.flat_price','Flat Shipping Price') ?>
            </div>
            <div class="card-body row g-3">

                <input type="hidden"
                       name="flat_price"
                       value="<?= ($shipping['flat_price'] !== null && $shipping['flat_price'] !== '') ? (string)(float)$shipping['flat_price'] : '' ?>">

                <div class="col-md-3">
                    <label><?= __('shipping.home_price','Home Delivery') ?></label>
                    <input type="number"
                           name="flat_home_price"
                           class="form-control"
                           placeholder="<?= __('shipping.empty_means_unavailable','Empty = unavailable · 0 = Free') ?>"
                           value="<?= ($shipping['flat_home_price'] !== null && $shipping['flat_home_price'] !== '') ? (string)(float)$shipping['flat_home_price'] : '' ?>">
                </div>

                <div class="col-md-3">
                    <label><?= __('shipping.desk_price','Desk Delivery') ?></label>
                    <input type="number"
                           name="flat_desk_price"
                           class="form-control"
                           placeholder="<?= __('shipping.empty_means_unavailable','Empty = unavailable · 0 = Free') ?>"
                           value="<?= ($shipping['flat_desk_price'] !== null && $shipping['flat_desk_price'] !== '') ? (string)(float)$shipping['flat_desk_price'] : '' ?>">
                </div>

            </div>
        </div>

        <!-- STATE -->
        <div class="card mb-4 shipping-box" data-mode="state">
            <div class="card-header">
                <strong><?= __('shipping.by_state','Shipping by Region') ?></strong>
            </div>
            <div class="card-body">

                <table class="table table-bordered align-middle" id="stateTable">
                    <thead>
                        <tr>
                            <th><?= __('shipping.region','Region') ?></th>
                            <th><?= __('shipping.home_price','Home Delivery') ?></th>
                            <th><?= __('shipping.desk_price','Desk Delivery') ?></th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>

                <!-- ADDED: Pagination UI (UI ONLY) -->
                <div class="d-flex justify-content-center mt-3">
                    <ul class="pagination pagination-sm mb-0" id="statePagination"></ul>
                </div>

            </div>
        </div>

        <!-- ZONES -->
        <div class="card mb-4 shipping-box" data-mode="zones">
            <div class="card-header d-flex justify-content-between align-items-center">
                <strong><?= __('shipping.zones','Shipping Zones') ?></strong>
                <button type="button" class="btn btn-sm btn-success" id="addZone">
                    <i class="bi bi-plus"></i> <?= __('actions.add','Add') ?>
                </button>
            </div>

            <div class="card-body" id="zonesWrapper">
                <?php foreach (($shipping['zones'] ?? []) as $i => $zone): ?>
                    <div class="zone-box border rounded p-3 mb-3">
                        <div class="row g-3 align-items-end">

                            <div class="col-md-3">
                                <label><?= __('shipping.zone_name','Zone Name') ?></label>
                                <input type="text" class="form-control"
                                       name="zones[<?= $i ?>][name]"
                                       value="<?= htmlspecialchars($zone['name']) ?>">
                            </div>

                            <div class="col-md-2">
                                <label><?= __('shipping.home_price','Home') ?></label>
                                <input type="number" class="form-control"
                                       name="zones[<?= $i ?>][home_price]"
                                       placeholder="<?= __('shipping.empty_means_unavailable','Empty = unavailable · 0 = Free') ?>"
                                       value="<?= ($zone['home_price'] !== null && $zone['home_price'] !== '') ? htmlspecialchars((string)(float)$zone['home_price']) : '' ?>">
                            </div>

                            <div class="col-md-2">
                                <label><?= __('shipping.desk_price','Desk') ?></label>
                                <input type="number" class="form-control"
                                       name="zones[<?= $i ?>][desk_price]"
                                       placeholder="<?= __('shipping.empty_means_unavailable','Empty = unavailable · 0 = Free') ?>"
                                       value="<?= ($zone['desk_price'] !== null && $zone['desk_price'] !== '') ? htmlspecialchars((string)(float)$zone['desk_price']) : '' ?>">
                            </div>

                            <div class="col-md-6">
                                <label><?= __('shipping.regions','Regions') ?></label>
                                <select class="form-select region-select"
                                        name="zones[<?= $i ?>][regions][]"
                                        multiple
                                        data-selected="<?= htmlspecialchars(json_encode($zone['regions'])) ?>">
                                </select>
                            </div>

                            <div class="col-md-1">
                                <button type="button" class="btn btn-danger remove-zone">
                                    <i class="bi bi-trash"></i>
                                </button>
                            </div>

                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>


<!-- ============================= -->
<!-- SHIPPING PROVIDERS PRICES -->
<!-- ============================= -->
<?php
use Core\App\Models\ShippingIntegrationModel;
use Core\App\Models\ShippingPriceModel;
use Core\App\Support\DzLocation;

$integrationModel = new ShippingIntegrationModel();
$priceModel       = new ShippingPriceModel();
$providers        = $integrationModel->getAllIndexed();
$dzStates         = DzLocation::states();
$providerModes    = $shipping['provider_price_modes'] ?? [];
$providerImports  = $shipping['provider_imported_prices'] ?? [];
$providerMeta     = $shipping['provider_imported_meta'] ?? [];
$activeProvidersForPricing = [];
foreach ($providers as $providerKey => $integrationRow) {
    if ((int)($integrationRow['is_active'] ?? 0) === 1) {
        $activeProvidersForPricing[$providerKey] = (string)($integrationRow['display_name'] ?? $providerKey);
    }
}

$pricingSupport = [
    'ecotrack'   => ['status' => 'supported'],
    'zr_express' => ['status' => 'not_supported'],
    'yalidine'   => ['status' => 'not_supported'],
    'maystro'    => ['status' => 'supported'],
    'dhd'        => ['status' => 'not_supported'],
];
?>
<div class="card mb-4">
    <div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
        <strong><?= __('shipping.providers_prices','Shipping Providers Prices') ?></strong>
        <small class="text-muted"><?= __('shipping.providers_prices_desc','Manage each provider with the same manual grid, while optionally importing provider prices when available.') ?></small>
    </div>

    <div class="card-body">
        <?php foreach ($providers as $provider => $integration): ?>
            <?php if ((int)($integration['is_active'] ?? 0) !== 1) continue; ?>
            <?php
            $manualRows = $priceModel->getAllByProvider($provider);
            $manualMap = [];
            foreach ($manualRows as $row) {
                $manualMap[(string)$row['wilaya_code']][(string)$row['delivery_type']] = (string)$row['price'];
            }
            $importedMap = is_array($providerImports[$provider] ?? null) ? $providerImports[$provider] : [];
            $meta = is_array($providerMeta[$provider] ?? null) ? $providerMeta[$provider] : [];
            $support = $pricingSupport[$provider]['status'] ?? 'not_supported';
            $supportsSync = $support === 'supported';
            ?>
            <div class="border rounded mb-4 provider-pricing-card" data-provider="<?= htmlspecialchars($provider) ?>">
                <input type="hidden" name="provider_price_modes[<?= htmlspecialchars($provider) ?>]" value="<?= htmlspecialchars($providerModes[$provider] ?? 'manual') ?>">
                <div class="p-3 border-bottom bg-light-subtle">
                    <div class="d-flex justify-content-between align-items-start flex-wrap gap-3">
                        <div>
                            <div class="fw-bold">🚚 <?= htmlspecialchars($integration['display_name']) ?></div>
                            <div class="small text-muted"><?= htmlspecialchars($provider) ?></div>
                        </div>
                        <div class="d-flex align-items-center flex-wrap gap-2">
                            <?php if ($supportsSync): ?>
                                <span class="badge text-bg-success"><?= __('shipping.pricing_supported','Automatic pricing supported') ?></span>
                            <?php else: ?>
                                <span class="badge text-bg-secondary"><?= __('shipping.pricing_not_supported','Automatic pricing not supported') ?></span>
                            <?php endif; ?>
                            <span class="small text-muted provider-sync-time" data-provider-sync-time><?= !empty($meta['last_synced_at']) ? __('shipping.last_sync','Last sync') . ': ' . htmlspecialchars($meta['last_synced_at']) : __('shipping.not_synced_yet','Not synced yet') ?></span>
                        </div>
                    </div>
                    <div class="d-flex flex-wrap gap-2 mt-3 justify-content-end">
                        <button type="button" class="btn btn-outline-primary provider-sync-btn" data-provider-sync="<?= htmlspecialchars($provider) ?>" <?= $supportsSync ? '' : 'disabled' ?>>
                            <?= __('shipping.sync_now','Sync provider prices now') ?>
                        </button>
                        <button type="button" class="btn btn-outline-secondary provider-apply-btn" data-provider-apply="<?= htmlspecialchars($provider) ?>" <?= !empty($importedMap) ? '' : 'disabled' ?>>
                            <?= __('shipping.apply_imported_to_manual','Copy imported prices into manual prices') ?>
                        </button>
                    </div>
                </div>

                <div class="table-responsive">
                    <table class="table table-bordered align-middle mb-0 provider-pricing-table" data-provider-table="<?= htmlspecialchars($provider) ?>">
                        <thead>
                            <tr>
                                <th style="width:24%;"><?= __('shipping.wilaya','Wilaya') ?></th>
                                <th><?= __('shipping.home_price','Home Delivery') ?></th>
                                <th><?= __('shipping.desk_price','Desk Delivery') ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($dzStates as $state): ?>
                                <?php
                                $code = \Core\App\Support\DzLocation::normalizeCode((string)($state['code'] ?? ''));
                                $manualHome = $manualMap[$code]['home'] ?? '';
                                $manualDesk = $manualMap[$code]['desk'] ?? '';
                                $apiHome = $importedMap[$code]['home'] ?? null;
                                $apiDesk = $importedMap[$code]['desk'] ?? null;
                                ?>
                                <tr>
                                    <td>
                                        <div class="fw-semibold"><?= htmlspecialchars($state['name'] ?? $code) ?></div>
                                        <div class="small text-muted"><?= htmlspecialchars($state['ar_name'] ?? '') ?></div>
                                    </td>
                                    <td>
                                        <input type="number" class="form-control form-control-sm"
                                               name="providers_prices[<?= htmlspecialchars($provider) ?>][<?= htmlspecialchars($code) ?>][home]"
                                               value="<?= htmlspecialchars((string)$manualHome) ?>"
                                               data-provider-input="<?= htmlspecialchars($provider) ?>"
                                               data-state-code="<?= htmlspecialchars($code) ?>"
                                               data-type="home">
                                        <div class="small text-muted mt-1 provider-api-note" data-provider-api-note="<?= htmlspecialchars($provider) ?>" data-state-code="<?= htmlspecialchars($code) ?>" data-type="home">
                                            <?= __('shipping.provider_price_label','Provider price') ?>:
                                            <span><?= $apiHome !== null ? htmlspecialchars((string)$apiHome) : '—' ?></span>
                                        </div>
                                    </td>
                                    <td>
                                        <input type="number" class="form-control form-control-sm"
                                               name="providers_prices[<?= htmlspecialchars($provider) ?>][<?= htmlspecialchars($code) ?>][desk]"
                                               value="<?= htmlspecialchars((string)$manualDesk) ?>"
                                               data-provider-input="<?= htmlspecialchars($provider) ?>"
                                               data-state-code="<?= htmlspecialchars($code) ?>"
                                               data-type="desk">
                                        <div class="small text-muted mt-1 provider-api-note" data-provider-api-note="<?= htmlspecialchars($provider) ?>" data-state-code="<?= htmlspecialchars($code) ?>" data-type="desk">
                                            <?= __('shipping.provider_price_label','Provider price') ?>:
                                            <span><?= $apiDesk !== null ? htmlspecialchars((string)$apiDesk) : '—' ?></span>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <div class="p-3 border-top provider-pagination" data-provider-pagination="<?= htmlspecialchars($provider) ?>"></div>
            </div>
        <?php endforeach; ?>
    </div>
</div>

        <button type="submit" class="btn btn-primary px-4">
            <?= __('actions.save','Save') ?>
        </button>

    </form>
</div>


<script>
/* ===== ADDED: STATE PAGINATION (UI ONLY) ===== */

const STATES_PER_PAGE = 6;
let CURRENT_STATE_PAGE = 1;
let STATE_ROWS = [];

function applyStatePagination() {
    const tbody = document.querySelector('#stateTable tbody');
    if (!tbody) return;

    if (STATE_ROWS.length === 0) {
        STATE_ROWS = Array.from(tbody.children);
    }

    renderStatePage(1);
    renderStatePagination();
}

function renderStatePage(page) {
    CURRENT_STATE_PAGE = page;
    const tbody = document.querySelector('#stateTable tbody');
    tbody.innerHTML = '';

    const start = (page - 1) * STATES_PER_PAGE;
    const end = start + STATES_PER_PAGE;

    STATE_ROWS.slice(start, end).forEach(tr => tbody.appendChild(tr));
}

function renderStatePagination() {
    const ul = document.getElementById('statePagination');
    ul.innerHTML = '';

    const pages = Math.ceil(STATE_ROWS.length / STATES_PER_PAGE);

    for (let i = 1; i <= pages; i++) {
        const li = document.createElement('li');
        li.className = 'page-item' + (i === CURRENT_STATE_PAGE ? ' active' : '');
        li.innerHTML = `<button type="button" class="page-link">${i}</button>`;
        li.onclick = () => {
            renderStatePage(i);
            renderStatePagination();
        };
        ul.appendChild(li);
    }
}

/* تشغيل بعد تحميل الجدول */
document.addEventListener('DOMContentLoaded', () => {
    setTimeout(applyStatePagination, 300);
});

</script>



<script>
/* ===============================
   MODE TOGGLING
================================ */
function updateBoxes() {
    const mode = document.querySelector('input[name="mode"]:checked')?.value;
    document.querySelectorAll('.shipping-box').forEach(box => {
        box.style.display = box.dataset.mode === mode ? 'block' : 'none';
    });
}
document.querySelectorAll('input[name="mode"]').forEach(r => r.addEventListener('change', updateBoxes));
updateBoxes();

/* ===============================
   LOAD STATES
================================ */
let STATES = [];
fetch('/api/dz/states')
    .then(r => r.json())
    .then(data => {
        STATES = data;
        initZones();
        initStateTable();
    });

/* ===============================
   STATE MODE TABLE
   (UPDATED: HOME / DESK)
================================ */
function initStateTable() {
    const tbody = document.querySelector('#stateTable tbody');
    tbody.innerHTML = '';

    const saved = <?= json_encode($shipping['states'] ?? []) ?>;

    STATES.forEach(state => {
        const row = saved[state.code] || {};

        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td>${state.name}</td>

            <td>
                <input type="number"
                       class="form-control"
                       name="states[${state.code}][home]"
                       value="${row.home ?? ''}">
            </td>

            <td>
                <input type="number"
                       class="form-control"
                       name="states[${state.code}][desk]"
                       value="${row.desk ?? ''}">
            </td>
        `;
        tbody.appendChild(tr);
    });
}

/* ===============================
   ZONES LOGIC
================================ */
function getUsedRegions(except = null) {
    const used = new Set();
    document.querySelectorAll('.region-select').forEach(sel => {
        if (sel === except) return;
        [...sel.selectedOptions].forEach(opt => used.add(opt.value));
    });
    return used;
}

function refreshDisabledRegions() {
    const used = new Set();

    document.querySelectorAll('.region-select').forEach(sel => {
        [...sel.selectedOptions].forEach(opt => used.add(opt.value));
    });

    document.querySelectorAll('.region-select').forEach(sel => {
        [...sel.options].forEach(opt => {
            opt.disabled = used.has(opt.value) && !opt.selected;
        });
    });
}

function initZones() {
    document.querySelectorAll('.region-select').forEach(select => {
        const selected = JSON.parse(select.dataset.selected || '[]');
        select.innerHTML = '';

        const used = getUsedRegions(select);

        STATES.forEach(state => {
            const opt = document.createElement('option');
            opt.value = state.code;
            opt.textContent = state.name;

            if (selected.includes(state.code)) opt.selected = true;
            if (used.has(state.code) && !opt.selected) opt.disabled = true;

            select.appendChild(opt);
        });

        select.onchange = refreshDisabledRegions;
    });
}

/* ===============================
   ADD / REMOVE ZONES
   (UPDATED: HOME / DESK)
================================ */
const zonesWrapper = document.getElementById('zonesWrapper');

document.getElementById('addZone').addEventListener('click', () => {
    const i = zonesWrapper.children.length;

    const div = document.createElement('div');
    div.className = 'zone-box border rounded p-3 mb-3';

    div.innerHTML = `
        <div class="row g-3 align-items-end">

            <div class="col-md-3">
                <label><?= __('shipping.zone_name','Zone Name') ?></label>
                <input type="text"
                       class="form-control"
                       name="zones[${i}][name]">
            </div>

            <div class="col-md-2">
                <label><?= __('shipping.home_price','Home') ?></label>
                <input type="number"
                       class="form-control"
                       name="zones[${i}][home_price]">
            </div>

            <div class="col-md-2">
                <label><?= __('shipping.desk_price','Desk') ?></label>
                <input type="number"
                       class="form-control"
                       name="zones[${i}][desk_price]">
            </div>

            <div class="col-md-4">
                <label><?= __('shipping.regions','Regions') ?></label>
                <select class="form-select region-select"
                        name="zones[${i}][regions][]"
                        multiple></select>
            </div>

            <div class="col-md-1">
                <button type="button"
                        class="btn btn-danger remove-zone">
                    <i class="bi bi-trash"></i>
                </button>
            </div>

        </div>
    `;

    zonesWrapper.appendChild(div);
    initZones();
});

zonesWrapper.addEventListener('click', e => {
    if (e.target.closest('.remove-zone')) {
        e.target.closest('.zone-box').remove();
        refreshDisabledRegions();
    }
});
</script>
<script>
/* ===============================
   GLOBAL STATE STORAGE
================================ */
let STATE_PRICES = {}; // { "01": {home: 500, desk: 300}, ... }

/* ===============================
   INIT STATE TABLE (MODIFIED)
================================ */
function initStateTable() {
    const tbody = document.querySelector('#stateTable tbody');
    tbody.innerHTML = '';

    const saved = <?= json_encode($shipping['states'] ?? []) ?>;

    STATES.forEach(state => {
        const row = saved[state.code] || {};

        // INIT STATE STORAGE
        STATE_PRICES[state.code] = {
            home: row.home ?? '',
            desk: row.desk ?? ''
        };

        const tr = document.createElement('tr');
        tr.dataset.state = state.code;

        tr.innerHTML = `
            <td>${state.name}</td>

            <td>
                <input type="number"
                       class="form-control state-home"
                       value="${STATE_PRICES[state.code].home}">
            </td>

            <td>
                <input type="number"
                       class="form-control state-desk"
                       value="${STATE_PRICES[state.code].desk}">
            </td>
        `;

        tbody.appendChild(tr);
    });

    applyStatePagination();
}

/* ===============================
   CAPTURE INPUT CHANGES
================================ */
document.addEventListener('input', e => {
    const tr = e.target.closest('tr[data-state]');
    if (!tr) return;

    const code = tr.dataset.state;

    if (e.target.classList.contains('state-home')) {
        STATE_PRICES[code].home = e.target.value;
    }

    if (e.target.classList.contains('state-desk')) {
        STATE_PRICES[code].desk = e.target.value;
    }
});

/* ===============================
   BEFORE SUBMIT: INJECT ALL STATES
================================ */


const PROVIDER_PAGE_SIZE = 8;
const PROVIDER_ROWS = {};
const PROVIDER_PAGES = {};
const PROVIDER_VALUES = {};
const SHIPPING_CSRF = document.querySelector('input[name="_csrf"]') ? document.querySelector('input[name="_csrf"]').value : '';
const T_SELECT_PROVIDER = <?= json_encode(__('shipping.select_provider_first','Select a provider first')) ?>;
const T_SYNCING = <?= json_encode(__('shipping.syncing','Syncing...')) ?>;
const T_APPLYING = <?= json_encode(__('shipping.applying','Applying...')) ?>;

function setupProviderTables() {
    document.querySelectorAll('[data-provider-table]').forEach(table => {
        const provider = table.dataset.providerTable;
        const tbody = table.querySelector('tbody');
        PROVIDER_ROWS[provider] = Array.from(tbody.children);
        PROVIDER_VALUES[provider] = {};
        PROVIDER_ROWS[provider].forEach(row => {
            row.querySelectorAll('[data-provider-input]').forEach(input => {
                const stateCode = input.dataset.stateCode;
                const type = input.dataset.type;
                PROVIDER_VALUES[provider][stateCode] = PROVIDER_VALUES[provider][stateCode] || {home:'', desk:''};
                PROVIDER_VALUES[provider][stateCode][type] = input.value || '';
            });
        });
        renderProviderPage(provider, 1);
    });
}

function renderProviderPage(provider, page) {
    const table = document.querySelector(`[data-provider-table="${provider}"]`);
    if (!table) return;
    const tbody = table.querySelector('tbody');
    const rows = PROVIDER_ROWS[provider] || [];
    PROVIDER_PAGES[provider] = page;
    tbody.innerHTML = '';
    const start = (page - 1) * PROVIDER_PAGE_SIZE;
    rows.slice(start, start + PROVIDER_PAGE_SIZE).forEach(row => tbody.appendChild(row));
    renderProviderPagination(provider);
}

function renderProviderPagination(provider) {
    const wrap = document.querySelector(`[data-provider-pagination="${provider}"]`);
    if (!wrap) return;
    const rows = PROVIDER_ROWS[provider] || [];
    const pages = Math.max(1, Math.ceil(rows.length / PROVIDER_PAGE_SIZE));
    const current = PROVIDER_PAGES[provider] || 1;
    wrap.innerHTML = '';
    if (pages <= 1) return;

    const ul = document.createElement('ul');
    ul.className = 'pagination pagination-sm mb-0 justify-content-center';
    for (let i = 1; i <= pages; i++) {
        const li = document.createElement('li');
        li.className = 'page-item' + (i === current ? ' active' : '');
        li.innerHTML = `<button type="button" class="page-link">${i}</button>`;
        li.addEventListener('click', () => renderProviderPage(provider, i));
        ul.appendChild(li);
    }
    wrap.appendChild(ul);
}

function setProviderImportedPrices(provider, prices) {
    Object.entries(prices || {}).forEach(([stateCode, types]) => {
        ['home', 'desk'].forEach(type => {
            const note = document.querySelector(`[data-provider-api-note="${provider}"][data-state-code="${stateCode}"][data-type="${type}"] span`);
            if (note) {
                note.textContent = (types && types[type] !== null && types[type] !== undefined && types[type] !== '') ? types[type] : '—';
            }
        });
    });
    const applyBtn = document.querySelector(`[data-provider-apply="${provider}"]`);
    if (applyBtn) applyBtn.disabled = false;
}

function wireProviderActions() {
    document.querySelectorAll('[data-provider-sync]').forEach(btn => {
        btn.addEventListener('click', async function () {
            const provider = this.dataset.providerSync;
            const syncTime = document.querySelector(`[data-provider="${provider}"] [data-provider-sync-time]`);
            const original = this.textContent.trim();
            this.disabled = true;
            this.textContent = T_SYNCING;
            try {
                const body = new URLSearchParams({_csrf: SHIPPING_CSRF, provider});
                const res = await fetch('/admin/settings/shipping/sync-provider-prices', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
                    body: body.toString(),
                    credentials: 'same-origin'
                });
                const data = await res.json();
                if (!data.success) throw new Error(data.message || 'Sync failed');
                setProviderImportedPrices(provider, data.prices || {});
                if (syncTime) syncTime.textContent = `<?= __('shipping.last_sync','Last sync') ?>: ${data.last_synced_at || ''}`;
                alert(data.message || 'OK');
            } catch (err) {
                alert(err.message || 'Sync failed');
            } finally {
                this.disabled = false;
                this.textContent = original;
            }
        });
    });

    document.querySelectorAll('[data-provider-apply]').forEach(btn => {
        btn.addEventListener('click', async function () {
            const provider = this.dataset.providerApply;
            const original = this.textContent.trim();
            this.disabled = true;
            this.textContent = T_APPLYING;
            try {
                const body = new URLSearchParams({_csrf: SHIPPING_CSRF, provider});
                const res = await fetch('/admin/settings/shipping/apply-imported-prices', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
                    body: body.toString(),
                    credentials: 'same-origin'
                });
                const data = await res.json();
                if (!data.success) throw new Error(data.message || 'Apply failed');
                location.reload();
            } catch (err) {
                alert(err.message || 'Apply failed');
                this.disabled = false;
                this.textContent = original;
            }
        });
    });
}


document.addEventListener('input', event => {
    const input = event.target.closest('[data-provider-input]');
    if (!input) return;
    const provider = input.dataset.providerInput;
    const stateCode = input.dataset.stateCode;
    const type = input.dataset.type;
    PROVIDER_VALUES[provider] = PROVIDER_VALUES[provider] || {};
    PROVIDER_VALUES[provider][stateCode] = PROVIDER_VALUES[provider][stateCode] || {home:'', desk:''};
    PROVIDER_VALUES[provider][stateCode][type] = input.value || '';
});


function getSelectedPricingProvider() {
    const select = document.getElementById('pricing-provider-select');
    return select ? select.value : '';
}

function triggerProviderSync(provider) {
    const btn = provider ? document.querySelector(`[data-provider-sync="${provider}"]`) : null;
    if (!btn || btn.disabled) {
        alert(T_SELECT_PROVIDER);
        return;
    }
    btn.click();
}

function triggerProviderApply(provider) {
    const btn = provider ? document.querySelector(`[data-provider-apply="${provider}"]`) : null;
    if (!btn || btn.disabled) {
        alert(T_SELECT_PROVIDER);
        return;
    }
    btn.click();
}

document.getElementById('sync-selected-provider-prices')?.addEventListener('click', function () {
    triggerProviderSync(getSelectedPricingProvider());
});

document.getElementById('copy-selected-provider-prices')?.addEventListener('click', function () {
    triggerProviderApply(getSelectedPricingProvider());
});

setupProviderTables();
wireProviderActions();


function toggleFrontendProviderModeFields() {
    const allowChoice = document.getElementById('allow-customer-provider-choice');
    const modeWrap = document.getElementById('provider-selection-mode-wrap');
    const modeSelect = document.getElementById('provider-selection-mode');
    const forcedWrap = document.getElementById('forced-provider-wrap');
    const forcedSelect = document.getElementById('forced-provider-select');

    const enabled = !!(allowChoice && allowChoice.checked);
    if (modeWrap) modeWrap.style.display = enabled ? '' : 'none';

    let mode = enabled && modeSelect ? modeSelect.value : 'manual_admin';
    if (enabled && mode === 'manual_admin') {
        mode = 'customer_choice';
        if (modeSelect) modeSelect.value = 'customer_choice';
    }
    const showForced = enabled && mode === 'forced_provider';
    if (forcedWrap) forcedWrap.style.display = showForced ? '' : 'none';
    if (forcedSelect && !showForced) forcedSelect.value = '';
}

document.getElementById('allow-customer-provider-choice')?.addEventListener('change', toggleFrontendProviderModeFields);
document.getElementById('provider-selection-mode')?.addEventListener('change', toggleFrontendProviderModeFields);
toggleFrontendProviderModeFields();

document.getElementById('shippingForm').addEventListener('submit', () => {
    const tbody = document.querySelector('#stateTable tbody');
    tbody.innerHTML = ''; // remove paginated rows

    Object.entries(STATE_PRICES).forEach(([code, prices]) => {
        const tr = document.createElement('tr');

        tr.innerHTML = `
            <input type="hidden"
                   name="states[${code}][home]"
                   value="${prices.home}">

            <input type="hidden"
                   name="states[${code}][desk]"
                   value="${prices.desk}">
        `;

        tbody.appendChild(tr);
    });

    let hiddenWrap = document.getElementById('providerPricesHiddenInputs');
    if (hiddenWrap) hiddenWrap.remove();
    hiddenWrap = document.createElement('div');
    hiddenWrap.id = 'providerPricesHiddenInputs';
    hiddenWrap.style.display = 'none';

    Object.entries(PROVIDER_VALUES).forEach(([provider, states]) => {
        Object.entries(states || {}).forEach(([code, prices]) => {
            ['home','desk'].forEach(type => {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = `providers_prices[${provider}][${code}][${type}]`;
                input.value = prices && prices[type] !== undefined ? prices[type] : '';
                hiddenWrap.appendChild(input);
            });
        });
    });

    document.getElementById('shippingForm').appendChild(hiddenWrap);
});
</script>
