<?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'] ?? [];
$quantity = $extra['quantity'] ?? null;
$shippingType = $shipping['type'] ?? null;

$destination = $shipping['destination'] ?? [];

/* ===== Algeria States Map (Code → Name) ===== */
$dzStates = [
    1=>'أدرار',2=>'الشلف',3=>'الأغواط',4=>'أم البواقي',5=>'باتنة',6=>'بجاية',
    7=>'بسكرة',8=>'بشار',9=>'البليدة',10=>'البويرة',11=>'تمنراست',
    12=>'تبسة',13=>'تلمسان',14=>'تيارت',15=>'تيزي وزو',16=>'الجزائر',
    17=>'الجلفة',18=>'جيجل',19=>'سطيف',20=>'سعيدة',21=>'سكيكدة',
    22=>'سيدي بلعباس',23=>'عنابة',24=>'قالمة',25=>'قسنطينة',26=>'المدية',
    27=>'مستغانم',28=>'المسيلة',29=>'معسكر',30=>'ورقلة',31=>'وهران',
    32=>'البيض',33=>'إليزي',34=>'برج بوعريريج',35=>'بومرداس',
    36=>'الطارف',37=>'تندوف',38=>'تيسمسيلت',39=>'الوادي',40=>'خنشلة',
    41=>'سوق أهراس',42=>'تيبازة',43=>'ميلة',44=>'عين الدفلى',
    45=>'النعامة',46=>'عين تموشنت',47=>'غرداية',48=>'غليزان',
    49=>'تيميمون',50=>'برج باجي مختار',51=>'أولاد جلال',
    52=>'بني عباس',53=>'عين صالح',54=>'عين قزام',
    55=>'تقرت',56=>'جانت',57=>'المغير',58=>'المنيعة'
];

$stateCode    = $destination['state_code'] ?? null;
$orderWilaya  = $dzStates[(int)$stateCode] ?? '';
$orderCommune = $destination['city_name'] ?? '';


/* =============================
   Load DHD integration
============================= */
$eco = $integrationModel->getByProvider('dhd');
$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) ?: [];
}

$requireStopDesk = ($shippingType === 'desk');
?>

<div class="container py-4">

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

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

<!-- PROVIDER -->
<div class="mb-3">
    <label class="form-label"><?= __('shipping.provider') ?></label>
    <select class="form-select"
            name="shipping_provider"
            id="shipping_provider"
            required
            onchange="toggleDHD(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>

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

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

<!-- ✅ ORDER LOCATION (READ ONLY – FROM ORDER) -->
<div class="row mb-3">
    <div class="col-md-6">
        <label class="form-label"><?= __('shipping.code_wilaya') ?></label>
        <input class="form-control"
               value="<?= htmlspecialchars($orderWilaya) ?>"
               readonly>
    </div>
    <div class="col-md-6">
        <label class="form-label"><?= __('shipping.city') ?></label>
        <input class="form-control"
               value="<?= htmlspecialchars($orderCommune) ?>"
               readonly>
    </div>
</div>

<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; ?>

<!-- ECOTRACK WILAYA / COMMUNE -->
<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
                onchange="loadEcoCommunes(this.value)">
            <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>
        <?php if ($requireStopDesk): ?>
            <small class="text-muted">
                <?= __('shipping.dhd.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" required></textarea>
</div>

<div class="row mb-3">
    <div class="col-md-6">
        <label class="form-label"><?= __('shipping.amount') ?></label>
        <input class="form-control"
               type="number"
               name="montant"
               value="<?= (float)OrderPricing::effectiveTotal($order) ?>"
               readonly>
    </div>
    <div class="col-md-6">
        <label class="form-label"><?= __('shipping.type') ?></label>
        <select class="form-select" name="type" required>
            <option value="1"><?= __('shipping.dhd.livraison') ?></option>
            <option value="2"><?= __('shipping.dhd.echange') ?></option>
            <option value="3"><?= __('shipping.dhd.pickup') ?></option>
            <option value="4"><?= __('shipping.dhd.recouvrement') ?></option>
        </select>
    </div>
</div>

</div>

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

</form>
</div>

<script>
function toggleDHD(value) {
    const ecoFields = document.getElementById('dhd-fields');
    const orderId = <?= (int)$order['id'] ?>;

    if (value === 'dhd') {
        if (ecoFields) ecoFields.style.display = 'block';
        return;
    }

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

    if (!value) return;

    // ✅ redirect إلى صفحة شركة الشحن المختارة
    window.location.href = `/admin/orders/prepare-${value}/${orderId}`;
}

function loadEcoCommunes(wilayaId) {

    const communeSel = document.getElementById('eco-commune');
    if (!communeSel) return;

    const chooseText  = <?= json_encode(__('actions.choose')) ?>;
    const requireDesk = <?= $requireStopDesk ? 'true' : 'false' ?>;

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

    if (!wilayaId) return;

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

    fetch(url.toString())
        .then(r => r.json())
        .then(data => {
            if (Array.isArray(data)) {
                data.forEach(c => {
                    const opt = document.createElement('option');
                    opt.value = c.nom;
                    opt.textContent = c.nom;
                    communeSel.appendChild(opt);
                });
                communeSel.disabled = false;
            }
        });
}
</script>