<?php
require_once __DIR__ . '/auth.php';
require_login();
if (!is_master()) { http_response_code(403); die('Acesso negado'); }

$me = current_user();
$errors = [];
$success = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = $_POST['csrf_token'] ?? '';
    if (!verify_csrf($token)) { $errors[] = 'Token inválido.'; }
    else {
        $action = $_POST['action'] ?? '';
        if ($action === 'create') {
            $username = $_POST['username'] ?? '';
            $email = $_POST['email'] ?? '';
            $password = $_POST['password'] ?? '';
            $expires = $_POST['expires_at'] ?? null;
            $active = isset($_POST['active']) ? true : true;
            $err = null;
            $created = register_user($username, $email, $password, 'revendedor', $me['id'], $expires, $err);
            if ($created === false) $errors[] = $err ?: 'Erro ao criar revendedor.';
            else $success = 'Revendedor criado com sucesso.';
        } elseif ($action === 'edit') {
            $id = $_POST['id'] ?? '';
            $patch = [];
            if (isset($_POST['email'])) $patch['email'] = $_POST['email'];
            if (isset($_POST['username'])) $patch['username'] = $_POST['username'];
            if (!empty($_POST['password'])) $patch['password_hash'] = password_hash($_POST['password'], PASSWORD_DEFAULT);
            $patch['expires_at'] = !empty($_POST['expires_at']) ? date(DATE_ATOM, strtotime($_POST['expires_at'])) : null;
            $patch['active'] = isset($_POST['active']) ? true : false;
            $u = find_user_by_id($id);
            if (!$u || ($u['master_id'] ?? null) !== $me['id']) $errors[] = 'Revendedor não encontrado ou sem permissão.';
            else {
                update_user_by_id($id, $patch);
                $success = 'Revendedor atualizado.';
            }
        } elseif ($action === 'delete') {
            $id = $_POST['id'] ?? '';
            $u = find_user_by_id($id);
            if (!$u || ($u['master_id'] ?? null) !== $me['id']) $errors[] = 'Revendedor não encontrado ou sem permissão.';
            else {
                delete_user_by_id($id);
                $success = 'Revendedor removido.';
            }
        } elseif ($action === 'toggle') {
            $id = $_POST['id'] ?? '';
            $u = find_user_by_id($id);
            if (!$u || ($u['master_id'] ?? null) !== $me['id']) $errors[] = 'Revendedor não encontrado ou sem permissão.';
            else {
                $new = empty($u['active']) ? true : false;
                update_user_by_id($id, ['active' => $new]);
                $success = $new ? 'Revendedor ativado.' : 'Revendedor bloqueado.';
            }
        }
    }
}

$revendedores = list_revendedores_by_master($me['id']);
$token = csrf_token();
?>
<!doctype html>
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Gerenciar Revendedores</title>
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
<style>body{background:#0b1220;color:#ecf2ff;font-family:Arial,Helvetica,sans-serif} .card{background:rgba(255,255,255,0.03);padding:16px;border-radius:8px}</style>
</head>
<body class="p-6">
  <div class="max-w-4xl mx-auto">
    <h1 class="text-2xl font-bold mb-3">Gerenciar Revendedores</h1>
    <?php if (!empty($errors)): ?>
      <div class="mb-3 p-3 bg-red-900/20 rounded">
        <?php foreach($errors as $e) echo '<div>'.htmlspecialchars($e).'</div>'; ?>
      </div>
    <?php endif; ?>
    <?php if (!empty($success)): ?>
      <div class="mb-3 p-3 bg-green-900/20 rounded"><?php echo htmlspecialchars($success); ?></div>
    <?php endif; ?>

    <div class="card mb-6">
      <h2 class="font-semibold mb-2">Criar novo revendedor</h2>
      <form method="post" class="grid grid-cols-1 gap-2">
        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($token); ?>">
        <input type="hidden" name="action" value="create">
        <div><label class="block text-sm">Usuário</label><input name="username" required class="w-full p-2 rounded bg-gray-900" /></div>
        <div><label class="block text-sm">Email</label><input name="email" type="email" required class="w-full p-2 rounded bg-gray-900" /></div>
        <div><label class="block text-sm">Senha</label><input name="password" required class="w-full p-2 rounded bg-gray-900" /></div>
        <div><label class="block text-sm">Data de vencimento (opcional)</label><input name="expires_at" type="date" class="p-2 rounded bg-gray-900" /></div>
        <div><label class="inline-flex items-center"><input type="checkbox" name="active" checked class="mr-2">Ativo</label></div>
        <div><button class="bg-indigo-600 py-2 px-4 rounded">Criar revendedor</button></div>
      </form>
    </div>

    <div class="card">
      <h2 class="font-semibold mb-2">Revendedores criados</h2>
      <?php if (empty($revendedores)): ?>
        <div>Nenhum revendedor criado ainda.</div>
      <?php else: ?>
        <table class="w-full text-left text-sm">
          <thead><tr><th>Usuário</th><th>Email</th><th>Vencimento</th><th>Ativo</th><th>Ações</th></tr></thead>
          <tbody>
            <?php foreach ($revendedores as $r): ?>
              <tr class="border-t border-white/5">
                <td class="py-2"><?php echo htmlspecialchars($r['username']); ?></td>
                <td><?php echo htmlspecialchars($r['email']); ?></td>
                <td><?php echo htmlspecialchars($r['expires_at'] ?? '-'); ?></td>
                <td><?php echo (!empty($r['active']) ? 'Sim' : 'Não'); ?></td>
                <td>
                  <form method="post" style="display:inline-block">
                    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($token); ?>">
                    <input type="hidden" name="action" value="toggle">
                    <input type="hidden" name="id" value="<?php echo htmlspecialchars($r['id']); ?>">
                    <button class="bg-yellow-600 text-white py-1 px-2 rounded"><?php echo (!empty($r['active']) ? 'Bloquear' : 'Ativar'); ?></button>
                  </form>

                  <form method="post" style="display:inline-block">
                    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($token); ?>">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="id" value="<?php echo htmlspecialchars($r['id']); ?>">
                    <button onclick="return confirm('Remover revendedor?')" class="bg-red-600 text-white py-1 px-2 rounded">Remover</button>
                  </form>

                  <a href="#edit-<?php echo htmlspecialchars($r['id']); ?>" class="ml-2 text-indigo-300">Editar</a>
                </td>
              </tr>

              <tr id="edit-<?php echo htmlspecialchars($r['id']); ?>" class="bg-white/3">
                <td colspan="5" class="p-3">
                  <form method="post" class="grid grid-cols-1 md:grid-cols-3 gap-2">
                    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($token); ?>">
                    <input type="hidden" name="action" value="edit">
                    <input type="hidden" name="id" value="<?php echo htmlspecialchars($r['id']); ?>">
                    <div><input name="username" value="<?php echo htmlspecialchars($r['username']); ?>" class="w-full p-2 rounded bg-gray-900" /></div>
                    <div><input name="email" value="<?php echo htmlspecialchars($r['email']); ?>" class="w-full p-2 rounded bg-gray-900" /></div>
                    <div><input name="password" placeholder="Nova senha (opcional)" class="w-full p-2 rounded bg-gray-900" /></div>
                    <div><label>Vencimento</label><input name="expires_at" type="date" value="<?php echo !empty($r['expires_at']) ? date('Y-m-d', strtotime($r['expires_at'])) : ''; ?>" class="p-2 rounded bg-gray-900" /></div>
                    <div class="flex items-center"><label><input type="checkbox" name="active" <?php echo (!empty($r['active']) ? 'checked' : ''); ?> class="mr-2">Ativo</label></div>
                    <div class="text-right"><button class="bg-green-600 py-2 px-4 rounded">Salvar</button></div>
                  </form>
                </td>
              </tr>

            <?php endforeach; ?>
          </tbody>
        </table>
      <?php endif; ?>
    </div>

    <div class="mt-4">
      <a href="index.php" class="text-indigo-300">Voltar ao painel</a>
    </div>
  </div>
</body>
</html>