<?php
use Core\App\Support\OrderPricing;
use Core\App\Support\ShippingSettings;
/**
 * Prepare Shipping – Yalidine
 * API Docs: https://api.yalidine.app/
 */

$extra       = is_array($order['extra']) ? $order['extra'] : json_decode($order['extra'], true);
$shipping    = $extra['shipping'] ?? [];
$destination = $shipping['destination'] ?? [];
$deliveryType = $shipping['type'] ?? 'home';
$isStopDesk  = ($deliveryType === 'desk');
$shippingSettings = ShippingSettings::load();
$originStateCode = (string)($shippingSettings['origin']['state_code'] ?? '');
$originStateId = (int)ltrim($originStateCode, '0');

// جلب قائمة الولايات من Yalidine
$integrationModel = new \Core\App\Models\ShippingIntegrationModel();
$yalidine = $integrationModel->getByProvider('yalidine');
$wilayas  = [];

if ($yalidine && !empty($yalidine['is_active'])) {
    $client  = new \Core\App\Integrations\Shipping\YalidineClient(
        $yalidine['api_token'],
        $yalidine['api_id'] ?? ''
    );
    $wRes    = $client->getWilayas();
    $wilayas = $wRes['data']['data'] ?? [];
}
?>

<div class="container py-4">

<h3 class="mb-4">
    <?= __('orders.prepare_shipping', 'Prepare Shipping') ?>
    <span class="text-muted">#<?= (int)$order['id'] ?></span>
    <small class="d-block text-muted mt-1 fs-6">
        <i class="bi bi-truck me-1"></i> Yalidine
    </small>
</h3>

<form method="POST" action="/admin/orders/send-yalidine/<?= (int)$order['id'] ?>">
    <?= \Core\System\Csrf::field() ?>
    <input type="hidden" name="shipping_provider" value="yalidine">

    <!-- معلومات الزبون -->
    <div class="card mb-4">
        <div class="card-header"><strong><?= __('orders.customer_info', 'Customer Info') ?></strong></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" value="<?= htmlspecialchars($order['full_name']) ?>" readonly>
                </div>
                <div class="col-md-4">
                    <label class="form-label"><?= __('orders.phone', 'Phone') ?></label>
                    <input type="text" class="form-control" value="<?= htmlspecialchars($order['phone']) ?>" readonly>
                </div>
                <div class="col-md-4">
                    <label class="form-label"><?= __('shipping.delivery_type', 'Delivery Type') ?></label>
                    <input type="text" class="form-control"
                           value="<?= $isStopDesk ? __('shipping.desk','Stop Desk') : __('shipping.home','Home Delivery') ?>" readonly>
                </div>
            </div>
        </div>
    </div>

    <!-- بيانات الشحنة -->
    <div class="card mb-4">
        <div class="card-header"><strong><?= __('shipping.yalidine_data', 'Yalidine Shipment Data') ?></strong></div>
        <div class="card-body">
            <div class="row g-3">

                <!-- من ولاية -->
                <div class="col-md-4">
                    <label class="form-label"><?= __('shipping.from_wilaya', 'From Wilaya') ?></label>
                    <select name="from_wilaya_id" class="form-select" required>
                        <option value=""><?= __('actions.choose', 'Choose') ?></option>
                        
                        <?php foreach ($wilayas as $w): ?>
                            <option value="<?= (int)$w['id'] ?>" <?= ($originStateId > 0 && $originStateId === (int)$w['id']) ? 'selected' : '' ?>><?= htmlspecialchars($w['name'] ?? '') ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <!-- إلى ولاية -->
                <div class="col-md-4">
                    <label class="form-label"><?= __('shipping.to_wilaya', 'To Wilaya') ?> *</label>
                    <select name="to_wilaya_id" id="ya_wilaya" class="form-select" required onchange="loadYalidineCommunes(this.value)">
                        <option value=""><?= __('actions.choose', 'Choose') ?></option>
                        <?php foreach ($wilayas as $w): ?>
                            <option value="<?= (int)$w['id'] ?>"
                                <?= ((int)($destination['state_code'] ?? 0) === (int)$w['id']) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($w['name'] ?? '') ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <!-- بلدية -->
                <div class="col-md-4">
                    <label class="form-label"><?= __('shipping.commune', 'Commune') ?> *</label>
                    <select name="to_commune_id" id="ya_commune" class="form-select" required>
                        <option value=""><?= __('shipping.ecotrack.select_commune_first', 'Select wilaya first') ?></option>
                    </select>
                </div>

                <?php if ($isStopDesk): ?>
                <!-- Stop Desk -->
                <div class="col-md-4">
                    <label class="form-label"><?= __('shipping.stopdesk', 'Stop Desk') ?> *</label>
                    <select name="stopdesk_id" id="ya_stopdesk" class="form-select">
                        <option value=""><?= __('actions.choose', 'Choose') ?></option>
                    </select>
                </div>
                <?php endif; ?>

                <!-- عنوان -->
                <div class="col-md-8">
                    <label class="form-label"><?= __('shipping.address', 'Address') ?> *</label>
                    <input type="text" name="address" class="form-control"
                           value="<?= htmlspecialchars($destination['city_name'] ?? '') ?>" required>
                </div>

                <!-- المبلغ -->
                <div class="col-md-4">
                    <label class="form-label"><?= __('shipping.amount', 'Amount (COD)') ?> *</label>
                    <input type="number" step="0.01" name="amount" class="form-control"
                           value="<?= (float)OrderPricing::effectiveTotal($order) ?>" required>
                </div>

                <!-- المنتج -->
                <div class="col-md-4">
                    <label class="form-label"><?= __('shipping.product_list', 'Product Description') ?></label>
                    <input type="text" name="product_list" class="form-control"
                           value="<?= htmlspecialchars($extra['product']['name'] ?? 'colis') ?>">
                </div>

                <!-- الوزن -->
                <div class="col-md-2">
                    <label class="form-label"><?= __('shipping.weight', 'Weight (kg)') ?></label>
                    <input type="number" step="0.1" name="weight" class="form-control" value="0.5" min="0.1">
                </div>

                <!-- الأبعاد -->
                <div class="col-md-2">
                    <label class="form-label"><?= __('shipping.length', 'L') ?></label>
                    <input type="number" step="1" name="length" class="form-control" value="10" min="1">
                </div>
                <div class="col-md-2">
                    <label class="form-label"><?= __('shipping.width', 'W') ?></label>
                    <input type="number" step="1" name="width" class="form-control" value="10" min="1">
                </div>
                <div class="col-md-2">
                    <label class="form-label"><?= __('shipping.height', 'H') ?></label>
                    <input type="number" step="1" name="height" class="form-control" value="5" min="1">
                </div>

                <!-- ملاحظة -->
                <div class="col-12">
                    <label class="form-label"><?= __('shipping.note', 'Note') ?></label>
                    <textarea name="note" class="form-control" rows="2"></textarea>
                </div>

            </div>
        </div>
    </div>

    <button type="submit" class="btn btn-success">
        <i class="bi bi-truck me-1"></i>
        <?= __('orders.send_to_shipping', 'Send to Yalidine') ?>
    </button>
    <a href="/admin/orders/view/<?= (int)$order['id'] ?>" class="btn btn-secondary ms-2">
        <?= __('actions.cancel', 'Cancel') ?>
    </a>
</form>

</div>

<script>
const wantedYalidineCommune = <?= json_encode($destination['city_name'] ?? '', JSON_UNESCAPED_UNICODE) ?>;
function loadYalidineCommunes(wilayaId) {
    if (!wilayaId) return;
    var sel = document.getElementById('ya_commune');
    sel.innerHTML = '<option><?= __('admin.loading', 'Loading...') ?></option>';

    fetch('/admin/orders/yalidine/communes?wilaya_id=' + wilayaId)
        .then(r => r.json())
        .then(data => {
            sel.innerHTML = '<option value=""><?= __('actions.choose', 'Choose') ?></option>';
            (data.data || data || []).forEach(function(c) {
                var opt = document.createElement('option');
                opt.value = c.id;
                opt.textContent = c.name;
                if (wantedYalidineCommune && String(c.name).toLowerCase() === String(wantedYalidineCommune).toLowerCase()) {
                    opt.selected = true;
                }
                sel.appendChild(opt);
            });
        })
        .catch(function() {
            sel.innerHTML = '<option><?= __('errors.network','Error') ?></option>';
        });

    <?php if ($isStopDesk): ?>
    // تحميل stop desks
    var sdSel = document.getElementById('ya_stopdesk');
    if (sdSel) {
        fetch('/admin/orders/yalidine/stopdesks?wilaya_id=' + wilayaId)
            .then(r => r.json())
            .then(data => {
                sdSel.innerHTML = '<option value=""><?= __('actions.choose','Choose') ?></option>';
                (data.data || data || []).forEach(function(sd) {
                    var opt = document.createElement('option');
                    opt.value = sd.id;
                    opt.textContent = sd.name;
                    sdSel.appendChild(opt);
                });
            });
    }
    <?php endif; ?>
}

// تحميل تلقائي إذا كانت الولاية محددة
document.addEventListener('DOMContentLoaded', function() {
    var sel = document.getElementById('ya_wilaya');
    if (sel && sel.value) loadYalidineCommunes(sel.value);
});
</script>