<?php
use Core\App\Support\OrderPricing;
use Core\App\Models\ShippingIntegrationModel;

/* =============================
   Load integrations
============================= */
$integrationModel = new ShippingIntegrationModel();
$providers = [];

foreach ($integrationModel->getAllIndexed() as $k => $i) {
    if (!empty($i['is_active'])) {
        $providers[$k] = $i;
    }
}

/* =============================
   Order data
============================= */
$extra        = is_array($order['extra']) ? $order['extra'] : json_decode($order['extra'], true);
$shipping     = $extra['shipping'] ?? [];
$lockedProvider = trim((string)($shipping['provider'] ?? ''));
if ($lockedProvider !== '' && !isset($providers[$lockedProvider])) {
    $lockedProvider = '';
}
$quantity     = $extra['quantity'] ?? null;
$shippingType = $shipping['type'] ?? null;
$destination  = $shipping['destination'] ?? [];

$stateCode         = (string)($destination['state_code'] ?? '');
$orderCommune      = trim((string)($destination['city_name'] ?? ''));
$orderWilayaFrench = trim((string)($destination['state_name'] ?? ''));

/* =============================
   Load Ecotrack integration
============================= */
$eco = $integrationModel->getByProvider('ecotrack');
$wilayas = [];

if ($eco && !empty($eco['is_active'])) {
    $ch = curl_init(rtrim($eco['api_id'], '/') . '/api/v1/get/wilayas');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . $eco['api_token'],
            'Accept: application/json'
        ]
    ]);
    $res = curl_exec($ch);
    curl_close($ch);

    $wilayas = json_decode($res, true) ?: [];
}

/* =============================
   Resolve visible ECOTRACK labels
============================= */
if ($orderWilayaFrench === '' && !empty($wilayas) && $stateCode !== '') {
    foreach ($wilayas as $w) {
        $wilayaId = (string)($w['wilaya_id'] ?? '');
        if ($wilayaId === ltrim($stateCode, '0') || $wilayaId === $stateCode) {
            $orderWilayaFrench = trim((string)($w['wilaya_name'] ?? ''));
            break;
        }
    }
}

$orderAddress = trim($orderWilayaFrench . ' - ' . $orderCommune, ' -');
$requireStopDesk = ($shippingType === 'desk');

$ecotrackProductLabel = trim((string)($extra['product']['name'] ?? ''));
$variantBits = [];
if (!empty($extra['variants']['size'])) {
    $variantBits[] = 'Taille: ' . (string)$extra['variants']['size'];
}
if (!empty($extra['variants']['color'])) {
    $variantBits[] = 'Couleur: ' . (string)$extra['variants']['color'];
}
if (!empty($variantBits)) {
    $ecotrackProductLabel .= ($ecotrackProductLabel !== '' ? ' - ' : '') . implode(' | ', $variantBits);
}
if (!empty($extra['quantity']) && (int)$extra['quantity'] > 1) {
    $ecotrackProductLabel .= ($ecotrackProductLabel !== '' ? ' - ' : '') . 'Qte: ' . (int)$extra['quantity'];
}
if ($ecotrackProductLabel === '') {
    $ecotrackProductLabel = 'Commande #' . (int)$order['id'];
}
?>

<div class="container py-4">

<h3 class="mb-4">
    <?= __('orders.prepare_shipping') ?>
    <span class="text-muted">#<?= (int)$order['id'] ?></span>
</h3>

<form method="POST" id="shipping-form" action="/admin/orders/send-<?= htmlspecialchars($lockedProvider !== '' ? $lockedProvider : 'ecotrack') ?>/<?= (int)$order['id'] ?>">
<?= \Core\System\Csrf::field(); ?>

<!-- PROVIDER -->
<?php if ($lockedProvider === ''): ?>
<div class="mb-3">
    <label class="form-label"><?= __('shipping.provider') ?></label>
    <select class="form-select"
            name="shipping_provider"
            id="shipping_provider"
            required
            onchange="toggleEcotrack(this.value)">
        <option value=""><?= __('actions.choose') ?></option>
        <?php foreach ($providers as $k => $p): ?>
            <option value="<?= $k ?>"><?= htmlspecialchars($p['display_name']) ?></option>
        <?php endforeach; ?>
    </select>
</div>
<?php else: ?>
<input type="hidden" name="shipping_provider" id="shipping_provider" value="<?= htmlspecialchars($lockedProvider) ?>">
<div class="mb-3">
    <label class="form-label"><?= __('shipping.provider') ?></label>
    <input type="text" class="form-control" value="<?= htmlspecialchars($providers[$lockedProvider]['display_name'] ?? strtoupper($lockedProvider)) ?>" readonly>
</div>
<?php endif; ?>

<!-- ================= ECOTRACK ================= -->
<div id="ecotrack-fields" style="display:none">

<h5 class="mt-4 mb-3"><?= __('shipping.ecotrack_data') ?></h5>

<div class="row mb-3">
    <div class="col-md-6">
        <label class="form-label"><?= __('orders.full_name') ?></label>
        <input class="form-control"
               name="nom_client"
               value="<?= htmlspecialchars($order['full_name']) ?>"
               readonly>
    </div>
    <div class="col-md-6">
        <label class="form-label"><?= __('orders.phone') ?></label>
        <input class="form-control"
               name="telephone"
               value="<?= htmlspecialchars($order['phone']) ?>"
               readonly>
    </div>
</div>

<?php if ($quantity !== null): ?>
<div class="mb-3">
    <label class="form-label"><?= __('orders.quantity') ?></label>
    <input class="form-control"
           name="quantite"
           value="<?= (int)$quantity ?>"
           readonly>
</div>
<?php endif; ?>

<div class="mb-3">
    <label class="form-label"><?= __('shipping.ecotrack.contents_description', 'Shipment contents description (ECOTRACK)') ?></label>
    <input class="form-control"
           name="produit"
           value="<?= htmlspecialchars($ecotrackProductLabel) ?>"
           readonly>
    <div class="form-text text-muted small"><?= __('shipping.ecotrack.description_hint', 'This text is sent to Ecotrack to fill the parcel contents on the shipment form.') ?></div>
</div>

<div class="row mb-3">
    <div class="col-md-6">
        <label class="form-label"><?= __('shipping.code_wilaya') ?> (ECOTRACK)</label>
        <input class="form-control"
               id="eco-wilaya-display"
               value="<?= htmlspecialchars($orderWilayaFrench) ?>"
               readonly>
    </div>

    <div class="col-md-6">
        <label class="form-label"><?= __('shipping.city') ?></label>
        <input class="form-control"
               id="eco-commune-display"
               value="<?= htmlspecialchars($orderCommune) ?>"
               readonly>
        <?php if ($requireStopDesk): ?>
            <small class="text-muted">
                <?= __('shipping.ecotrack.stop_desk_only') ?>
            </small>
        <?php endif; ?>
    </div>
</div>

<div class="mb-3">
    <label class="form-label"><?= __('shipping.address') ?></label>
    <textarea class="form-control" name="adresse" id="eco-address" required readonly><?= htmlspecialchars($orderAddress) ?></textarea>
</div>

<div id="eco-auto-alert" class="alert alert-warning border-0 shadow-sm" style="display:none;">
    <div class="d-flex align-items-start">
        <div class="me-2 fs-5">⚠️</div>
        <div>
            <div class="fw-bold mb-1">
                <?= __('shipping.ecotrack.auto_match_failed_title', 'Automatic destination matching failed') ?>
            </div>
            <div class="small">
                <?= __('shipping.ecotrack.auto_match_failed_text', 'We could not automatically match the wilaya or commune with the ECOTRACK list. Please choose them manually from the following lists to ensure the shipment is sent correctly.') ?>
            </div>
        </div>
    </div>
</div>

<div id="eco-manual-wrapper" style="display:none;">
    <div class="row mb-3">
        <div class="col-md-6">
            <label class="form-label"><?= __('shipping.code_wilaya') ?></label>
            <select class="form-select"
                    name="code_wilaya"
                    id="eco-wilaya"
                    required
                    disabled
                    onchange="loadEcoCommunes(this.value, false)">
                <option value=""><?= __('actions.choose') ?></option>
                <?php foreach ($wilayas as $w): ?>
                    <option value="<?= (int)$w['wilaya_id'] ?>">
                        <?= htmlspecialchars($w['wilaya_name']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="col-md-6">
            <label class="form-label"><?= __('shipping.city') ?></label>
            <select class="form-select" name="commune" id="eco-commune" required disabled>
                <option value=""><?= __('actions.choose') ?></option>
            </select>
        </div>
    </div>
</div>

<input type="hidden" name="code_wilaya" id="eco-code-hidden" value="">
<input type="hidden" name="commune" id="eco-commune-hidden" value="">

<div class="row mb-3">
    <div class="col-md-6">
        <label class="form-label"><?= __('shipping.amount') ?></label>
        <input class="form-control"
               type="number"
               id="prepMontantField"
               name="montant"
               value="<?= (float)OrderPricing::effectiveTotal($order) ?>"
               step="0.01" min="0"
               title="<?= __('shipping.amount_editable_hint', 'You can edit this if you agreed a different price with the customer') ?>">
        <div class="form-text text-muted small">
            <?= __('shipping.original_amount', 'Original') ?>: <strong id="prepOriginalAmount"><?= (float)OrderPricing::effectiveTotal($order) ?></strong>
            — <?= __('shipping.amount_editable', 'Edit if negotiated') ?>
        </div>
    </div>
    <div class="col-md-6">
        <label class="form-label"><?= __('shipping.type') ?></label>
        <select class="form-select" name="type" required>
            <option value="1"><?= __('shipping.ecotrack.livraison') ?></option>
            <option value="2"><?= __('shipping.ecotrack.echange') ?></option>
            <option value="3"><?= __('shipping.ecotrack.pickup') ?></option>
            <option value="4"><?= __('shipping.ecotrack.recouvrement') ?></option>
        </select>
    </div>
</div>

<!-- Negotiated price note (shown when amount changes) -->
<div class="mb-3" id="prepNegotiatedWrap" style="display:none">
    <div class="alert alert-warning py-2 small mb-2">
        <i class="bi bi-exclamation-triangle me-1"></i>
        <?= __('shipping.negotiated_changed', 'Amount changed from original. Please add a note explaining the reason.') ?>
    </div>
    <input type="text" class="form-control form-control-sm"
           name="negotiated_note"
           id="prepNegotiatedNote"
           placeholder="<?= __('shipping.negotiated_reason', 'Reason: Customer agreed to pay 1800 instead of 2000...') ?>">
</div>

<script>
(function () {
    const orig = <?= (float)OrderPricing::effectiveTotal($order) ?>;
    const f    = document.getElementById('prepMontantField');
    const wrap = document.getElementById('prepNegotiatedWrap');
    const note = document.getElementById('prepNegotiatedNote');
    const autoPrefix = '<?= __('shipping.negotiated_auto_note', 'Price changed from') ?> ';
    const autoJoiner = ' <?= __('ecotrack.negotiated_to', 'to') ?> ';
    if (!f) return;

    function buildAutoNote(value) {
        return autoPrefix + orig + autoJoiner + value;
    }

    function isAutoGenerated(text) {
        return !text || text.startsWith(autoPrefix);
    }

    function syncNegotiatedState() {
        const raw = String(f.value ?? '').trim();
        const v = raw === '' ? NaN : Number(raw);
        if (!Number.isNaN(v) && Math.abs(v - orig) > 0.01) {
            wrap.style.display = 'block';
            if (note && isAutoGenerated(note.value.trim())) {
                note.value = buildAutoNote(raw);
            }
        } else {
            wrap.style.display = 'none';
            if (note && isAutoGenerated(note.value.trim())) {
                note.value = '';
            }
        }
    }

    f.addEventListener('input', syncNegotiatedState);
    syncNegotiatedState();
})();
</script>

</div>

<button class="btn btn-success mt-4">
    <?= __('shipping.prepare') ?>
</button>

</form>
</div>

<script>
const ecoWantedStateCode = <?= json_encode((string)$stateCode, JSON_UNESCAPED_UNICODE) ?>;
const ecoWantedStateName = <?= json_encode((string)$orderWilayaFrench, JSON_UNESCAPED_UNICODE) ?>;
const ecoWantedCommune   = <?= json_encode((string)$orderCommune, JSON_UNESCAPED_UNICODE) ?>;
const ecoRequireStopDesk = <?= $requireStopDesk ? 'true' : 'false' ?>;
const ecoChooseText      = <?= json_encode(__('actions.choose')) ?>;

function normalizeEcoText(value) {
    return String(value || '')
        .toLowerCase()
        .replace(/[\'’\-_]/g, ' ')
        .replace(/\s+/g, ' ')
        .trim();
}

function setEcoAddress() {
    const wilayaDisplay = document.getElementById('eco-wilaya-display');
    const communeDisplay = document.getElementById('eco-commune-display');
    const address = document.getElementById('eco-address');
    if (!address) return;

    const wilaya = wilayaDisplay ? wilayaDisplay.value.trim() : '';
    const commune = communeDisplay ? communeDisplay.value.trim() : '';
    address.value = [wilaya, commune].filter(Boolean).join(' - ');
}

function setEcoHiddenValues(wilayaCode, communeName) {
    const codeHidden = document.getElementById('eco-code-hidden');
    const communeHidden = document.getElementById('eco-commune-hidden');
    if (codeHidden) codeHidden.value = wilayaCode || '';
    if (communeHidden) communeHidden.value = communeName || '';
}

function showEcoManualFallback(show) {
    const alertBox = document.getElementById('eco-auto-alert');
    const manualWrapper = document.getElementById('eco-manual-wrapper');
    const codeHidden = document.getElementById('eco-code-hidden');
    const communeHidden = document.getElementById('eco-commune-hidden');
    const wilayaSel = document.getElementById('eco-wilaya');
    const communeSel = document.getElementById('eco-commune');

    if (alertBox) alertBox.style.display = show ? 'block' : 'none';
    if (manualWrapper) manualWrapper.style.display = show ? 'block' : 'none';

    if (codeHidden) codeHidden.disabled = show;
    if (communeHidden) communeHidden.disabled = show;

    if (wilayaSel) wilayaSel.disabled = !show;
    if (communeSel) communeSel.disabled = !show;
}

function syncManualDisplays() {
    const wilayaSel = document.getElementById('eco-wilaya');
    const communeSel = document.getElementById('eco-commune');
    const wilayaDisplay = document.getElementById('eco-wilaya-display');
    const communeDisplay = document.getElementById('eco-commune-display');

    if (wilayaSel && wilayaDisplay && wilayaSel.selectedIndex > 0) {
        wilayaDisplay.value = wilayaSel.options[wilayaSel.selectedIndex].text.trim();
    }
    if (communeSel && communeDisplay && communeSel.selectedIndex > 0) {
        communeDisplay.value = communeSel.options[communeSel.selectedIndex].text.trim();
    }

    setEcoAddress();
}

function toggleEcotrack(value) {
    const ecoFields = document.getElementById('ecotrack-fields');
    const shippingForm = document.getElementById('shipping-form');

    const providerActions = {
        'ecotrack':   '/admin/orders/send-ecotrack/<?= (int)$order['id'] ?>',
        'dhd':        '/admin/orders/send-dhd/<?= (int)$order['id'] ?>',
        'zr_express': '/admin/orders/send-zrexpress/<?= (int)$order['id'] ?>',
        'yalidine':   '/admin/orders/send-yalidine/<?= (int)$order['id'] ?>',
        'maystro':    '/admin/orders/send-maystro/<?= (int)$order['id'] ?>',
    };
    const orderId = <?= (int)$order['id'] ?>;

    if (value === 'ecotrack' || value === 'dhd') {
        if (ecoFields) ecoFields.style.display = 'block';
        if (shippingForm && providerActions[value]) {
            shippingForm.action = providerActions[value];
        }
        autoMatchEcotrack();
        return;
    }

    if (ecoFields) ecoFields.style.display = 'none';

    if (!value) return;

    const redirectMap = {
        'zr_express': 'prepare-zrexpress',
        'yalidine':   'prepare-yalidine',
        'maystro':    'prepare-maystro',
    };
    const page = redirectMap[value] || ('prepare-' + value);
    window.location.href = '/admin/orders/' + page + '/' + orderId;
}

function autoMatchEcotrack() {
    const wilayaSel = document.getElementById('eco-wilaya');
    if (!wilayaSel) return;

    showEcoManualFallback(false);
    setEcoHiddenValues('', '');

    const wantedCode = String(ecoWantedStateCode || '').replace(/^0+/, '');
    const wantedName = normalizeEcoText(ecoWantedStateName);
    let foundWilaya = false;

    Array.from(wilayaSel.options).forEach(opt => {
        const optValue = String(opt.value || '').replace(/^0+/, '');
        const optText = normalizeEcoText(opt.textContent || '');

        if (!foundWilaya && wantedCode && optValue === wantedCode) {
            opt.selected = true;
            foundWilaya = true;
            return;
        }

        if (!foundWilaya && wantedName && optText === wantedName) {
            opt.selected = true;
            foundWilaya = true;
        }
    });

    if (!foundWilaya || !wilayaSel.value) {
        showEcoManualFallback(true);
        return;
    }

    loadEcoCommunes(wilayaSel.value, true);
}

function loadEcoCommunes(wilayaId, autoMode) {
    const communeSel = document.getElementById('eco-commune');
    const wilayaSel = document.getElementById('eco-wilaya');
    if (!communeSel) return;

    communeSel.innerHTML = `<option value="">${ecoChooseText}</option>`;
    communeSel.disabled = true;

    if (!wilayaId) {
        if (autoMode) showEcoManualFallback(true);
        return;
    }

    const url = new URL('/admin/orders/ecotrack/communes', window.location.origin);
    url.searchParams.set('wilaya_id', wilayaId);
    if (ecoRequireStopDesk) {
        url.searchParams.set('stop_desk', '1');
    }

    fetch(url.toString())
        .then(r => r.json())
        .then(data => {
            if (!Array.isArray(data)) {
                if (autoMode) showEcoManualFallback(true);
                return;
            }

            let foundCommune = false;
            const wantedCommune = normalizeEcoText(ecoWantedCommune);

            data.forEach(c => {
                const communeName = String(c.nom || '');
                const opt = document.createElement('option');
                opt.value = communeName;
                opt.textContent = communeName;

                if (!foundCommune && wantedCommune && normalizeEcoText(communeName) === wantedCommune) {
                    opt.selected = true;
                    foundCommune = true;
                }

                communeSel.appendChild(opt);
            });

            communeSel.disabled = false;

            if (autoMode) {
                if (foundCommune) {
                    const wilayaText = wilayaSel && wilayaSel.selectedIndex > 0
                        ? wilayaSel.options[wilayaSel.selectedIndex].text.trim()
                        : '';
                    document.getElementById('eco-wilaya-display').value = wilayaText;
                    document.getElementById('eco-commune-display').value = communeSel.value;
                    setEcoHiddenValues(wilayaId, communeSel.value);
                    showEcoManualFallback(false);
                    setEcoAddress();
                } else {
                    showEcoManualFallback(true);
                }
            } else {
                syncManualDisplays();
            }
        })
        .catch(() => {
            if (autoMode) {
                showEcoManualFallback(true);
            }
        });
}

document.addEventListener('DOMContentLoaded', function () {
    const provider = document.getElementById('shipping_provider');
    const lockedProvider = <?= json_encode($lockedProvider) ?>;
    const wilayaSel = document.getElementById('eco-wilaya');
    const communeSel = document.getElementById('eco-commune');

    if (wilayaSel) {
        wilayaSel.addEventListener('change', function () {
            loadEcoCommunes(this.value, false);
            const wilayaDisplay = document.getElementById('eco-wilaya-display');
            if (wilayaDisplay && this.selectedIndex > 0) {
                wilayaDisplay.value = this.options[this.selectedIndex].text.trim();
            }
            setEcoAddress();
        });
    }

    if (communeSel) {
        communeSel.addEventListener('change', function () {
            const communeDisplay = document.getElementById('eco-commune-display');
            if (communeDisplay) {
                communeDisplay.value = this.value || '';
            }
            setEcoAddress();
        });
    }

    setEcoAddress();

    const initialProvider = lockedProvider || (provider ? provider.value : '');
    if (initialProvider) {
        toggleEcotrack(initialProvider);
    }
});
</script>
