<?php
require_once __DIR__ . '/../includes/header.php';
require_admin();
$pdo = db();
$plansStmt = $pdo->query("SELECT * FROM plans ORDER BY price ASC, name ASC");
$plans = $plansStmt->fetchAll();

$errors = [];
$editingUser = null;
$selectedPlanId = $plans[0]['id'] ?? null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'create_user' || $action === 'update_user') {
        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $role = $_POST['role'] ?? 'user';
        $password = $_POST['password'] ?? '';
        $active = isset($_POST['active']) ? 1 : 0;
        $planId = isset($_POST['plan_id']) ? (int)$_POST['plan_id'] : 0;
        if ($planId) {
            $selectedPlanId = $planId;
        }

        if (!$name) {
            $errors[] = 'Informe o nome.';
        }
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors[] = 'E-mail inválido.';
        }
        if (!in_array($role, ['admin', 'user'], true)) {
            $errors[] = 'Função inválida.';
        }
        if ($action === 'create_user' && !$password) {
            $errors[] = 'Defina uma senha para o novo usuário.';
        }
        if (!$planId) {
            $errors[] = 'Selecione um plano.';
        } else {
            $stmtPlan = $pdo->prepare("SELECT id FROM plans WHERE id = ? LIMIT 1");
            $stmtPlan->execute([$planId]);
            if (!$stmtPlan->fetch()) {
                $errors[] = 'Plano selecionado inválido.';
            }
        }

        if ($action === 'update_user') {
            $userId = (int)($_POST['user_id'] ?? 0);
            $editingUser = $pdo->prepare("SELECT * FROM users WHERE id = ? LIMIT 1");
            $editingUser->execute([$userId]);
            $editingUser = $editingUser->fetch();
            if (!$editingUser) {
                $errors[] = 'Usuário não encontrado.';
            }
        }

        if (!$errors) {
            $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ? " . ($action === 'update_user' ? "AND id <> ?" : ""));
            $params = [$email];
            if ($action === 'update_user' && $editingUser) {
                $params[] = $editingUser['id'];
            }
            $stmt->execute($params);
            if ($stmt->fetch()) {
                $errors[] = 'Este e-mail já está em uso.';
            }
        }

        if (!$errors) {
            if ($action === 'create_user') {
                $hash = password_hash($password, PASSWORD_DEFAULT);
                $stmt = $pdo->prepare("INSERT INTO users (name, email, password_hash, role, active) VALUES (?, ?, ?, ?, ?)");
                $stmt->execute([$name, $email, $hash, $role, $active]);
                $newUserId = (int)$pdo->lastInsertId();
                if ($planId) {
                    $pdo->prepare("INSERT INTO subscriptions (user_id, plan_id) VALUES (?, ?)")->execute([$newUserId, $planId]);
                }
            } else {
                $params = [$name, $email, $role, $active];
                $sql = "UPDATE users SET name = ?, email = ?, role = ?, active = ?";
                if ($password) {
                    $hash = password_hash($password, PASSWORD_DEFAULT);
                    $sql .= ", password_hash = ?";
                    $params[] = $hash;
                }
                $sql .= " WHERE id = ?";
                $params[] = $editingUser['id'];
                $stmt = $pdo->prepare($sql);
                $stmt->execute($params);
                if ($planId) {
                    $currentPlan = get_user_plan($editingUser['id']);
                    if (!$currentPlan || (int)$currentPlan['id'] !== $planId) {
                        $pdo->prepare("INSERT INTO subscriptions (user_id, plan_id) VALUES (?, ?)")->execute([$editingUser['id'], $planId]);
                    }
                }
            }
            redirect("index.php?page=admin_users");
        } else {
            $editingUser = $editingUser ?: [
                'id' => $action === 'create_user' ? null : (int)($_POST['user_id'] ?? 0),
                'name' => $name,
                'email' => $email,
                'role' => $role,
                'active' => $active
            ];
        }
    } elseif ($action === 'delete_user' && isset($_POST['user_id'])) {
        $userId = (int)$_POST['user_id'];
        if ($userId === (int)$user['id']) {
            $errors[] = 'Você não pode excluir seu próprio usuário.';
        } else {
            $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
            $stmt->execute([$userId]);
            redirect("index.php?page=admin_users");
        }
    }
}

if (isset($_GET['edit']) && ctype_digit($_GET['edit'])) {
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ? LIMIT 1");
    $stmt->execute([(int)$_GET['edit']]);
    $editingUser = $stmt->fetch();
    if ($editingUser) {
        $planInfo = get_user_plan($editingUser['id']);
        if ($planInfo) {
            $selectedPlanId = $planInfo['id'];
        }
    }
}

if (isset($_GET['toggle']) && ctype_digit($_GET['toggle'])) {
    $id = (int)$_GET['toggle'];
    $pdo->prepare("UPDATE users SET active = NOT active WHERE id = ?")->execute([$id]);
    redirect("index.php?page=admin_users");
}

$stmt = $pdo->query("SELECT * FROM users ORDER BY created_at DESC");
$users = $stmt->fetchAll();
?>

<div class="card">
    <h2><?php echo $editingUser ? 'Editar usuário' : 'Novo usuário'; ?></h2>
    <?php if ($errors): ?>
        <div class="card" style="background:#fee2e2;color:#b91c1c;">
            <?php foreach ($errors as $error): ?>
                <p><?php echo h($error); ?></p>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
    <form method="post">
        <input type="hidden" name="action" value="<?php echo $editingUser ? 'update_user' : 'create_user'; ?>">
        <?php if ($editingUser): ?>
            <input type="hidden" name="user_id" value="<?php echo (int)$editingUser['id']; ?>">
        <?php endif; ?>
        <label>Nome</label>
        <input type="text" name="name" value="<?php echo h($editingUser['name'] ?? ''); ?>" required>

        <label>E-mail</label>
        <input type="email" name="email" value="<?php echo h($editingUser['email'] ?? ''); ?>" required>

        <label>Senha <?php echo $editingUser ? '(deixe em branco para manter)' : ''; ?></label>
        <input type="password" name="password" <?php echo $editingUser ? '' : 'required'; ?>>

        <label>Função</label>
        <select name="role" required>
            <option value="user" <?php echo (($editingUser['role'] ?? '') === 'user') ? 'selected' : ''; ?>>Usuário</option>
            <option value="admin" <?php echo (($editingUser['role'] ?? '') === 'admin') ? 'selected' : ''; ?>>Administrador</option>
        </select>

        <label>Plano</label>
        <select name="plan_id" required>
            <option value="">Selecione...</option>
            <?php foreach ($plans as $planOption): ?>
                <option value="<?php echo (int)$planOption['id']; ?>" <?php echo ((int)$selectedPlanId === (int)$planOption['id']) ? 'selected' : ''; ?>>
                    <?php echo h($planOption['name']); ?>
                </option>
            <?php endforeach; ?>
        </select>

        <label><input type="checkbox" name="active" <?php echo (($editingUser['active'] ?? 1) ? 'checked' : ''); ?>> Usuário ativo</label>

        <button type="submit"><?php echo $editingUser ? 'Salvar alterações' : 'Criar usuário'; ?></button>
        <?php if ($editingUser): ?>
            <a class="ghost-button" href="index.php?page=admin_users" style="margin-left:8px;">Cancelar</a>
        <?php endif; ?>
    </form>
</div>

<div class="card">
    <h2>Usuários cadastrados</h2>
    <table>
        <thead>
            <tr>
                <th>Nome</th>
                <th>E-mail</th>
                <th>Função</th>
                <th>Ativo</th>
                <th>Criado em</th>
                <th>Ações</th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($users as $u): ?>
            <tr>
                <td><?php echo h($u['name']); ?></td>
                <td><?php echo h($u['email']); ?></td>
                <td><?php echo h($u['role']); ?></td>
                <td><?php echo $u['active'] ? 'Sim' : 'Não'; ?></td>
                <td><?php echo h($u['created_at']); ?></td>
                <td class="ip-card-actions">
                    <a href="index.php?page=admin_users&edit=<?php echo $u['id']; ?>">Editar</a>
                    <a href="index.php?page=admin_users&toggle=<?php echo $u['id']; ?>">
                        <?php echo $u['active'] ? 'Desativar' : 'Ativar'; ?>
                    </a>
                    <?php if ((int)$u['id'] !== (int)$user['id']): ?>
                        <form method="post" style="display:inline;" onsubmit="return confirm('Excluir este usuário?');">
                            <input type="hidden" name="action" value="delete_user">
                            <input type="hidden" name="user_id" value="<?php echo $u['id']; ?>">
                            <button type="submit" style="background:#dc2626;">Excluir</button>
                        </form>
                    <?php endif; ?>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
