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

<?php
$csrfToken      = $_SESSION['_csrf'] ?? '';
$totalEligible  = count($eligibleOrders ?? []);

/** @var array $eligibleOrders */
/** @var array $activeProviders */
/** @var string $forcedProvider */
/** @var string $selectionMode */
?>

<div class="content-wrapper">
<section class="content pt-3">
<div class="container-fluid pb-5">

<!-- ══════════════════════════════════════════════════
     PAGE HEADER
══════════════════════════════════════════════════ -->
<div class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-4">
    <div>
        <h3 class="mb-1 fw-bold">
            <i class="bi bi-send-check me-2 text-primary"></i>
            <?= __('bulk_confirm.title', 'Bulk Order Confirmation') ?>
        </h3>
        <p class="text-muted mb-0 small"><?= __('bulk_confirm.subtitle', 'Send multiple confirmed orders to your shipping carrier at once') ?></p>
    </div>
    <a href="/admin/orders" class="btn btn-outline-secondary btn-sm">
        <i class="bi bi-arrow-left me-1"></i>
        <?= __('bulk_confirm.back_to_orders', 'Back to Orders') ?>
    </a>
</div>

<!-- ══════════════════════════════════════════════════
     KPI CARDS
══════════════════════════════════════════════════ -->
<div class="row g-3 mb-4">
    <div class="col-6 col-md-3">
        <div class="card border-0 shadow-sm h-100" style="border-top:3px solid #0d6efd !important">
            <div class="card-body px-4 py-3">
                <div class="d-flex align-items-center justify-content-between mb-2">
                    <div class="rounded-circle d-flex align-items-center justify-content-center bg-primary-subtle"
                         style="width:42px;height:42px">
                        <i class="bi bi-inbox fs-5 text-primary"></i>
                    </div>
                </div>
                <div class="fw-bold fs-2 lh-1 mb-1" id="kpi-eligible"><?= $totalEligible ?></div>
                <div class="text-muted small"><?= __('bulk_confirm.eligible_orders', 'Eligible Orders') ?></div>
            </div>
        </div>
    </div>
    <div class="col-6 col-md-3">
        <div class="card border-0 shadow-sm h-100" style="border-top:3px solid #6c757d !important">
            <div class="card-body px-4 py-3">
                <div class="d-flex align-items-center justify-content-between mb-2">
                    <div class="rounded-circle d-flex align-items-center justify-content-center bg-secondary-subtle"
                         style="width:42px;height:42px">
                        <i class="bi bi-check2-square fs-5 text-secondary"></i>
                    </div>
                </div>
                <div class="fw-bold fs-2 lh-1 mb-1" id="kpi-selected">0</div>
                <div class="text-muted small"><?= __('bulk_confirm.selected', 'Selected') ?></div>
            </div>
        </div>
    </div>
    <div class="col-6 col-md-3">
        <div class="card border-0 shadow-sm h-100" style="border-top:3px solid #198754 !important">
            <div class="card-body px-4 py-3">
                <div class="d-flex align-items-center justify-content-between mb-2">
                    <div class="rounded-circle d-flex align-items-center justify-content-center bg-success-subtle"
                         style="width:42px;height:42px">
                        <i class="bi bi-check-circle fs-5 text-success"></i>
                    </div>
                </div>
                <div class="fw-bold fs-2 lh-1 mb-1" id="kpi-success">—</div>
                <div class="text-muted small"><?= __('bulk_confirm.sent_ok', 'Sent Successfully') ?></div>
            </div>
        </div>
    </div>
    <div class="col-6 col-md-3">
        <div class="card border-0 shadow-sm h-100" style="border-top:3px solid #dc3545 !important">
            <div class="card-body px-4 py-3">
                <div class="d-flex align-items-center justify-content-between mb-2">
                    <div class="rounded-circle d-flex align-items-center justify-content-center bg-danger-subtle"
                         style="width:42px;height:42px">
                        <i class="bi bi-x-circle fs-5 text-danger"></i>
                    </div>
                </div>
                <div class="fw-bold fs-2 lh-1 mb-1" id="kpi-failed">—</div>
                <div class="text-muted small"><?= __('bulk_confirm.sent_failed', 'Failed') ?></div>
            </div>
        </div>
    </div>
</div>

<?php if (empty($eligibleOrders)): ?>
<!-- ══ NO ELIGIBLE ORDERS ══ -->
<div class="card border-0 shadow-sm">
    <div class="card-body text-center py-5">
        <i class="bi bi-inbox fs-1 text-muted mb-3 d-block"></i>
        <h5 class="text-muted"><?= __('bulk_confirm.no_eligible', 'No eligible orders found') ?></h5>
        <p class="text-muted small mb-0">
            <?= __('bulk_confirm.no_eligible_hint', 'Only confirmed orders without a tracking number are shown here.') ?>
        </p>
    </div>
</div>
<?php else: ?>

<!-- ══════════════════════════════════════════════════
     TOOLBAR  (provider selector + action buttons)
══════════════════════════════════════════════════ -->
<div class="card border-0 shadow-sm mb-3">
    <div class="card-body py-3 px-4">
        <div class="row align-items-center g-3">
            <!-- Provider selector -->
            <div class="col-12 col-md-5">
                <label class="form-label fw-semibold mb-1 small">
                    <i class="bi bi-truck me-1"></i>
                    <?= __('bulk_confirm.select_provider', 'Shipping Provider') ?>
                </label>
                <?php if ($selectionMode === 'forced_provider' && $forcedProvider !== ''): ?>
                    <div class="alert alert-info py-2 mb-0 small">
                        <i class="bi bi-lock me-1"></i>
                        <?= __('bulk_confirm.forced_provider', 'Provider is locked by settings') ?>:
                        <strong><?= htmlspecialchars($activeProviders[$forcedProvider] ?? $forcedProvider) ?></strong>
                    </div>
                    <input type="hidden" id="providerSelect" value="<?= htmlspecialchars($forcedProvider) ?>">
                <?php else: ?>
                    <select id="providerSelect" class="form-select form-select-sm">
                        <option value="">— <?= __('bulk_confirm.choose_provider', 'Choose provider') ?> —</option>
                        <?php foreach ($activeProviders as $key => $name): ?>
                            <option value="<?= htmlspecialchars($key) ?>">
                                <?= htmlspecialchars($name) ?>
                            </option>
                        <?php endforeach; ?>
                        <?php if (empty($activeProviders)): ?>
                            <option disabled><?= __('bulk_confirm.no_providers', 'No active providers configured') ?></option>
                        <?php endif; ?>
                    </select>
                <?php endif; ?>
            </div>

            <!-- Selection helpers -->
            <div class="col-12 col-md-7">
                <label class="form-label fw-semibold mb-1 small">&nbsp;</label>
                <div class="d-flex flex-wrap gap-2">
                    <button type="button" class="btn btn-outline-secondary btn-sm" id="selectAllBtn">
                        <i class="bi bi-check-all me-1"></i>
                        <?= __('bulk_confirm.select_all', 'Select All') ?>
                    </button>
                    <button type="button" class="btn btn-outline-secondary btn-sm" id="deselectAllBtn">
                        <i class="bi bi-x-square me-1"></i>
                        <?= __('bulk_confirm.deselect_all', 'Deselect All') ?>
                    </button>
                    <button type="button" class="btn btn-primary btn-sm ms-auto" id="processBtn" disabled>
                        <i class="bi bi-send me-1"></i>
                        <span id="processBtnText">
                            <?= __('bulk_confirm.process_selected', 'Process Selected') ?>
                        </span>
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- ══════════════════════════════════════════════════
     ORDERS TABLE
══════════════════════════════════════════════════ -->
<div class="card border-0 shadow-sm mb-4" id="ordersTableCard">
    <div class="card-header border-0 bg-white py-3 px-4">
        <div class="d-flex align-items-center gap-2">
            <h6 class="mb-0 fw-semibold">
                <i class="bi bi-list-ul me-1 text-primary"></i>
                <?= __('bulk_confirm.eligible_orders', 'Eligible Orders') ?>
            </h6>
            <span class="badge bg-primary-subtle text-primary"><?= $totalEligible ?></span>
        </div>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-light">
                    <tr>
                        <th style="width:40px" class="ps-4">
                            <input type="checkbox" id="selectAllCheck" class="form-check-input" title="Select all">
                        </th>
                        <th class="text-muted fw-medium small"><?= __('bulk_confirm.order_id', 'Order #') ?></th>
                        <th class="text-muted fw-medium small"><?= __('bulk_confirm.customer', 'Customer') ?></th>
                        <th class="text-muted fw-medium small"><?= __('bulk_confirm.phone', 'Phone') ?></th>
                        <th class="text-muted fw-medium small"><?= __('bulk_confirm.product', 'Product') ?></th>
                        <th class="text-muted fw-medium small"><?= __('bulk_confirm.wilaya', 'Wilaya') ?></th>
                        <th class="text-muted fw-medium small"><?= __('bulk_confirm.amount', 'Amount') ?></th>
                        <th class="text-muted fw-medium small"><?= __('bulk_confirm.order_date', 'Date') ?></th>
                        <th class="text-muted fw-medium small"><?= __('bulk_confirm.row_status', 'Status') ?></th>
                    </tr>
                </thead>
                <tbody id="ordersTableBody">
                <?php foreach ($eligibleOrders as $order):
                    $extra       = is_array($order['extra']) ? $order['extra'] : [];
                    $destination = $extra['shipping']['destination'] ?? [];
                    $wilayaName  = trim($destination['state_name'] ?? ($destination['state_code'] ?? '—'));
                    $productName = trim($extra['product']['name'] ?? '—');
                    if (strlen($productName) > 30) $productName = substr($productName, 0, 27) . '…';
                    $amount      = \Core\App\Support\OrderPricing::effectiveTotal($order);
                    $createdAt   = $order['created_at'] ?? '';
                    $canSend     = $wilayaName !== '—' && $wilayaName !== '';
                ?>
                <tr class="order-row <?= $canSend ? '' : 'table-warning' ?>"
                    data-id="<?= (int)$order['id'] ?>"
                    data-can-send="<?= $canSend ? '1' : '0' ?>">
                    <td class="ps-4">
                        <?php if ($canSend): ?>
                        <input type="checkbox" class="form-check-input order-checkbox"
                               value="<?= (int)$order['id'] ?>">
                        <?php else: ?>
                        <i class="bi bi-exclamation-triangle text-warning"
                           title="<?= __('bulk_confirm.missing_data', 'Missing destination data') ?>"></i>
                        <?php endif; ?>
                    </td>
                    <td>
                        <a href="/admin/orders/view/<?= (int)$order['id'] ?>" target="_blank"
                           class="text-decoration-none fw-semibold text-primary">
                            #<?= (int)$order['id'] ?>
                        </a>
                    </td>
                    <td class="small"><?= htmlspecialchars($order['full_name'] ?? '') ?></td>
                    <td class="small text-muted"><?= htmlspecialchars($order['phone'] ?? '') ?></td>
                    <td class="small text-muted"><?= htmlspecialchars($productName) ?></td>
                    <td class="small"><?= htmlspecialchars($wilayaName) ?></td>
                    <td class="small fw-medium"><?= number_format($amount, 0, '.', ' ') ?> <small class="text-muted">DA</small></td>
                    <td class="small text-muted"><?= $createdAt ? date('d/m/Y', strtotime($createdAt)) : '—' ?></td>
                    <td class="row-status-cell" data-order-id="<?= (int)$order['id'] ?>">
                        <?php if (!$canSend): ?>
                            <span class="badge bg-warning text-dark">
                                <i class="bi bi-exclamation-triangle me-1"></i>
                                <?= __('bulk_confirm.missing_data', 'Incomplete') ?>
                            </span>
                        <?php else: ?>
                            <span class="badge bg-light text-secondary border">
                                <?= __('bulk_confirm.status_pending', 'Pending') ?>
                            </span>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- ══════════════════════════════════════════════════
     RESULTS SECTION  (hidden until processing)
══════════════════════════════════════════════════ -->
<div class="card border-0 shadow-sm d-none" id="resultsCard">
    <div class="card-header border-0 bg-white py-3 px-4">
        <h6 class="mb-0 fw-semibold">
            <i class="bi bi-bar-chart me-1 text-success"></i>
            <?= __('bulk_confirm.results_title', 'Processing Results') ?>
        </h6>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-sm align-middle mb-0">
                <thead class="table-light">
                    <tr>
                        <th class="ps-4 text-muted fw-medium small"><?= __('bulk_confirm.order_id', 'Order #') ?></th>
                        <th class="text-muted fw-medium small"><?= __('bulk_confirm.customer', 'Customer') ?></th>
                        <th class="text-muted fw-medium small"><?= __('bulk_confirm.phone', 'Phone') ?></th>
                        <th class="text-muted fw-medium small"><?= __('bulk_confirm.result_status', 'Result') ?></th>
                        <th class="text-muted fw-medium small"><?= __('bulk_confirm.tracking', 'Tracking') ?></th>
                        <th class="text-muted fw-medium small"><?= __('bulk_confirm.error', 'Error') ?></th>
                    </tr>
                </thead>
                <tbody id="resultsTableBody"></tbody>
            </table>
        </div>
    </div>
</div>

<?php endif; ?>

</div><!-- /container-fluid -->
</section>
</div><!-- /content-wrapper -->

<!-- ══════════════════════════════════════════════════
     PROGRESS OVERLAY
══════════════════════════════════════════════════ -->
<div id="progressOverlay" class="d-none position-fixed top-0 start-0 w-100 h-100 d-flex align-items-center justify-content-center"
     style="background:rgba(0,0,0,.45);z-index:9999">
    <div class="card shadow-lg p-4 text-center" style="min-width:260px;border-radius:12px">
        <div class="spinner-border text-primary mb-3" role="status" style="width:3rem;height:3rem"></div>
        <div class="fw-semibold"><?= __('bulk_confirm.processing', 'Processing orders…') ?></div>
        <div class="text-muted small mt-1" id="progressDetail"></div>
    </div>
</div>

<script>
(function () {
    'use strict';

    var csrfToken    = <?= json_encode($csrfToken) ?>;
    var processUrl   = '/admin/orders/bulk-confirm/process';

    /* ── DOM refs ─────────────────────────────────── */
    var selectAllCheck  = document.getElementById('selectAllCheck');
    var selectAllBtn    = document.getElementById('selectAllBtn');
    var deselectAllBtn  = document.getElementById('deselectAllBtn');
    var processBtn      = document.getElementById('processBtn');
    var processBtnText  = document.getElementById('processBtnText');
    var providerSelect  = document.getElementById('providerSelect');
    var kpiSelected     = document.getElementById('kpi-selected');
    var kpiSuccess      = document.getElementById('kpi-success');
    var kpiFailed       = document.getElementById('kpi-failed');
    var resultsCard     = document.getElementById('resultsCard');
    var resultsBody     = document.getElementById('resultsTableBody');
    var progressOverlay = document.getElementById('progressOverlay');
    var progressDetail  = document.getElementById('progressDetail');

    /* ── Labels (PHP-rendered) ───────────────────── */
    var LABEL = {
        success     : <?= json_encode(__('bulk_confirm.status_success', 'Sent')) ?>,
        failed      : <?= json_encode(__('bulk_confirm.status_failed',  'Failed')) ?>,
        processing  : <?= json_encode(__('bulk_confirm.processing',     'Processing orders…')) ?>,
        confirmTpl  : <?= json_encode(__('bulk_confirm.confirm_dialog', 'Send {count} orders to {provider}? This action cannot be undone.')) ?>,
        noProvider  : <?= json_encode(__('bulk_confirm.choose_provider','Please select a provider first')) ?>,
        noOrders    : <?= json_encode(__('bulk_confirm.select_min_one', 'Please select at least one order')) ?>,
        processBtn  : <?= json_encode(__('bulk_confirm.process_selected','Process Selected')) ?>,
        sent        : <?= json_encode(__('bulk_confirm.status_pending',  'Pending')) ?>,
    };

    /* ── Checkbox helpers ───────────────────────── */
    function getCheckboxes() {
        return document.querySelectorAll('.order-checkbox');
    }
    function getChecked() {
        return document.querySelectorAll('.order-checkbox:checked');
    }
    function updateKpiSelected() {
        var n = getChecked().length;
        if (kpiSelected) kpiSelected.textContent = n;
        if (processBtn)  processBtn.disabled = (n === 0);
        if (processBtnText) {
            processBtnText.textContent = n > 0
                ? LABEL.processBtn + ' (' + n + ')'
                : LABEL.processBtn;
        }
    }

    /* ── Select / Deselect all ──────────────────── */
    if (selectAllCheck) {
        selectAllCheck.addEventListener('change', function () {
            getCheckboxes().forEach(function (cb) { cb.checked = selectAllCheck.checked; });
            updateKpiSelected();
        });
    }
    if (selectAllBtn) {
        selectAllBtn.addEventListener('click', function () {
            getCheckboxes().forEach(function (cb) { cb.checked = true; });
            if (selectAllCheck) selectAllCheck.checked = true;
            updateKpiSelected();
        });
    }
    if (deselectAllBtn) {
        deselectAllBtn.addEventListener('click', function () {
            getCheckboxes().forEach(function (cb) { cb.checked = false; });
            if (selectAllCheck) selectAllCheck.checked = false;
            updateKpiSelected();
        });
    }

    getCheckboxes().forEach(function (cb) {
        cb.addEventListener('change', function () {
            updateKpiSelected();
            if (selectAllCheck) {
                var all = getCheckboxes();
                selectAllCheck.checked = all.length > 0 && getChecked().length === all.length;
            }
        });
    });

    updateKpiSelected();

    /* ── Process button ─────────────────────────── */
    if (processBtn) {
        processBtn.addEventListener('click', function () {
            var checked = getChecked();
            if (checked.length === 0) { alert(LABEL.noOrders); return; }

            var provider = providerSelect ? providerSelect.value : '';
            if (!provider) { alert(LABEL.noProvider); return; }

            var providerName = providerSelect
                ? (providerSelect.options[providerSelect.selectedIndex] || {}).text || provider
                : provider;

            var msg = LABEL.confirmTpl
                .replace('{count}',    checked.length)
                .replace('{provider}', providerName);
            if (!confirm(msg)) return;

            var orderIds = Array.from(checked).map(function (cb) { return cb.value; });
            sendOrders(orderIds, provider);
        });
    }

    /* ── AJAX: send orders ──────────────────────── */
    function sendOrders(orderIds, provider) {
        showProgress(true, LABEL.processing);

        var body = new URLSearchParams();
        body.append('_csrf',    csrfToken);
        body.append('provider', provider);
        orderIds.forEach(function (id) { body.append('order_ids[]', id); });

        fetch(processUrl, {
            method:  'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body:    body.toString(),
        })
        .then(function (r) { return r.json(); })
        .then(function (data) {
            showProgress(false);
            if (!data.success) {
                alert(data.error || 'Error');
                return;
            }
            renderResults(data.result, orderIds, provider);
        })
        .catch(function (err) {
            showProgress(false);
            alert('Network error: ' + err.message);
        });
    }

    /* ── Render results ─────────────────────────── */
    function renderResults(result, sentIds, provider) {
        var total   = result.total   || 0;
        var success = result.success || 0;
        var failed  = result.failed  || 0;
        var rows    = result.results || [];

        if (kpiSuccess) kpiSuccess.textContent = success;
        if (kpiFailed)  kpiFailed.textContent  = failed;

        // Update row statuses in orders table
        rows.forEach(function (row) {
            var statusCell = document.querySelector('.row-status-cell[data-order-id="' + row.order_id + '"]');
            var trEl = statusCell ? statusCell.closest('tr') : null;

            if (row.success) {
                if (statusCell) statusCell.innerHTML = '<span class="badge bg-success"><i class="bi bi-check-lg me-1"></i>' + LABEL.success + '</span>';
                if (trEl) {
                    trEl.classList.add('table-success');
                    var cb = trEl.querySelector('.order-checkbox');
                    if (cb) cb.disabled = true;
                }
            } else {
                if (statusCell) statusCell.innerHTML = '<span class="badge bg-danger"><i class="bi bi-x-lg me-1"></i>' + LABEL.failed + '</span>';
                if (trEl) trEl.classList.add('table-danger');
            }
        });

        // Populate results table
        if (resultsBody) {
            resultsBody.innerHTML = '';
            rows.forEach(function (row) {
                var tr = document.createElement('tr');
                tr.innerHTML = [
                    '<td class="ps-4"><a href="/admin/orders/view/' + row.order_id + '" target="_blank" class="text-primary fw-semibold">#' + row.order_id + '</a></td>',
                    '<td class="small">' + escHtml(row.full_name || '') + '</td>',
                    '<td class="small text-muted">' + escHtml(row.phone || '') + '</td>',
                    row.success
                        ? '<td><span class="badge bg-success"><i class="bi bi-check-lg me-1"></i>' + LABEL.success + '</span></td>'
                        : '<td><span class="badge bg-danger"><i class="bi bi-x-lg me-1"></i>' + LABEL.failed + '</span></td>',
                    '<td class="small"><code>' + escHtml(row.tracking || '—') + '</code></td>',
                    '<td class="small text-danger">' + escHtml(row.error || '') + '</td>',
                ].join('');
                resultsBody.appendChild(tr);
            });
        }

        if (resultsCard)  resultsCard.classList.remove('d-none');
        if (resultsCard)  resultsCard.scrollIntoView({ behavior: 'smooth', block: 'start' });

        updateKpiSelected();
    }

    /* ── Utilities ──────────────────────────────── */
    function showProgress(show, text) {
        if (!progressOverlay) return;
        if (show) {
            progressOverlay.classList.remove('d-none');
            progressOverlay.style.display = 'flex';
            if (progressDetail && text) progressDetail.textContent = text;
        } else {
            progressOverlay.classList.add('d-none');
            progressOverlay.style.display = '';
        }
    }

    function escHtml(str) {
        return String(str)
            .replace(/&/g,  '&amp;')
            .replace(/</g,  '&lt;')
            .replace(/>/g,  '&gt;')
            .replace(/"/g,  '&quot;')
            .replace(/'/g, '&#39;');
    }

})();
</script>
