<?php include __DIR__ . '/../header.php'; ?>

<?php
use Core\App\Support\OrderPricing;
/* =============================
   LOAD EXTRA FROM ORDER
============================= */
$extra = is_array($order['extra'] ?? null)
    ? $order['extra']
    : [];

/* ===== Shipping ===== */
$shipping = $extra['shipping'] ?? [];
$destination = $shipping['destination'] ?? [];

$stateCode = $destination['state_code'] ?? '';
$cityName  = $destination['city_name']  ?? '';

/* ===== Algeria States Map ===== */
$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=>'المنيعة'
];

$stateName = $dzStates[(int)$stateCode] ?? $stateCode;

/* ===== ECOTRACK TYPES (FIXED) ===== */
$ecotrackTypes = [
    1 => __('ecotrack.type_livraison', 'Livraison'),
    2 => __('ecotrack.type_echange', 'Echange'),
    3 => __('ecotrack.type_pickup', 'Pickup'),
    4 => __('ecotrack.type_recouvrement', 'Recouvrement'),
];
?>

<div class="container py-4">

    <!-- PAGE HEADER -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3>
            <?= __('ecotrack.title', 'ECOTRACK Shipping') ?>
            <span class="text-muted">#<?= $order['id'] ?></span>
        </h3>

        <a href="/admin/orders/view/<?= $order['id'] ?>" class="btn btn-secondary">
            <?= __('actions.back', 'Back') ?>
        </a>
    </div>

    <!-- ECOTRACK FORM -->
    <div class="card mb-4">
        <div class="card-header">
            <strong><?= __('ecotrack.form_title', 'Prepare ECOTRACK Shipment') ?></strong>
        </div>

        <div class="card-body">

            <form method="post">

                <h5 class="mb-3"><?= __('ecotrack.required_info', 'Required Information') ?></h5>

                <div class="mb-3">
                    <label class="form-label"><?= __('orders.full_name', 'Full Name') ?> *</label>
                    <input type="text" class="form-control"
                           name="nom_client"
                           value="<?= htmlspecialchars($order['full_name']) ?>" required>
                </div>

                <div class="mb-3">
                    <label class="form-label"><?= __('orders.phone', 'Phone') ?> *</label>
                    <input type="text" class="form-control"
                           name="telephone"
                           value="<?= htmlspecialchars($order['phone']) ?>" required>
                </div>

                <div class="mb-3">
                    <label class="form-label"><?= __('ecotrack.address', 'Address') ?> *</label>
                    <input type="text" class="form-control"
                           name="adresse"
                           value="<?= htmlspecialchars($stateName) ?>" required>
                </div>

                <div class="mb-3">
                    <label class="form-label"><?= __('ecotrack.commune', 'Commune') ?> *</label>
                    <input type="text" class="form-control"
                           name="commune"
                           value="<?= htmlspecialchars($cityName) ?>" required>
                </div>

                <div class="mb-3">
                    <label class="form-label"><?= __('ecotrack.wilaya_code', 'Wilaya Code') ?> *</label>
                    <input type="text" class="form-control"
                           name="code_wilaya"
                           value="<?= htmlspecialchars($stateCode) ?>" required>
                </div>

                <div class="mb-3">
                    <label class="form-label"><?= __('ecotrack.amount', 'Amount') ?> *</label>
                    <input type="number" class="form-control"
                           name="montant"
                           id="montantField"
                           value="<?= htmlspecialchars((string)OrderPricing::effectiveTotal($order)) ?>"
                           step="0.01" min="0" required>
                    <div class="form-text text-muted"><?= __('ecotrack.original_amount', 'Original amount') ?>: <strong><?= htmlspecialchars((string)OrderPricing::effectiveTotal($order)) ?></strong></div>
                </div>

                <!-- Negotiated price note -->
                <div class="mb-3" id="negotiatedNoteWrap" style="display:none">
                    <div class="alert alert-warning py-2 small mb-2">
                        <i class="bi bi-exclamation-triangle me-1"></i>
                        <?= __('ecotrack.negotiated_note_info', 'You changed the amount. A note will be recorded automatically.') ?>
                    </div>
                    <label class="form-label"><?= __('ecotrack.negotiated_note', 'Reason for price change') ?></label>
                    <input type="text" class="form-control form-control-sm"
                           name="negotiated_note"
                           id="negotiatedNote"
                           placeholder="<?= __('ecotrack.negotiated_placeholder', 'e.g. Customer negotiated 1800 instead of 2000') ?>">
                </div>

                <div class="mb-4">
                    <label class="form-label"><?= __('ecotrack.type', 'Shipping Type') ?> *</label>
                    <select name="type" class="form-select" required>
                        <option value=""><?= __('actions.choose', 'Choose') ?></option>
                        <?php foreach ($ecotrackTypes as $value => $label): ?>
                            <option value="<?= $value ?>"><?= $label ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <h5 class="mb-3"><?= __('ecotrack.optional_info', 'Optional Information') ?></h5>

                <div class="mb-3">
                    <label class="form-label"><?= __('ecotrack.reference', 'Reference') ?></label>
                    <input type="text" class="form-control"
                           name="reference"
                           value="<?= $order['id'] ?>">
                </div>

                <div class="mb-3">
                    <label class="form-label"><?= __('ecotrack.remark', 'Remark') ?></label>
                    <textarea name="remarque" class="form-control"></textarea>
                </div>

                <button type="submit" class="btn btn-primary" disabled>
                    <?= __('ecotrack.execute_disabled', 'Execute ECOTRACK (Disabled)') ?>
                </button>

            </form>

        </div>
    </div>

</div>

<script>
(function () {
    const originalAmount = <?= (float)OrderPricing::effectiveTotal($order) ?>;
    const montantField   = document.getElementById('montantField');
    const noteWrap       = document.getElementById('negotiatedNoteWrap');
    const noteField      = document.getElementById('negotiatedNote');

    if (!montantField) return;

    montantField.addEventListener('input', function () {
        const val = parseFloat(this.value);
        if (!isNaN(val) && val !== originalAmount) {
            noteWrap.style.display = 'block';
            if (!noteField.value) {
                noteField.value = '<?= __('ecotrack.negotiated_auto_note', 'Price changed from') ?> ' + originalAmount + ' <?= __('ecotrack.negotiated_to', 'to') ?> ' + val;
            }
        } else {
            noteWrap.style.display = 'none';
        }
    });
})();
</script>

<?php include __DIR__ . '/../footer.php'; ?>
