<?php

use yii\helpers\Html;
use yii\helpers\Url;

$gforce        = $model->data->gforce;
$csrfToken = Yii::$app->request->csrfToken;
$csrfParam = Yii::$app->request->csrfParam;

Yii::warning($gforce->attributes, 'gforce');
?>
<?php
$exData = [];
if (!empty($gforce->tracking_number)) {
    $exData = str_contains($gforce->tracking_number, ',')
        ? array_map('trim', explode(',', $gforce->tracking_number))
        : [trim($gforce->tracking_number)];
}
$trackingUrl = Url::to(['/gforce/consignment/tracking']);
$labelPdfUrl = Url::to(['/gforce/consignment/labels']);
$cancelUrl   = Url::to(['/gforce/consignment/delete']);
?>

<div class="card">
    <div class="card-header">
        <h5 class="mb-0">GForce Despatch Manager</h5>
    </div>
    <div class="card-body">
        <?php if ($exData) { ?>
            <div class="mb-3">
                <?php foreach ($exData as $trackingNo) { ?>
                    <div class="d-flex align-items-center flex-wrap mb-1">
                        <button
                            type="button"
                            class="badge badge-secondary gforcetrack-btn mr-2"
                            style="cursor:pointer;border:none;"
                            data-tracking="<?= Html::encode($trackingNo) ?>"
                            title="View tracking for <?= Html::encode($trackingNo) ?>"
                        ><?= Html::encode($trackingNo) ?></button>
                        <button
                            type="button"
                            class="btn btn-sm btn-outline-secondary gforceprint-btn mr-1"
                            data-tracking="<?= Html::encode($trackingNo) ?>"
                            title="Print label"
                        ><i class="fa fa-print"></i> Print Label</button>
                        <button
                            type="button"
                            class="btn btn-sm btn-outline-primary gforcedownload-btn mr-1"
                            data-tracking="<?= Html::encode($trackingNo) ?>"
                            title="Download label"
                        ><i class="fa fa-download"></i> Download Label</button>
                        <button
                            type="button"
                            class="btn btn-sm btn-outline-danger gforcecancel-btn"
                            data-tracking="<?= Html::encode($trackingNo) ?>"
                            title="Cancel this consignment item"
                        ><i class="fa fa-times"></i> Cancel</button>
                    </div>
                <?php } ?>
            </div>
        <?php } ?>

        <?php foreach ($gforce as $key => $value) { ?>
            <?php if ($key !== 'tracking_number') { ?>
                <p><strong><?= Html::encode(ucwords(str_replace('_', ' ', $key))) ?>:</strong> <?= Html::encode($value) ?></p>
            <?php } ?>
        <?php } ?>
    </div>
    <div class="card-footer">
        <?= Html::a('Create Consignment', ['gforce/consignment/create', 'id' => $model->id], ['target' => '_blank', 'class' => 'btn btn-primary']) ?>
        <?= Html::a('Pick Order', ['gforce/consignment/pick-order', 'id' => $model->id], ['target' => '_blank', 'class' => 'btn btn-primary']) ?>
        <?= Html::a('Mark Dispatched', ['gforce/admin/dispatched', 'id' => $model->id], ['target' => '_blank', 'class' => 'btn btn-primary']) ?>
        <?= Html::a('Mark Arrived', ['gforce/admin/arrived', 'id' => $model->id], ['target' => '_blank', 'class' => 'btn btn-primary']) ?>
    </div>
</div>

<?php
$encodedTrackingUrl = json_encode($trackingUrl);
$encodedLabelUrl    = json_encode($labelPdfUrl);
$encodedCancelUrl   = json_encode($cancelUrl);
$encodedCsrfParam   = json_encode($csrfParam);
$encodedCsrfToken   = json_encode($csrfToken);

$js = <<<JS
(function () {
    var trackingUrl = {$encodedTrackingUrl};
    var labelPdfUrl = {$encodedLabelUrl};
    var cancelUrl   = {$encodedCancelUrl};
    var csrfParam   = {$encodedCsrfParam};
    var csrfToken   = {$encodedCsrfToken};

    var modal      = \$('#LGmodal');
    var modalTitle = modal.find('.modal-title');
    var modalBody  = modal.find('.modal-body');
    var modalFooter = modal.find('.modal-footer');

    var spinner = '<div class="text-center py-3"><span class="spinner-border text-primary" role="status"></span></div>';

    // ── Tracking ─────────────────────────────────────────────────────────────
    document.querySelectorAll('.gforcetrack-btn').foreach (function (btn) {
        btn.addEventListener('click', function () {
            var trackingNumber = this.getAttribute('data-tracking');

            modalTitle.text('gforce Tracking \u2014 ' + trackingNumber);
            modalBody.html(spinner);
            modalFooter.html('');
            modal.modal('show');

            fetch(trackingUrl + '?trackingCode=' + encodeURIComponent(trackingNumber), {
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            })
            .then(function (res) { return res.json(); })
            .then(function (json) {
                if (!json.success) {
                    modalBody.html('<div class="alert alert-warning">' + (json.message || 'No tracking found.') + '</div>');
                    return;
                }
                modalBody.html('<pre style="max-height:420px;overflow:auto">' + JSON.stringify(json.data, null, 2) + '</pre>');
            })
            .catch(function () {
                modalBody.html('<div class="alert alert-danger">Failed to load tracking information.</div>');
            });
        });
    });

    // ── Print Label ──────────────────────────────────────────────────────────
    document.querySelectorAll('.gforceprint-btn').foreach (function (btn) {
        btn.addEventListener('click', function () {
            var trackingNumber = this.getAttribute('data-tracking');
            var self = this;

            self.disabled = true;
            self.innerHTML = '<span class="spinner-border spinner-border-sm" role="status"></span> Fetching\u2026';

            fetch(labelPdfUrl + '?trackingCode=' + encodeURIComponent(trackingNumber), {
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            })
            .then(function (res) {
                if (!res.ok) {
                    return res.json().then(function (json) {
                        throw new Error(json.message || 'Failed to fetch label PDF.');
                    });
                }
                return res.blob();
            })
            .then(function (blob) {
                self.disabled = false;
                self.innerHTML = '<i class="fa fa-print"></i> Print Label';
                var url = URL.createObjectURL(blob);
                var win = window.open(url, '_blank');
                if (win) {
                    win.onload = function () {
                        try { win.print(); } catch (e) {}
                    };
                }
                setTimeout(function () { URL.revokeObjectURL(url); }, 60000);
            })
            .catch(function (error) {
                self.disabled = false;
                self.innerHTML = '<i class="fa fa-print"></i> Print Label';
                alert(error && error.message ? error.message : 'Failed to fetch label PDF.');
            });
        });
    });

    // ── Download Label ───────────────────────────────────────────────────────
    document.querySelectorAll('.gforcedownload-btn').foreach (function (btn) {
        btn.addEventListener('click', function () {
            var trackingNumber = this.getAttribute('data-tracking');
            window.location.href = labelPdfUrl + '?trackingCode=' + encodeURIComponent(trackingNumber) + '&download=1';
        });
    });

    // ── Cancel ───────────────────────────────────────────────────────────────
    var cancelTrackingNumber = null;

    function showCancelConfirm(trackingNumber) {
        cancelTrackingNumber = trackingNumber;
        \$modalTitle.text('Cancel Consignment Item');
        \$modalBody.html(
            '<p>Are you sure you want to cancel tracking number <strong>' +
            \$('<span>').text(trackingNumber).html() +
            '</strong>?</p>' +
            '<p class="text-danger small">This cannot be undone and must be done before the despatch date.</p>' +
            '<div id="gforceCancelResult"></div>'
        );
        \$modalFooter.html(
            '<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> ' +
            '<button type="button" class="btn btn-danger" id="gforceCancelConfirmBtn">Yes, Cancel Item</button>'
        );

        document.getElementById('gforceCancelConfirmBtn').addEventListener('click', doCancelConfirm);
        \$modal.modal('show');
    }

    function doCancelConfirm() {
        if (!cancelTrackingNumber) { return; }

        var confirmBtn = document.getElementById('gforceCancelConfirmBtn');
        confirmBtn.disabled = true;
        confirmBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status"></span> Cancelling\u2026';

        var body = new URLSearchParams();
        body.append('trackingCode', cancelTrackingNumber);
        body.append(csrfParam, csrfToken);

        fetch(cancelUrl, {
            method:  'POST',
            headers: { 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded' },
            body:    body.toString()
        })
        .then(function (res) { return res.json(); })
        .then(function (json) {
            var resultDiv = document.getElementById('gforceCancelResult');
            if (json.success) {
                resultDiv.innerHTML = '<div class="alert alert-success mt-2">Item cancelled successfully.</div>';
                confirmBtn.disabled = true;
            } else {
                resultDiv.innerHTML = '<div class="alert alert-danger mt-2">' +
                    (json.message || 'Cancellation failed.') + '</div>';
                confirmBtn.disabled = false;
                confirmBtn.textContent = 'Retry';
            }
        })
        .catch(function () {
            var resultDiv = document.getElementById('gforceCancelResult');
            if (resultDiv) {
                resultDiv.innerHTML = '<div class="alert alert-danger mt-2">Request failed. Please try again.</div>';
            }
            confirmBtn.disabled = false;
            confirmBtn.textContent = 'Retry';
        });
    }

    document.querySelectorAll('.gforcecancel-btn').foreach (function (btn) {
        btn.addEventListener('click', function () {
            showCancelConfirm(this.getAttribute('data-tracking'));
        });
    });
}());
JS;
$this->registerJs($js);
?>
