<?php
require_once dirname(__DIR__) . '/includes/auth.php';
require_once dirname(__DIR__) . '/includes/revenda_schema.php';
require_once dirname(__DIR__) . '/includes/branding.php';

revenda_ensure_schema($db);

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

function rv_h($v): string { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
function rv_date_for_input($value): string {
    $raw = trim((string)$value);
    if ($raw === '' || $raw === '0') return '';
    if (ctype_digit($raw)) return date('Y-m-d', (int)$raw);
    $ts = strtotime($raw);
    return $ts ? date('Y-m-d', $ts) : '';
}
function rv_status_badge(string $status, $vencimento): string {
    $status = trim($status) ?: 'ativo';
    if (revenda_is_expired($vencimento)) return '<span class="badge bg-danger">Vencido</span>';
    if ($status === 'ativo') return '<span class="badge bg-success">Ativo</span>';
    return '<span class="badge bg-secondary">Inativo</span>';
}
function rv_unique_login(PDO $db, string $username, int $ignoreId = 0): bool {
    $st = $db->prepare('SELECT id FROM revendedores WHERE lower(username)=lower(?) AND id<>? LIMIT 1');
    $st->execute([$username, $ignoreId]);
    if ($st->fetch(PDO::FETCH_ASSOC)) return false;
    $st2 = $db->prepare('SELECT id FROM panel_users WHERE lower(username)=lower(?) LIMIT 1');
    $st2->execute([$username]);
    return !$st2->fetch(PDO::FETCH_ASSOC);
}

$msg = '';
$msgType = 'success';
$editRow = null;

if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    if ($id > 0) {
        $logoSt = $db->prepare('SELECT logo_path FROM revendedores WHERE id=? LIMIT 1');
        $logoSt->execute([$id]);
        $revendaLogoToDelete = (string)($logoSt->fetchColumn() ?: '');
        $db->beginTransaction();
        try {
            // Limpa primeiro os dados dependentes, preservando o isolamento entre revendas.
            try { $db->prepare('DELETE FROM online_status WHERE usuario_id=? OR mac IN (SELECT mac FROM usuarios WHERE usuario_id=?)')->execute([$id, $id]); } catch (Throwable $ignored) {}
            try { $db->prepare('DELETE FROM app_pairing_codes WHERE revendedor_id=? OR mac IN (SELECT mac FROM usuarios WHERE usuario_id=?)')->execute([$id, $id]); } catch (Throwable $ignored) {}
            try { $db->prepare('DELETE FROM device_pending_info WHERE mac IN (SELECT mac FROM usuarios WHERE usuario_id=?)')->execute([$id]); } catch (Throwable $ignored) {}
            try { $db->prepare('DELETE FROM mac_messages WHERE usuario_id=? OR mac IN (SELECT mac FROM usuarios WHERE usuario_id=?)')->execute([$id, $id]); } catch (Throwable $ignored) {}
            try { $db->prepare('DELETE FROM access_rules WHERE usuario_id=? OR mac IN (SELECT mac FROM usuarios WHERE usuario_id=?)')->execute([$id, $id]); } catch (Throwable $ignored) {}
            $db->prepare('DELETE FROM revendedor_dns WHERE revendedor_id=?')->execute([$id]);
            $db->prepare('DELETE FROM revendedor_clientes WHERE revendedor_id=?')->execute([$id]);
            $db->prepare('DELETE FROM usuarios WHERE usuario_id=?')->execute([$id]);
            $db->prepare("DELETE FROM branding_assets WHERE owner_type='revendedor' AND owner_id=?")->execute([$id]);
            $db->prepare('DELETE FROM revendedores WHERE id=?')->execute([$id]);
            $db->commit();
            if ($revendaLogoToDelete !== '') media_delete_relative_file($revendaLogoToDelete);
            header('Location: revendas.php?r=deleted');
            exit;
        } catch (Throwable $e) {
            if ($db->inTransaction()) $db->rollBack();
            $msg = 'Erro ao apagar revenda.';
            $msgType = 'danger';
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_revenda'])) {
    $id = (int)($_POST['id'] ?? 0);
    $nome = trim((string)($_POST['nome'] ?? ''));
    $username = trim((string)($_POST['username'] ?? ''));
    $password = trim((string)($_POST['password'] ?? ''));
    $whatsapp = preg_replace('/\D+/', '', (string)($_POST['whatsapp'] ?? ''));
    $macLimit = max(0, (int)($_POST['mac_limit'] ?? 0));
    $status = trim((string)($_POST['status'] ?? 'ativo'));
    if (!in_array($status, ['ativo', 'inativo'], true)) $status = 'ativo';
    $vencInput = trim((string)($_POST['vencimento'] ?? ''));
    $vencimento = $vencInput !== '' ? $vencInput : '';

    if ($nome === '' || $username === '') {
        $msg = 'Informe nome e login da revenda.';
        $msgType = 'danger';
    } elseif (!preg_match('/^[A-Za-z0-9_.-]{3,60}$/', $username)) {
        $msg = 'Login inválido. Use letras, números, ponto, hífen ou underline.';
        $msgType = 'danger';
    } elseif ($id <= 0 && strlen($password) < 4) {
        $msg = 'Senha obrigatória com no mínimo 4 caracteres.';
        $msgType = 'danger';
    } elseif ($password !== '' && strlen($password) < 4) {
        $msg = 'A nova senha precisa ter no mínimo 4 caracteres.';
        $msgType = 'danger';
    } elseif (!rv_unique_login($db, $username, $id)) {
        $msg = 'Esse login já está em uso.';
        $msgType = 'danger';
    } else {
        if ($id > 0) {
            if ($password !== '') {
                $hash = password_hash($password, PASSWORD_DEFAULT);
                $st = $db->prepare("UPDATE revendedores SET nome=?, username=?, password=?, email=?, whatsapp=?, mac_limit=?, vencimento=?, status=?, updated_at=strftime('%s','now') WHERE id=?");
                $st->execute([$nome, $username, $hash, $username . '@revenda.local', $whatsapp, $macLimit, $vencimento, $status, $id]);
            } else {
                $st = $db->prepare("UPDATE revendedores SET nome=?, username=?, email=?, whatsapp=?, mac_limit=?, vencimento=?, status=?, updated_at=strftime('%s','now') WHERE id=?");
                $st->execute([$nome, $username, $username . '@revenda.local', $whatsapp, $macLimit, $vencimento, $status, $id]);
            }
            header('Location: revendas.php?r=updated');
            exit;
        }

        $hash = password_hash($password, PASSWORD_DEFAULT);
        $st = $db->prepare("INSERT INTO revendedores (nome, username, password, email, whatsapp, mac_limit, vencimento, status, creditos, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, strftime('%s','now'), strftime('%s','now'))");
        $st->execute([$nome, $username, $hash, $username . '@revenda.local', $whatsapp, $macLimit, $vencimento, $status]);
        header('Location: revendas.php?r=created');
        exit;
    }
}

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

if (isset($_GET['r'])) {
    $map = ['created' => 'Revenda criada com sucesso.', 'updated' => 'Revenda atualizada com sucesso.', 'deleted' => 'Revenda apagada com sucesso.'];
    $msg = $map[(string)$_GET['r']] ?? $msg;
    $msgType = 'success';
}

$showForm = isset($_GET['create']) || $editRow;
$rows = $db->query("SELECT r.*, (SELECT COUNT(*) FROM usuarios u WHERE u.usuario_id=r.id) AS total_macs, (SELECT COUNT(*) FROM revendedor_dns d WHERE d.revendedor_id=r.id) AS total_dns FROM revendedores r ORDER BY r.id DESC")->fetchAll(PDO::FETCH_ASSOC) ?: [];
$rvTotal = count($rows);
$rvAtivas = count(array_filter($rows, fn($r) => (($r['status'] ?? '') === 'ativo') && !revenda_is_expired($r['vencimento'] ?? '')));
$rvVencidas = count(array_filter($rows, fn($r) => revenda_is_expired($r['vencimento'] ?? '')));
$rvClientes = array_sum(array_map(fn($r) => (int)($r['total_macs'] ?? 0), $rows));

require_once __DIR__ . '/../includes/header.php';
?>
<div class="rev-wrap">
    <div class="rev-kpis">
        <div class="rev-kpi"><span>Total de revendas</span><strong><?= (int)$rvTotal ?></strong></div>
        <div class="rev-kpi"><span>Revendas ativas</span><strong><?= (int)$rvAtivas ?></strong></div>
        <div class="rev-kpi"><span>Vencidas</span><strong><?= (int)$rvVencidas ?></strong></div>
        <div class="rev-kpi"><span>Clientes vinculados</span><strong><?= (int)$rvClientes ?></strong></div>
    </div>
    <?php if ($msg !== ''): ?><div class="alert alert-<?= rv_h($msgType) ?>"><?= rv_h($msg) ?></div><?php endif; ?>

    <?php if ($showForm): ?>
        <?php $f = $editRow ?: ['id'=>0,'nome'=>'','username'=>'','whatsapp'=>'','mac_limit'=>0,'vencimento'=>'','status'=>'ativo']; ?>
        <div class="card radius-10 rev-card mb-3">
            <div class="card-header bg-transparent rev-header">
                <div class="rev-title"><div class="ic"><i class="bi bi-person-gear"></i></div><div><h5><?= $editRow ? 'Editar Revenda' : 'Criar Revenda' ?></h5><span>Login próprio no painel, limite de MACs, nome e WhatsApp</span></div></div>
                <a href="revendas.php" class="btn btn-outline-secondary"><i class="bi bi-arrow-left"></i> Voltar</a>
            </div>
            <div class="card-body">
                <form method="post" class="row g-3" autocomplete="off">
                    <input type="hidden" name="save_revenda" value="1">
                    <input type="hidden" name="id" value="<?= (int)$f['id'] ?>">
                    <div class="col-lg-4 col-md-6 col-12"><label class="form-label fw-bold">Nome da revenda</label><input class="form-control input-radius" name="nome" value="<?= rv_h($f['nome']) ?>" required></div>
                    <div class="col-lg-4 col-md-6 col-12"><label class="form-label fw-bold">Login</label><input class="form-control input-radius" name="username" value="<?= rv_h($f['username']) ?>" required></div>
                    <div class="col-lg-4 col-md-6 col-12"><label class="form-label fw-bold"><?= $editRow ? 'Nova senha (opcional)' : 'Senha' ?></label><input type="password" class="form-control input-radius" name="password" <?= $editRow ? '' : 'required' ?>></div>
                    <div class="col-lg-3 col-md-6 col-12"><label class="form-label fw-bold">WhatsApp</label><input class="form-control input-radius" name="whatsapp" value="<?= rv_h($f['whatsapp']) ?>" placeholder="5511999999999"></div>
                    <div class="col-lg-3 col-md-6 col-12"><label class="form-label fw-bold">Limite de MACs</label><input type="number" min="0" class="form-control input-radius" name="mac_limit" value="<?= (int)$f['mac_limit'] ?>"><small class="text-muted">0 = ilimitado</small></div>
                    <div class="col-lg-3 col-md-6 col-12"><label class="form-label fw-bold">Vencimento</label><input type="date" class="form-control input-radius" name="vencimento" value="<?= rv_h(rv_date_for_input($f['vencimento'])) ?>"></div>
                    <div class="col-lg-3 col-md-6 col-12"><label class="form-label fw-bold">Status</label><select class="form-select input-radius" name="status"><option value="ativo" <?= ($f['status'] ?? '') === 'ativo' ? 'selected' : '' ?>>Ativo</option><option value="inativo" <?= ($f['status'] ?? '') === 'inativo' ? 'selected' : '' ?>>Inativo</option></select></div>
                    <div class="col-12 d-flex justify-content-end gap-2 flex-wrap"><a href="revendas.php" class="btn btn-secondary"><i class="bi bi-x-circle"></i> Cancelar</a><button class="btn btn-success"><i class="bi bi-save2"></i> Salvar Revenda</button></div>
                </form>
            </div>
        </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-shop"></i></div><div><h5>Revendas</h5><span>Crie, edite, apague e acompanhe clientes de cada revenda</span></div></div>
            <div class="d-flex gap-2 flex-wrap"><input id="revSearch" class="form-control rev-search" placeholder="Buscar por nome, login ou WhatsApp"><a href="revendas.php?create=1" class="btn btn-primary"><i class="bi bi-plus-lg"></i> Criar Revenda</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>ID</th><th>Logo</th><th>Nome</th><th>Login</th><th>WhatsApp</th><th>MACs</th><th>DNS</th><th>Status</th><th>Vencimento</th><th class="text-end">Ações</th></tr></thead>
                    <tbody>
                    <?php if (!$rows): ?><tr><td colspan="10" class="text-center py-4">Nenhuma revenda cadastrada.</td></tr><?php endif; ?>
                    <?php foreach ($rows as $r): ?>
                        <?php $limit = (int)($r['mac_limit'] ?? 0); $used=(int)($r['total_macs'] ?? 0); $limitTxt = $limit <= 0 ? 'Ilimitado' : $used . '/' . $limit; $limitCls = ($limit > 0 && $used >= $limit) ? 'limit-full' : 'limit-ok'; ?>
                        <?php $revLogoUrl = branding_logo_url($db, 'revendedor', (int)$r['id']); $hasOwnLogo = trim((string)($r['logo_path'] ?? '')) !== '' && is_file(media_absolute_path((string)$r['logo_path'])); ?>
                        <tr class="rev-row" data-search="<?= rv_h(strtolower(($r['nome'] ?? '') . ' ' . ($r['username'] ?? '') . ' ' . ($r['whatsapp'] ?? ''))) ?>">
                            <td>#<?= (int)$r['id'] ?></td>
                            <td><div class="rev-logo-wrap"><img class="rev-logo" src="<?= rv_h($revLogoUrl) ?>" alt="Logo da revenda" loading="lazy" data-image-error="invisible"><span class="rev-logo-tag"><?= $hasOwnLogo ? 'Própria' : 'Global' ?></span></div></td>
                            <td><strong><?= rv_h($r['nome'] ?: $r['username']) ?></strong></td>
                            <td><?= rv_h($r['username']) ?></td>
                            <td><?= rv_h($r['whatsapp'] ?: '—') ?></td>
                            <td><span class="stat-pill <?= $limitCls ?>"><i class="bi bi-hdd-network"></i><?= rv_h($limitTxt) ?></span></td>
                            <td><span class="stat-pill"><i class="bi bi-globe"></i><?= (int)($r['total_dns'] ?? 0) ?></span></td>
                            <td><?= rv_status_badge((string)($r['status'] ?? ''), $r['vencimento'] ?? '') ?></td>
                            <td><?= rv_h(rv_date_for_input($r['vencimento'] ?? '') ?: '—') ?></td>
                            <td><div class="actions"><a class="btn btn-sm btn-outline-info" href="revendas_clientes.php?id=<?= (int)$r['id'] ?>"><i class="bi bi-people"></i> Ver clientes</a><a class="btn btn-sm btn-outline-success" href="logo.php?revendedor_id=<?= (int)$r['id'] ?>"><i class="bi bi-image"></i> Logo</a><a class="btn btn-sm btn-outline-primary" href="revendas.php?edit=<?= (int)$r['id'] ?>"><i class="bi bi-pencil"></i> Editar</a><a class="btn btn-sm btn-outline-danger" data-confirm="Apagar esta revenda e todos os clientes dela?" href="revendas.php?delete=<?= (int)$r['id'] ?>"><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'; ?>
