<?php
require_once dirname(__DIR__) . '/includes/auth.php';
require_once dirname(__DIR__) . '/includes/revenda_schema.php';
revenda_ensure_schema($db);

if (!$isAdmin) {
    header('Location: dashboard.php');
    exit;
}

$id = (int)($_GET['id'] ?? 0);
$st = $db->prepare('SELECT * FROM revendedores WHERE id=? LIMIT 1');
$st->execute([$id]);
$rev = $st->fetch(PDO::FETCH_ASSOC) ?: null;
if (!$rev) {
    header('Location: revendas.php');
    exit;
}

if (isset($_GET['delete_mac'])) {
    $mac = trim((string)$_GET['delete_mac']);
    if ($mac !== '') {
        try { $db->prepare('DELETE FROM online_status WHERE mac=? AND usuario_id=?')->execute([$mac, $id]); } catch (Throwable $ignored) {}
        try { $db->prepare('DELETE FROM app_pairing_codes WHERE mac=? AND revendedor_id=?')->execute([$mac, $id]); } catch (Throwable $ignored) {}
        try { $db->prepare('DELETE FROM device_pending_info WHERE mac=?')->execute([$mac]); } catch (Throwable $ignored) {}
        $db->prepare('DELETE FROM usuarios WHERE mac=? AND usuario_id=?')->execute([$mac, $id]);
        $db->prepare('DELETE FROM revendedor_clientes WHERE mac=? AND revendedor_id=?')->execute([$mac, $id]);
        $db->prepare('DELETE FROM mac_messages WHERE mac=? AND usuario_id=?')->execute([$mac, $id]);
        $db->prepare('DELETE FROM access_rules WHERE mac=? AND usuario_id=?')->execute([$mac, $id]);
    }
    header('Location: revendas_clientes.php?id=' . $id . '&r=deleted');
    exit;
}

$limitInfo = revenda_limit_info($db, $id);
$stUsers = $db->prepare('SELECT rowid, * FROM usuarios WHERE usuario_id=? ORDER BY rowid DESC');
$stUsers->execute([$id]);
$clientes = $stUsers->fetchAll(PDO::FETCH_ASSOC) ?: [];
$msg = (($_GET['r'] ?? '') === 'deleted') ? 'Cliente apagado da revenda.' : '';

function rc_h($v): string { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
function rc_venc($v): string { $raw=trim((string)$v); if($raw===''||$raw==='0') return '—'; $ts=ctype_digit($raw)?(int)$raw:strtotime($raw); return $ts?date('d/m/Y H:i',$ts):$raw; }

require_once __DIR__ . '/../includes/header.php';
?>
<div class="rev-wrap">
    <?php if ($msg !== ''): ?><div class="alert alert-success"><?= rc_h($msg) ?></div><?php endif; ?>
    <div class="card radius-10 rev-card">
        <div class="card-header bg-transparent rev-header">
            <div class="rev-title">
                <div class="ic"><i class="bi bi-people-fill"></i></div>
                <div>
                    <h5>Clientes da Revenda: <?= rc_h($rev['nome'] ?: $rev['username']) ?></h5>
                    <span>MACs usados: <?= (int)$limitInfo['used'] ?> / <?= !empty($limitInfo['unlimited']) ? 'Ilimitado' : (int)$limitInfo['limit'] ?> · Login: <?= rc_h($rev['username']) ?></span>
                </div>
            </div>
            <div class="d-flex gap-2 flex-wrap">
                <a href="revendas.php" class="btn btn-outline-secondary"><i class="bi bi-arrow-left"></i> Voltar</a>
            </div>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead><tr><th>MAC</th><th>Cliente</th><th>WhatsApp</th><th>DNS</th><th>Usuário</th><th>Status</th><th>Vencimento</th><th class="text-end">Ações</th></tr></thead>
                    <tbody>
                    <?php if (!$clientes): ?><tr><td colspan="8" class="text-center py-4">Essa revenda ainda não tem clientes.</td></tr><?php endif; ?>
                    <?php foreach ($clientes as $c): ?>
                        <tr>
                            <td><span class="stat-pill"><i class="bi bi-hdd-network"></i><?= rc_h($c['mac']) ?></span></td>
                            <td><?= rc_h($c['nome_cliente'] ?: '—') ?></td>
                            <td><?= rc_h($c['whatsapp'] ?: '—') ?></td>
                            <td><?= rc_h($c['dns'] ?: '—') ?></td>
                            <td><?= rc_h($c['username'] ?: '—') ?></td>
                            <td><?= rc_h($c['status'] ?: '—') ?></td>
                            <td><?= rc_h(rc_venc($c['vencimento'] ?? '')) ?></td>
                            <td><div class="actions"><a class="btn btn-sm btn-outline-danger" data-confirm="Apagar este cliente da revenda?" href="revendas_clientes.php?id=<?= (int)$id ?>&delete_mac=<?= urlencode((string)$c['mac']) ?>"><i class="bi bi-trash"></i> Apagar</a></div></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
