<?php
use Core\App\Support\OrderPricing;
use Core\App\Integrations\Shipping\MaystroClient;
use Core\App\Models\ShippingIntegrationModel;
use Core\App\Services\MaystroLocationService;

$extra        = is_array($order['extra']) ? $order['extra'] : json_decode($order['extra'] ?? '{}', true);
$shipping     = $extra['shipping'] ?? [];
$destination  = $shipping['destination'] ?? [];
$shippingType = $shipping['type'] ?? 'home';
$typeIntMap   = ['home' => 1, 'desk' => 2, 'pickup' => 3];
$deliveryTypeInt = $typeIntMap[$shippingType] ?? 1;

$stateCode   = \Core\App\Support\DzLocation::normalizeCode((string)($destination['state_code'] ?? ''));
$stateName   = trim((string)($destination['state_name'] ?? ''));
$communeName = trim((string)($destination['city_name'] ?? ''));
$communeId   = (int)($destination['city_id'] ?? 0);

$maystroLocations = new MaystroLocationService();
$wilayasResult = $maystroLocations->getWilayas();
$wilayas = array_values((array)($wilayasResult['data'] ?? []));

$selectedWilaya = $maystroLocations->findWilayaBySavedState($stateCode, $stateName);
if ($selectedWilaya) {
    $wilayaId = (int)($selectedWilaya['id'] ?? 0);
    $stateCode = (string)($selectedWilaya['code'] ?? $stateCode);
    if ($stateName === '') {
        $stateName = (string)($selectedWilaya['name'] ?? '');
    }
} else {
    $wilayaId = (int)ltrim($stateCode, '0');
}

$communes = [];
$pickupPoints = [];
$integration  = (new ShippingIntegrationModel())->getByProvider('maystro');
if ($wilayaId > 0) {
    $communesRes = $maystroLocations->getCommunes($wilayaId);
    if (!empty($communesRes['success']) && is_array($communesRes['data'] ?? null)) {
        $communes = (array)$communesRes['data'];
        if ($communeName === '' && $communeId > 0) {
            foreach ($communes as $cm) {
                if ((int)($cm['id'] ?? 0) === $communeId) {
                    $communeName = (string)($cm['name'] ?? '');
                    break;
                }
            }
        }
    }
}

if ($integration && !empty($integration['api_token']) && !empty($integration['is_active'])) {
    $client = MaystroClient::fromIntegration($integration);
    if ($communeId > 0) {
        $ppRes  = $client->getPickupPoints($communeId);
        if (!empty($ppRes['success'])) {
            $pickupPoints = array_values(array_filter((array)($ppRes['data'] ?? []), static function ($pt) use ($communeId) {
                return (int)($pt['commune'] ?? 0) === $communeId;
            }));
        }
    }
}

if (empty($wilayas) && $wilayaId > 0) {
    $wilayas[] = [
        'id' => $wilayaId,
        'code' => $stateCode !== '' ? $stateCode : str_pad((string)$wilayaId, 2, '0', STR_PAD_LEFT),
        'name' => $stateName !== '' ? $stateName : ('Wilaya #' . $wilayaId),
        'ar_name' => '',
    ];
}

$autoAddress  = trim($stateName . ($communeName !== '' ? ' - ' . $communeName : ''), ' -');
if ($autoAddress === '') {
    $autoAddress = (string)($order['address'] ?? '');
}

$effectiveTotal = OrderPricing::effectiveTotal($order);
$productName    = (string)($extra['product']['name'] ?? ('Commande #' . (int)$order['id']));
$quantity       = max(1, (int)($extra['quantity'] ?? 1));
$hasTracking    = !empty($shipping['tracking']) && ($shipping['provider'] ?? '') === 'maystro';
$pickupPointSelected = (int)($shipping['pickup_point'] ?? 0);
$errorMessages  = (array)($shipping['error_msgs'] ?? []);
$errorCodes     = array_filter(array_map('intval', (array)($shipping['error_codes'] ?? [])));
?>

<div class="container py-4">

    <div class="d-flex align-items-center gap-3 mb-4">
        <img src="/admin/assets/img/maystro.png" height="36" alt="Maystro">
        <div>
            <h3 class="mb-0">
                <?= __('orders.prepare_shipping', 'Prepare Shipping') ?>
                <span class="text-muted fs-5">#<?= (int)$order['id'] ?></span>
            </h3>
            <small class="text-muted"><?= __('shipping.provider_maystro', 'Maystro Delivery') ?></small>
        </div>
        <?php if ($hasTracking): ?>
        <span class="badge bg-success ms-auto fs-6">
            <i class="bi bi-check-circle me-1"></i>
            <?= __('shipping.already_shipped', 'Shipped') ?>: <?= htmlspecialchars($shipping['tracking']) ?>
        </span>
        <?php endif; ?>
    </div>

    <?php if ($errorMessages): ?>
    <div class="alert alert-warning border shadow-sm">
        <div class="d-flex align-items-start gap-3">
            <i class="bi bi-exclamation-triangle-fill fs-4"></i>
            <div class="flex-grow-1">
                <div class="fw-bold mb-1"><?= __('shipping.maystro_fix_order_title', 'Maystro rejected this shipment. You can correct the destination and resend the order.') ?></div>
                <ul class="mb-0 ps-3">
                    <?php foreach ($errorMessages as $msg): ?>
                        <li><?= htmlspecialchars((string)$msg) ?></li>
                    <?php endforeach; ?>
                </ul>
                <?php if ($errorCodes): ?>
                    <div class="small text-muted mt-2"><?= __('shipping.error_codes', 'Error codes') ?>: <?= htmlspecialchars(implode(', ', $errorCodes)) ?></div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <?php if ($hasTracking): ?>
    <div class="alert alert-info d-flex align-items-center gap-3">
        <i class="bi bi-info-circle-fill fs-5"></i>
        <div>
            <?= __('shipping.already_shipped_msg', 'This order has already been shipped via Maystro.') ?>
            <strong><?= htmlspecialchars($shipping['tracking']) ?></strong>
        </div>
        <div class="ms-auto d-flex gap-2">
            <a href="/admin/orders/maystro/label/<?= (int)$order['id'] ?>" class="btn btn-outline-primary btn-sm" target="_blank">
                <i class="bi bi-printer me-1"></i><?= __('shipping.print_label', 'Print Label') ?>
            </a>
            <a href="/admin/orders/view/<?= (int)$order['id'] ?>" class="btn btn-secondary btn-sm">
                <?= __('actions.back', 'Back') ?>
            </a>
        </div>
    </div>
    <?php else: ?>

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

        <div class="card mb-4">
            <div class="card-header fw-bold">
                <i class="bi bi-person me-1"></i>
                <?= __('orders.customer_info', 'Customer Information') ?>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-md-4">
                        <label class="form-label"><?= __('orders.full_name', 'Full Name') ?></label>
                        <input type="text" class="form-control" name="customer_name" value="<?= htmlspecialchars($order['full_name'] ?? '') ?>" required>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label"><?= __('orders.phone', 'Phone') ?></label>
                        <input type="text" class="form-control" name="customer_phone" value="<?= htmlspecialchars($order['phone'] ?? '') ?>" required>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label"><?= __('orders.phone2', 'Phone 2') ?> <span class="text-muted small">(<?= __('actions.optional', 'optional') ?>)</span></label>
                        <input type="text" class="form-control" name="customer_phone2" value="<?= htmlspecialchars((string)($shipping['customer_phone2'] ?? '')) ?>">
                    </div>
                </div>

                <div class="row g-3 mt-1">
                    <div class="col-md-6">
                        <label class="form-label"><?= __('orders.state', 'Wilaya') ?></label>
                        <select class="form-select" name="wilaya_id" id="maystroWilaya" onchange="loadMaystroCommunes(this.value)">
                            <option value=""><?= __('actions.choose', 'Choose...') ?></option>
                            <?php foreach ($wilayas as $wl): ?>
                                <option value="<?= (int)$wl['id'] ?>" data-code="<?= htmlspecialchars($wl['code']) ?>" data-name="<?= htmlspecialchars($wl['name']) ?>" <?= (int)$wl['id'] === $wilayaId ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($wl['name']) ?><?php if ($wl['ar_name'] !== ''): ?> — <?= htmlspecialchars($wl['ar_name']) ?><?php endif; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <div class="form-text"><?= __('shipping.maystro_location_hint', 'You can correct the wilaya and commune here before sending the shipment.') ?></div>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label"><?= __('orders.city', 'Commune') ?></label>
                        <select class="form-select" name="commune_id" id="maystroCommune" onchange="onMaystroCommuneChange()" <?= $wilayaId > 0 ? '' : 'disabled' ?>>
                            <option value=""><?= __('actions.choose', 'Choose...') ?></option>
                            <?php foreach ($communes as $cm): ?>
                                <option value="<?= (int)($cm['id'] ?? 0) ?>" data-name="<?= htmlspecialchars((string)($cm['name'] ?? '')) ?>" <?= (int)($cm['id'] ?? 0) === $communeId ? 'selected' : '' ?>>
                                    <?= htmlspecialchars((string)($cm['name'] ?? '')) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <input type="hidden" name="state_code" id="maystroStateCode" value="<?= htmlspecialchars($stateCode) ?>">
                <input type="hidden" name="state_name" id="maystroStateName" value="<?= htmlspecialchars($stateName) ?>">
                <input type="hidden" name="commune_name" id="maystroCommuneName" value="<?= htmlspecialchars($communeName) ?>">
            </div>
        </div>

        <div class="card mb-4">
            <div class="card-header fw-bold">
                <i class="bi bi-truck me-1"></i>
                <?= __('shipping.delivery_options', 'Delivery Options') ?>
            </div>
            <div class="card-body">
                <div class="row g-3 align-items-end">
                    <div class="col-md-4">
                        <label class="form-label"><?= __('shipping.delivery_type', 'Delivery Type') ?></label>
                        <select class="form-select" name="delivery_type" id="maystroDeliveryType" onchange="toggleMaystroPickup(this.value); updateMaystroPrice(); if(this.value==='3'){loadMaystroPickupPoints();}">
                            <option value="1" <?= $deliveryTypeInt === 1 ? 'selected' : '' ?>>🏠 <?= __('shipping.home', 'Home Delivery') ?></option>
                            <option value="2" <?= $deliveryTypeInt === 2 ? 'selected' : '' ?>>🏢 <?= __('shipping.desk', 'Stop Desk') ?></option>
                            <option value="3" <?= $deliveryTypeInt === 3 ? 'selected' : '' ?>>📦 <?= __('shipping.pickup', 'Pickup Point') ?></option>
                        </select>
                    </div>
                    <div class="col-md-4 d-flex align-items-end pb-1">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="express" value="1" id="maystroExpress" <?= !empty($shipping['express']) ? 'checked' : '' ?> onchange="updateMaystroPrice()">
                            <label class="form-check-label" for="maystroExpress">
                                ⚡ <?= __('shipping.express', 'Express Delivery') ?>
                                <span class="text-muted small d-block"><?= __('shipping.express_hint', 'Higher price may apply') ?></span>
                            </label>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label"><?= __('shipping.delivery_price', 'Estimated Delivery Price') ?></label>
                        <div class="input-group">
                            <input type="text" class="form-control bg-light" id="maystroDeliveryPricePreview" value="—" readonly>
                            <span class="input-group-text">DA</span>
                        </div>
                        <div class="form-text text-muted" id="maystroDeliveryPriceHint"><?= __('shipping.from_api', 'Loaded from Maystro price list') ?></div>
                    </div>
                </div>

                <div id="maystroPickupWrap" class="mt-3" style="display:<?= $deliveryTypeInt === 3 ? 'block' : 'none' ?>">
                    <label class="form-label"><?= __('shipping.pickup_point', 'Pickup Point') ?> *</label>
                    <select class="form-select" name="pickup_point" id="maystroPickupSelect">
                        <option value=""><?= __('actions.choose', 'Choose...') ?></option>
                        <?php foreach ($pickupPoints as $pt):
                            $ppId = (int)($pt['pickup_point'] ?? $pt['id'] ?? 0);
                            $ppLabel = trim((string)($pt['name_lt'] ?? $pt['name'] ?? ''));
                            $ppAr = trim((string)($pt['name_ar'] ?? ''));
                        ?>
                            <option value="<?= $ppId ?>" <?= $pickupPointSelected === $ppId ? 'selected' : '' ?>>
                                <?= htmlspecialchars($ppLabel !== '' ? $ppLabel : $ppAr) ?><?php if ($ppAr !== '' && $ppAr !== $ppLabel): ?> — <?= htmlspecialchars($ppAr) ?><?php endif; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <div class="form-text" id="maystroPickupHint">
                        <?= empty($pickupPoints) ? __('shipping.pickup_points_loading', 'No pickup points loaded – check Maystro configuration.') : __('shipping.pickup_points_ready', 'Pickup points loaded for the selected commune.') ?>
                    </div>
                </div>
            </div>
        </div>

        <div class="card mb-4">
            <div class="card-header fw-bold">
                <i class="bi bi-box-seam me-1"></i>
                <?= __('shipping.shipment_data', 'Shipment Data') ?>
            </div>
            <div class="card-body">
                <div class="mb-3">
                    <label class="form-label"><?= __('shipping.destination_text', 'Delivery Address') ?> <span class="text-muted small">(<?= __('shipping.address_hint', 'Street / area for driver') ?>)</span></label>
                    <input type="text" class="form-control" name="address" value="<?= htmlspecialchars($autoAddress) ?>" required>
                </div>

                <div class="row g-3">
                    <div class="col-md-5">
                        <label class="form-label"><?= __('shipping.amount', 'Amount to Collect') ?> (DA)</label>
                        <input type="number" class="form-control" name="amount" id="maystroAmount" value="<?= (float)$effectiveTotal ?>" min="0" step="1" required>
                        <div class="form-text"><?= __('shipping.original_amount', 'Original') ?>: <strong><?= number_format($effectiveTotal, 0) ?> DA</strong> — <?= __('shipping.amount_editable', 'Editable if negotiated') ?></div>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label"><?= __('orders.quantity', 'Quantity') ?></label>
                        <input type="number" class="form-control" name="quantity" value="<?= $quantity ?>" min="1" required>
                    </div>
                    <div class="col-12" id="maystroNegotiatedWrap" 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. Add a note explaining the reason.') ?></div>
                        <input type="text" class="form-control form-control-sm" name="negotiated_note" id="maystroNegotiatedNote" placeholder="<?= __('shipping.negotiated_reason', 'Reason: Customer agreed to pay 1800 instead of 2000...') ?>">
                    </div>
                </div>

                <div class="mb-3 mt-3">
                    <label class="form-label"><?= __('shipping.product_description', 'Product / Contents Description') ?></label>
                    <input type="text" class="form-control" name="description" value="<?= htmlspecialchars($productName) ?>" required>
                    <div class="form-text text-muted"><?= __('shipping.maystro.description_hint', 'This label appears on the Maystro shipment. Must be unique per product.') ?></div>
                </div>

                <div class="mb-3">
                    <label class="form-label"><?= __('shipping.note_to_driver', 'Note to Driver') ?> <span class="text-muted small">(<?= __('actions.optional', 'optional') ?>)</span></label>
                    <textarea class="form-control" name="note" rows="2" placeholder="<?= __('shipping.note_to_driver_placeholder', 'e.g. Call before delivery, leave at door...') ?>"></textarea>
                </div>
            </div>
        </div>

        <div class="d-flex gap-2 flex-wrap">
            <button type="submit" class="btn btn-success px-4"><i class="bi bi-send me-1"></i><?= __('shipping.send_to_maystro', 'Send to Maystro') ?></button>
            <a href="/admin/orders/view/<?= (int)$order['id'] ?>" class="btn btn-secondary"><i class="bi bi-arrow-left me-1"></i><?= __('actions.cancel', 'Cancel') ?></a>
        </div>
    </form>

    <?php endif; ?>
</div>

<script>
let maystroApiPrices = {};

function syncMaystroHiddenLocationFields() {
    const wilaya = document.getElementById('maystroWilaya');
    const commune = document.getElementById('maystroCommune');
    const selectedWilaya = wilaya ? wilaya.options[wilaya.selectedIndex] : null;
    const selectedCommune = commune ? commune.options[commune.selectedIndex] : null;

    document.getElementById('maystroStateCode').value = selectedWilaya ? (selectedWilaya.dataset.code || '') : '';
    document.getElementById('maystroStateName').value = selectedWilaya ? (selectedWilaya.dataset.name || selectedWilaya.text || '') : '';
    document.getElementById('maystroCommuneName').value = selectedCommune ? (selectedCommune.dataset.name || selectedCommune.text || '') : '';
}

function onMaystroCommuneChange() {
    syncMaystroHiddenLocationFields();
    maystroApiPrices = {};
    updateMaystroPrice();
    loadMaystroDeliveryPrices();
    loadMaystroPickupPoints();
}

function loadMaystroCommunes(wilayaId) {
    const commune = document.getElementById('maystroCommune');
    if (!commune) return;
    commune.innerHTML = '<option value=""><?= __('actions.choose', 'Choose...') ?></option>';
    commune.disabled = true;
    syncMaystroHiddenLocationFields();
    if (!wilayaId) {
        onMaystroCommuneChange();
        return;
    }
    fetch('/admin/orders/maystro/communes?wilaya_id=' + encodeURIComponent(wilayaId), {credentials:'same-origin'})
        .then(r => r.json())
        .then(rows => {
            (Array.isArray(rows) ? rows : []).forEach(row => {
                const opt = document.createElement('option');
                opt.value = row.id || '';
                opt.textContent = row.name || '';
                opt.dataset.name = row.name || '';
                commune.appendChild(opt);
            });
            commune.disabled = false;
            syncMaystroHiddenLocationFields();
        })
        .catch(() => {
            commune.disabled = false;
        });
}

function loadMaystroDeliveryPrices() {
    const commune = document.getElementById('maystroCommune');
    const communeId = commune ? parseInt(commune.value || '0', 10) : 0;
    if (!communeId) return;
    fetch('/admin/orders/maystro/delivery-prices?commune_id=' + communeId, { credentials: 'same-origin' })
        .then(r => r.json())
        .then(res => {
            maystroApiPrices = {};
            if (!res.success || !Array.isArray(res.data)) {
                updateMaystroPrice();
                return;
            }
            res.data.forEach(opt => {
                const t = String(opt.type || '').toLowerCase();
                if (t === 'home') maystroApiPrices.home = opt.price ?? null;
                if (t === 'stopdesk') maystroApiPrices.stopdesk = opt.price ?? null;
                if (t === 'pickup') maystroApiPrices.pickup = opt.price ?? null;
            });
            updateMaystroPrice();
        })
        .catch(() => {});
}

function loadMaystroPickupPoints() {
    const type = document.getElementById('maystroDeliveryType');
    const commune = document.getElementById('maystroCommune');
    const select = document.getElementById('maystroPickupSelect');
    const hint = document.getElementById('maystroPickupHint');
    if (!type || !commune || !select) return;
    if (type.value !== '3') return;
    const communeId = parseInt(commune.value || '0', 10);
    select.innerHTML = '<option value=""><?= __('actions.choose', 'Choose...') ?></option>';
    if (!communeId) {
        if (hint) hint.textContent = '<?= __('shipping.pickup_point_select_commune', 'Choose a commune first to load pickup points.') ?>';
        return;
    }
    if (hint) hint.textContent = '<?= __('shipping.pickup_points_fetching', 'Loading pickup points...') ?>';
    fetch('/admin/orders/maystro/pickup-points?commune_id=' + communeId, {credentials:'same-origin'})
        .then(r => r.json())
        .then(res => {
            const rows = Array.isArray(res.data) ? res.data : [];
            rows.forEach(row => {
                const val = row.pickup_point || row.id || '';
                if (!val) return;
                const opt = document.createElement('option');
                opt.value = val;
                opt.textContent = [row.name_lt || row.name || '', row.name_ar || ''].filter(Boolean).join(' — ');
                select.appendChild(opt);
            });
            if (hint) {
                hint.textContent = rows.length
                    ? '<?= __('shipping.pickup_points_ready', 'Pickup points loaded for the selected commune.') ?>'
                    : '<?= __('shipping.pickup_points_loading', 'No pickup points loaded – check Maystro configuration.') ?>';
            }
        })
        .catch(() => {
            if (hint) hint.textContent = '<?= __('shipping.pickup_points_loading', 'No pickup points loaded – check Maystro configuration.') ?>';
        });
}

function updateMaystroPrice() {
    const typeSelect = document.getElementById('maystroDeliveryType');
    const express = document.getElementById('maystroExpress');
    const preview = document.getElementById('maystroDeliveryPricePreview');
    const hint = document.getElementById('maystroDeliveryPriceHint');
    if (!typeSelect || !preview) return;

    let price = null;
    if (typeSelect.value === '1') price = maystroApiPrices.home ?? null;
    if (typeSelect.value === '2') price = maystroApiPrices.stopdesk ?? null;
    if (typeSelect.value === '3') price = maystroApiPrices.pickup ?? maystroApiPrices.stopdesk ?? null;

    if (price !== null) {
        preview.value = Number(price).toLocaleString('fr-DZ');
        if (hint) hint.textContent = '<?= __('shipping.from_api', 'From Maystro price list') ?>' + (express && express.checked ? ' (Express ++)' : '');
    } else {
        preview.value = '—';
        if (hint) hint.textContent = '<?= __('shipping.price_not_available', 'Price not available for this commune') ?>';
    }
}

function toggleMaystroPickup(val) {
    const wrap = document.getElementById('maystroPickupWrap');
    if (wrap) wrap.style.display = val === '3' ? 'block' : 'none';
    if (val === '3') loadMaystroPickupPoints();
}

(function () {
    syncMaystroHiddenLocationFields();
    loadMaystroDeliveryPrices();
    if (document.getElementById('maystroDeliveryType')?.value === '3') {
        loadMaystroPickupPoints();
    }

    const orig = <?= (float)$effectiveTotal ?>;
    const amtField = document.getElementById('maystroAmount');
    const wrap = document.getElementById('maystroNegotiatedWrap');
    const note = document.getElementById('maystroNegotiatedNote');
    const autoPrefix = '<?= __('shipping.negotiated_auto_note', 'Price changed from') ?> ';
    const autoJoiner = ' <?= __('ecotrack.negotiated_to', 'to') ?> ';
    if (amtField) {
        function buildAutoNote(value) {
            return autoPrefix + orig + autoJoiner + value;
        }

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

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

        amtField.addEventListener('input', syncMaystroNegotiatedState);
        syncMaystroNegotiatedState();
    }
})();
</script>
