<?php
/**
 * صفحة الطلبات المشبوهة + المحاولات المرفوضة
 */

$orders          = $orders          ?? [];
$stats           = $stats           ?? ['total'=>0,'high_risk'=>0,'medium_risk'=>0,'banned_phones'=>0];
$banned_phones   = $banned_phones   ?? [];
$current_page    = $current_page    ?? 1;
$total_pages     = $total_pages     ?? 1;
$tab             = $tab             ?? 'orders';
$attempts        = $attempts        ?? [];
$attempts_filter = $attempts_filter ?? '';
$attempts_total  = $attempts_total  ?? 0;
$attempts_pages  = $attempts_pages  ?? 1;
?>

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

    <!-- ===== PAGE HEADER ===== -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h3 class="mb-1 fw-bold">
                        <i class="bi bi-shield-exclamation me-2 text-danger"></i>
                        <?= __('fraud.page_title', 'Suspicious Orders') ?>
                    </h3>
                    <p class="text-muted mb-0 small"><?= __('fraud.subtitle','Detect and manage suspicious activity') ?></p>
                </div>
                <button class="btn btn-outline-danger"
                        data-bs-toggle="modal"
                        data-bs-target="#bannedPhonesModal">
                    <i class="bi bi-telephone-x me-1"></i>
                    <?= __('fraud.banned_phones', 'Banned Phones') ?>
                    <?php if (!empty($stats['banned_phones'])): ?>
                        <span class="badge bg-danger ms-1"><?= (int)$stats['banned_phones'] ?></span>
                    <?php endif; ?>
                </button>
            </div>
        </div>
    </div>

    <!-- ===== STAT 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 #ffc107 !important">
                <div class="card-body px-4 py-3">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <div class="rounded-circle d-flex align-items-center justify-content-center bg-warning-subtle"
                             style="width:42px;height:42px">
                            <i class="bi bi-exclamation-triangle fs-5 text-warning"></i>
                        </div>
                    </div>
                    <div class="fw-bold fs-2 lh-1 mb-1"><?= (int)$stats['total'] ?></div>
                    <div class="text-muted small"><?= __('fraud.stat_total', 'Total Suspicious') ?></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 justify-content-between align-items-start 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-octagon fs-5 text-danger"></i>
                        </div>
                    </div>
                    <div class="fw-bold fs-2 lh-1 mb-1 text-danger"><?= (int)$stats['high_risk'] ?></div>
                    <div class="text-muted small"><?= __('fraud.stat_high', 'High Risk') ?></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 #fd7e14 !important">
                <div class="card-body px-4 py-3">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <div class="rounded-circle d-flex align-items-center justify-content-center"
                             style="width:42px;height:42px;background:rgba(253,126,20,.1)">
                            <i class="bi bi-eye fs-5 text-warning"></i>
                        </div>
                    </div>
                    <div class="fw-bold fs-2 lh-1 mb-1 text-warning"><?= (int)$stats['medium_risk'] ?></div>
                    <div class="text-muted small"><?= __('fraud.stat_medium', 'Medium Risk') ?></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 justify-content-between align-items-start 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-telephone-x fs-5 text-danger"></i>
                        </div>
                    </div>
                    <div class="fw-bold fs-2 lh-1 mb-1"><?= (int)$stats['banned_phones'] ?></div>
                    <div class="text-muted small"><?= __('fraud.stat_banned', 'Banned Phones') ?></div>
                </div>
            </div>
        </div>

    </div>

    <!-- ===== TABS ===== -->
    <ul class="nav nav-tabs mb-0" id="fraudTabs">
        <li class="nav-item">
            <a class="nav-link <?= $tab !== 'attempts' ? 'active' : '' ?>"
               href="/admin/suspicious-orders?tab=orders">
                <i class="bi bi-list-ul me-1"></i>
                <?= __('fraud.tab_orders', 'Suspicious Orders') ?>
                <?php if ($stats['total'] > 0): ?>
                    <span class="badge bg-warning text-dark ms-1"><?= (int)$stats['total'] ?></span>
                <?php endif; ?>
            </a>
        </li>
        <li class="nav-item">
            <a class="nav-link <?= $tab === 'attempts' ? 'active' : '' ?>"
               href="/admin/suspicious-orders?tab=attempts">
                <i class="bi bi-slash-circle me-1"></i>
                <?= __('fraud.tab_attempts', 'Rejected Attempts') ?>
                <?php if ($attempts_total > 0): ?>
                    <span class="badge bg-danger ms-1"><?= (int)$attempts_total ?></span>
                <?php endif; ?>
            </a>
        </li>
    </ul>

    <!-- ===== TAB: SUSPICIOUS ORDERS ===== -->
    <?php if ($tab !== 'attempts'): ?>

    <div class="card border-0 shadow-sm border-top-0" style="border-radius:0 0 .5rem .5rem;">

        <!-- فلاتر -->
        <div class="card-header bg-body border-bottom">
            <form method="GET" action="/admin/suspicious-orders" class="row g-2 align-items-center">
                <input type="hidden" name="tab" value="orders">
                <div class="col-auto">
                    <select name="risk" class="form-select form-select-sm">
                        <option value=""><?= __('fraud.filter_all', 'All') ?></option>
                        <option value="high"   <?= ($_GET['risk'] ?? '') === 'high'   ? 'selected' : '' ?>><?= __('fraud.high_risk',   'High Risk (50+)') ?></option>
                        <option value="medium" <?= ($_GET['risk'] ?? '') === 'medium' ? 'selected' : '' ?>><?= __('fraud.medium_risk', 'Medium Risk (20-49)') ?></option>
                    </select>
                </div>
                <div class="col-auto">
                    <input type="text" name="phone" class="form-control form-control-sm"
                           placeholder="<?= __('fraud.filter_phone', 'Search by phone...') ?>"
                           value="<?= htmlspecialchars($_GET['phone'] ?? '') ?>">
                </div>
                <div class="col-auto">
                    <button class="btn btn-sm btn-primary"><i class="bi bi-search me-1"></i><?= __('actions.search', 'Search') ?></button>
                    <a href="/admin/suspicious-orders" class="btn btn-sm btn-outline-secondary ms-1"><?= __('actions.reset', 'Reset') ?></a>
                </div>
            </form>
        </div>

        <div class="card-body p-0">
            <?php if (empty($orders)): ?>
                <div class="text-center py-5">
                    <i class="bi bi-shield-check display-4 text-success mb-3 d-block"></i>
                    <h5 class="text-muted"><?= __('fraud.no_suspicious', 'No suspicious orders found') ?></h5>
                    <p class="text-muted small"><?= __('fraud.no_suspicious_desc', 'All orders look clean') ?></p>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>#</th>
                                <th><?= __('fraud.col_client',      'Client') ?></th>
                                <th><?= __('fraud.col_phone',       'Phone') ?></th>
                                <th><?= __('fraud.col_wilaya',      'Wilaya') ?></th>
                                <th><?= __('fraud.col_amount',      'Amount') ?></th>
                                <th><?= __('fraud.col_risk',        'Risk Score') ?></th>
                                <th><?= __('fraud.col_reason',      'Reason') ?></th>
                                <th><?= __('fraud.col_return_rate', 'Return Rate') ?></th>
                                <th><?= __('fraud.col_date',        'Date') ?></th>
                                <th class="text-end"><?= __('fraud.col_actions', 'Actions') ?></th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($orders as $order): ?>
                            <?php
                            $score      = (int)($order['fraud_score'] ?? 0);
                            $isHigh     = $score >= 50;
                            $rowClass   = $isHigh ? 'table-danger' : 'table-warning';
                            $badgeCls   = $isHigh ? 'bg-danger' : 'bg-warning text-dark';
                            $phone      = htmlspecialchars($order['phone'] ?? '');
                            $returnRate = isset($order['return_rate']) ? (float)$order['return_rate'] : null;
                            ?>
                            <tr class="<?= $rowClass ?>" id="order-row-<?= (int)$order['id'] ?>">
                                <td class="fw-bold">#<?= (int)$order['id'] ?></td>
                                <td><?= htmlspecialchars($order['client_name'] ?? '') ?></td>
                                <td><span class="font-monospace"><?= $phone ?></span></td>
                                <td><?= htmlspecialchars($order['wilaya_name'] ?? '') ?></td>
                                <td class="fw-bold">
                                    <?= number_format((float)($order['total'] ?? 0), 0, '.', ' ') ?>
                                    <?= __('ui.currency', 'DA') ?>
                                </td>
                                <td><span class="badge <?= $badgeCls ?> fs-6 px-3"><?= $score ?></span></td>
                                <td>
                                    <?php
                                    foreach (explode(',', $order['fraud_reason'] ?? '') as $r):
                                        $r = trim($r); if (!$r) continue;
                                        $label = match(true) {
                                            str_starts_with($r, 'phone_flood') => __('fraud.reason_phone_flood', 'Phone flood'),
                                            str_starts_with($r, 'ip_flood')    => __('fraud.reason_ip_flood',    'IP flood'),
                                            str_starts_with($r, 'high_return') => __('fraud.reason_return_rate', 'High return rate'),
                                            $r === 'duplicate_order'           => __('fraud.reason_duplicate',   'Duplicate order'),
                                            default                            => $r,
                                        };
                                    ?>
                                        <span class="badge bg-secondary me-1 mb-1"><?= htmlspecialchars($label) ?></span>
                                    <?php endforeach; ?>
                                </td>
                                <td>
                                    <?php if ($returnRate !== null): ?>
                                        <div class="d-flex align-items-center gap-1">
                                            <div class="progress flex-grow-1" style="height:6px;min-width:60px;">
                                                <div class="progress-bar <?= $returnRate >= 60 ? 'bg-danger' : 'bg-warning' ?>"
                                                     style="width:<?= min(100, $returnRate) ?>%"></div>
                                            </div>
                                            <small class="<?= $returnRate >= 60 ? 'text-danger' : 'text-warning' ?> fw-bold"><?= $returnRate ?>%</small>
                                        </div>
                                    <?php else: ?><small class="text-muted">—</small><?php endif; ?>
                                </td>
                                <td><small class="text-muted"><?= date('d/m/Y H:i', strtotime($order['created_at'])) ?></small></td>
                                <td class="text-end">
                                    <div class="d-flex gap-1 justify-content-end">
                                        <button class="btn btn-sm btn-success"
                                                title="<?= __('fraud.action_approve', 'Approve Order') ?>"
                                                onclick="approveOrder(<?= (int)$order['id'] ?>)">
                                            <i class="bi bi-check-lg"></i>
                                        </button>
                                        <button class="btn btn-sm btn-warning"
                                                title="<?= __('fraud.action_ban_phone', 'Ban Phone') ?>"
                                                onclick="banPhone('<?= $phone ?>', <?= (int)$order['id'] ?>)">
                                            <i class="bi bi-telephone-x"></i>
                                        </button>
                                        <button class="btn btn-sm btn-danger"
                                                title="<?= __('fraud.action_cancel', 'Cancel Order') ?>"
                                                onclick="cancelOrder(<?= (int)$order['id'] ?>)">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>

        <?php if ($total_pages > 1): ?>
        <div class="card-footer bg-body d-flex justify-content-center">
            <ul class="pagination pagination-sm mb-0">
                <li class="page-item <?= $current_page <= 1 ? 'disabled' : '' ?>">
                    <a class="page-link" href="?tab=orders&page=<?= $current_page - 1 ?>&<?= http_build_query(array_diff_key($_GET, ['page'=>'','tab'=>''])) ?>">&laquo;</a>
                </li>
                <?php for ($p = 1; $p <= $total_pages; $p++): ?>
                    <li class="page-item <?= $p === $current_page ? 'active' : '' ?>">
                        <a class="page-link" href="?tab=orders&page=<?= $p ?>&<?= http_build_query(array_diff_key($_GET, ['page'=>'','tab'=>''])) ?>"><?= $p ?></a>
                    </li>
                <?php endfor; ?>
                <li class="page-item <?= $current_page >= $total_pages ? 'disabled' : '' ?>">
                    <a class="page-link" href="?tab=orders&page=<?= $current_page + 1 ?>&<?= http_build_query(array_diff_key($_GET, ['page'=>'','tab'=>''])) ?>">&raquo;</a>
                </li>
            </ul>
        </div>
        <?php endif; ?>

    </div>

    <?php else: ?>

    <!-- ===== TAB: REJECTED ATTEMPTS ===== -->
    <div class="card border-0 shadow-sm border-top-0" style="border-radius:0 0 .5rem .5rem;">

        <!-- فلتر -->
        <div class="card-header bg-body border-bottom">
            <form method="GET" action="/admin/suspicious-orders" class="row g-2 align-items-center">
                <input type="hidden" name="tab" value="attempts">
                <div class="col-auto">
                    <input type="text" name="attempts_phone" class="form-control form-control-sm"
                           placeholder="<?= __('fraud.filter_phone', 'Search by phone...') ?>"
                           value="<?= htmlspecialchars($attempts_filter) ?>">
                </div>
                <div class="col-auto">
                    <button class="btn btn-sm btn-primary"><i class="bi bi-search me-1"></i><?= __('actions.search', 'Search') ?></button>
                    <a href="/admin/suspicious-orders?tab=attempts" class="btn btn-sm btn-outline-secondary ms-1"><?= __('actions.reset', 'Reset') ?></a>
                </div>
                <div class="col-auto ms-auto">
                    <small class="text-muted"><?= (int)$attempts_total ?> <?= __('fraud.attempts_total', 'total attempts') ?></small>
                </div>
            </form>
        </div>

        <div class="card-body p-0">
            <?php if (empty($attempts)): ?>
                <div class="text-center py-5">
                    <i class="bi bi-check-circle display-4 text-success mb-3 d-block"></i>
                    <h5 class="text-muted"><?= __('fraud.no_attempts', 'No rejected attempts yet') ?></h5>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th><?= __('fraud.col_phone',   'Phone') ?></th>
                                <th><?= __('fraud.col_client',  'Name') ?></th>
                                <th>IP</th>
                                <th><?= __('fraud.col_reason',  'Reason') ?></th>
                                <th><?= __('fraud.col_risk',    'Score') ?></th>
                                <th><?= __('fraud.attempt_count', 'Attempts') ?></th>
                                <th><?= __('fraud.col_date',    'Date') ?></th>
                                <th class="text-end"><?= __('fraud.col_actions', 'Actions') ?></th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($attempts as $a): ?>
                            <?php
                            $aPhone = htmlspecialchars($a['phone'] ?? '');
                            $isBanned = ($a['reason'] === 'phone_banned');
                            $rowCls = $isBanned ? 'table-danger' : 'table-warning';
                            ?>
                            <tr class="<?= $rowCls ?>" id="attempt-row-<?= (int)$a['id'] ?>">
                                <td><span class="font-monospace fw-bold"><?= $aPhone ?></span></td>
                                <td><?= htmlspecialchars($a['full_name'] ?? '—') ?></td>
                                <td><small class="text-muted font-monospace"><?= htmlspecialchars($a['ip'] ?? '') ?></small></td>
                                <td>
                                    <?php if ($isBanned): ?>
                                        <span class="badge bg-danger"><?= __('fraud.reason_phone_banned', 'Phone banned') ?></span>
                                    <?php else: ?>
                                        <span class="badge bg-warning text-dark"><?= __('fraud.reason_suspicious', 'Suspicious') ?></span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if ((int)$a['fraud_score'] > 0): ?>
                                        <span class="badge bg-secondary"><?= (int)$a['fraud_score'] ?></span>
                                    <?php else: ?>
                                        <small class="text-muted">—</small>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="badge bg-dark"><?= (int)($a['attempts_count'] ?? 1) ?></span>
                                </td>
                                <td><small class="text-muted"><?= date('d/m/Y H:i', strtotime($a['created_at'])) ?></small></td>
                                <td class="text-end">
                                    <button class="btn btn-sm btn-outline-danger"
                                            title="<?= __('fraud.action_ban_phone', 'Ban Phone') ?>"
                                            onclick="banPhoneFromAttempt('<?= $aPhone ?>')">
                                        <i class="bi bi-telephone-x"></i>
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>

        <?php if ($attempts_pages > 1): ?>
        <div class="card-footer bg-body d-flex justify-content-center">
            <ul class="pagination pagination-sm mb-0">
                <li class="page-item <?= $current_page <= 1 ? 'disabled' : '' ?>">
                    <a class="page-link" href="?tab=attempts&page=<?= $current_page - 1 ?>">&laquo;</a>
                </li>
                <?php for ($p = 1; $p <= $attempts_pages; $p++): ?>
                    <li class="page-item <?= $p === $current_page ? 'active' : '' ?>">
                        <a class="page-link" href="?tab=attempts&page=<?= $p ?>"><?= $p ?></a>
                    </li>
                <?php endfor; ?>
                <li class="page-item <?= $current_page >= $attempts_pages ? 'disabled' : '' ?>">
                    <a class="page-link" href="?tab=attempts&page=<?= $current_page + 1 ?>">&raquo;</a>
                </li>
            </ul>
        </div>
        <?php endif; ?>

    </div>
    <?php endif; ?>

</div>


<!-- ===== MODAL: الهواتف المحظورة ===== -->
<div class="modal fade" id="bannedPhonesModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="bi bi-telephone-x me-2 text-danger"></i>
                    <?= __('fraud.banned_phones_list', 'Banned Phone Numbers') ?>
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="card bg-light border-0 mb-3">
                    <div class="card-body">
                        <h6><?= __('fraud.ban_manually', 'Ban a phone number manually') ?></h6>
                        <div class="row g-2">
                            <div class="col-md-5">
                                <input type="text" id="newBanPhone" class="form-control" placeholder="0551234567">
                            </div>
                            <div class="col-md-5">
                                <input type="text" id="newBanReason" class="form-control"
                                       placeholder="<?= __('fraud.ban_reason', 'Reason (optional)') ?>">
                            </div>
                            <div class="col-md-2">
                                <button class="btn btn-danger w-100" onclick="addBanPhone()">
                                    <i class="bi bi-plus"></i> <?= __('actions.ban', 'Ban') ?>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <div id="bannedPhonesList">
                    <?php if (empty($banned_phones)): ?>
                        <p class="text-muted text-center py-3"><?= __('fraud.no_banned_phones', 'No banned phone numbers yet') ?></p>
                    <?php else: ?>
                        <table class="table table-sm table-bordered align-middle mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th><?= __('fraud.col_phone',  'Phone') ?></th>
                                    <th><?= __('fraud.ban_reason', 'Reason') ?></th>
                                    <th><?= __('fraud.col_date',   'Date') ?></th>
                                    <th></th>
                                </tr>
                            </thead>
                            <tbody>
                            <?php foreach ($banned_phones as $bp): ?>
                                <tr id="ban-row-<?= htmlspecialchars($bp['phone']) ?>">
                                    <td class="font-monospace fw-bold"><?= htmlspecialchars($bp['phone']) ?></td>
                                    <td class="text-muted small"><?= htmlspecialchars($bp['reason'] ?? '—') ?></td>
                                    <td class="text-muted small"><?= date('d/m/Y', strtotime($bp['created_at'])) ?></td>
                                    <td class="text-end">
                                        <button class="btn btn-sm btn-outline-success"
                                                onclick="unbanPhone('<?= htmlspecialchars($bp['phone']) ?>')">
                                            <i class="bi bi-unlock"></i> <?= __('fraud.unban', 'Unban') ?>
                                        </button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php endif; ?>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    <?= __('actions.close', 'Close') ?>
                </button>
            </div>
        </div>
    </div>
</div>


<!-- ===== JAVASCRIPT ===== -->
<script>
const CSRF = '<?= \Core\System\Csrf::token() ?>';

function approveOrder(orderId) {
    if (!confirm('<?= __('fraud.confirm_approve', 'Approve this order?') ?>')) return;
    fetch('/admin/suspicious-orders/approve/' + orderId, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ _csrf: CSRF })
    }).then(r => r.json()).then(data => {
        if (data.success) {
            document.getElementById('order-row-' + orderId)?.remove();
            showToast('<?= __('fraud.approved_msg', 'Order approved') ?>', 'success');
        } else showToast(data.message || 'Error', 'danger');
    });
}

function banPhone(phone, orderId) {
    const reason = prompt('<?= __('fraud.ban_reason_prompt', 'Reason (optional):') ?>');
    if (reason === null) return;
    fetch('/admin/suspicious-orders/ban-phone', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ phone, reason, order_id: orderId, _csrf: CSRF })
    }).then(r => r.json()).then(data => {
        if (data.success) showToast('<?= __('fraud.phone_banned_msg', 'Phone banned') ?>', 'warning');
        else showToast(data.message || 'Error', 'danger');
    });
}

function banPhoneFromAttempt(phone) {
    const reason = prompt('<?= __('fraud.ban_reason_prompt', 'Reason (optional):') ?>');
    if (reason === null) return;
    fetch('/admin/suspicious-orders/ban-phone', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ phone, reason, _csrf: CSRF })
    }).then(r => r.json()).then(data => {
        if (data.success) {
            showToast('<?= __('fraud.phone_banned_msg', 'Phone banned') ?>', 'warning');
            // تلوين الصف
            document.querySelectorAll('td .font-monospace').forEach(el => {
                if (el.textContent.trim() === phone) {
                    el.closest('tr')?.classList.add('opacity-50', 'table-danger');
                }
            });
        } else showToast(data.message || 'Error', 'danger');
    });
}

function cancelOrder(orderId) {
    if (!confirm('<?= __('fraud.confirm_cancel', 'Cancel this order?') ?>')) return;
    fetch('/admin/suspicious-orders/cancel/' + orderId, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ _csrf: CSRF })
    }).then(r => r.json()).then(data => {
        if (data.success) {
            document.getElementById('order-row-' + orderId)?.remove();
            showToast('<?= __('fraud.cancelled_msg', 'Order cancelled') ?>', 'success');
        } else showToast(data.message || 'Error', 'danger');
    });
}

function addBanPhone() {
    const phone  = document.getElementById('newBanPhone').value.trim();
    const reason = document.getElementById('newBanReason').value.trim();
    if (!phone) { showToast('<?= __('fraud.phone_required', 'Phone required') ?>', 'warning'); return; }

    fetch('/admin/suspicious-orders/ban-phone', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ phone, reason, _csrf: CSRF })
    }).then(r => r.json()).then(data => {
        if (data.success) {
            document.getElementById('newBanPhone').value  = '';
            document.getElementById('newBanReason').value = '';
            const container = document.getElementById('bannedPhonesList');
            let tbody = container.querySelector('tbody');
            if (!tbody) {
                container.innerHTML = `<table class="table table-sm table-bordered align-middle mb-0">
                    <thead class="table-light"><tr>
                        <th><?= __('fraud.col_phone','Phone') ?></th>
                        <th><?= __('fraud.ban_reason','Reason') ?></th>
                        <th><?= __('fraud.col_date','Date') ?></th>
                        <th></th>
                    </tr></thead><tbody></tbody></table>`;
                tbody = container.querySelector('tbody');
            }
            const tr = document.createElement('tr');
            tr.id = 'ban-row-' + phone;
            tr.innerHTML = `<td class="font-monospace fw-bold">${phone}</td>
                <td class="text-muted small">${reason||'—'}</td>
                <td class="text-muted small"><?= date('d/m/Y') ?></td>
                <td class="text-end"><button class="btn btn-sm btn-outline-success" onclick="unbanPhone('${phone}')">
                    <i class="bi bi-unlock"></i> <?= __('fraud.unban','Unban') ?>
                </button></td>`;
            tbody.appendChild(tr);
            showToast('<?= __('fraud.phone_banned_msg','Phone banned') ?>', 'warning');
        } else showToast(data.message || 'Error', 'danger');
    }).catch(() => showToast('Connection error', 'danger'));
}

function unbanPhone(phone) {
    if (!confirm('<?= __('fraud.confirm_unban', 'Remove ban?') ?>')) return;
    fetch('/admin/suspicious-orders/unban-phone', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ phone, _csrf: CSRF })
    }).then(r => r.json()).then(data => {
        if (data.success) {
            document.getElementById('ban-row-' + phone)?.remove();
            showToast('<?= __('fraud.unbanned_msg', 'Phone unbanned') ?>', 'success');
        } else showToast(data.message || 'Error', 'danger');
    });
}

function showToast(message, type = 'success') {
    const container = document.getElementById('toastContainer') || (() => {
        const div = document.createElement('div');
        div.id = 'toastContainer';
        div.style.cssText = 'position:fixed;top:20px;right:20px;z-index:9999;display:flex;flex-direction:column;gap:8px;';
        document.body.appendChild(div);
        return div;
    })();
    const toast = document.createElement('div');
    toast.className = `alert alert-${type} shadow d-flex align-items-center mb-0`;
    toast.style.cssText = 'min-width:280px;animation:fadeIn .3s ease;';
    toast.innerHTML = `<i class="bi bi-${type==='success'?'check-circle':type==='danger'?'x-circle':'exclamation-triangle'} me-2"></i>${message}`;
    container.appendChild(toast);
    setTimeout(() => toast.remove(), 3500);
}
</script>

<style>
@keyframes fadeIn { from { opacity:0; transform:translateY(-8px); } to { opacity:1; transform:translateY(0); } }
.font-monospace { font-family: monospace; }
</style>-e 
</div></section></div>