<?php
session_start();

// Redireciona se não estiver autenticado
if (!isset($_SESSION["authenticated"]) || $_SESSION["authenticated"] !== true) {
    header("Location: index.php");
    exit();
}

$databaseFile = "../api/.db.db";
$panelAddress = (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] === "on" ? "https" : "http") . "://" . $_SERVER["HTTP_HOST"] . dirname($_SERVER["PHP_SELF"]);
$username = "admin";
$password = "admin";
$resetSuccess = false;
$errorMessage = "";

if (isset($_POST["reset"])) {
    try {
        $db = new PDO("sqlite:" . $databaseFile);
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        // Delete all existing users
        $db->exec("DELETE FROM users;");

        // Insert new admin user with password 'admin'
        $db->exec("INSERT INTO users (username, password) VALUES (". $db->quote($username) .", ". $db->quote($password) .");");

        $resetSuccess = true;
    } catch (PDOException $e) {
        $errorMessage = "Erro ao redefinir utilizador e senha: " . $e->getMessage();
    }
}
?>
<!DOCTYPE html>
<html lang="pt">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reset de Senha</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #1a1a1a;
            color: #f0f0f0;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            margin: 0;
        }
        .container {
            background-color: #2a2a2a;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 0 15px rgba(0, 0, 0, 0.5);
            text-align: center;
            width: 100%;
            max-width: 500px;
        }
        h1 {
            color: #e0e0e0;
            margin-bottom: 20px;
        }
        .message {
            margin-bottom: 20px;
            font-size: 1.1em;
        }
        .success {
            color: #4CAF50;
        }
        .error {
            color: #ff6b6b;
        }
        .credentials {
            background-color: #3a3a3a;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
            text-align: left;
            word-break: break-all;
        }
        .credentials p {
            margin: 5px 0;
        }
        .buttons button {
            background-color: #007bff;
            color: white;
            padding: 10px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            margin: 5px;
            transition: background-color 0.3s ease;
        }
        .buttons button:hover {
            background-color: #0056b3;
        }
        .buttons button.whatsapp {
            background-color: #25D366;
        }
        .buttons button.whatsapp:hover {
            background-color: #1DA851;
        }
        .buttons button.reset {
            background-color: #dc3545;
        }
        .buttons button.reset:hover {
            background-color: #c82333;
        }
        .logout-btn {
            background-color: #6c757d;
            margin-top: 20px;
        }
        .logout-btn:hover {
            background-color: #5a6268;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Reset de Senha</h1>
        <?php if ($resetSuccess): ?>
            <p class="message success">Senha resetada com sucesso!</p>
            <div class="credentials">
                <p><strong>Endereço do Painel:</strong> <span id="panelAddress"><?php echo htmlspecialchars($panelAddress); ?></span></p>
                <p><strong>Usuário:</strong> <span id="username"><?php echo htmlspecialchars($username); ?></span></p>
                <p><strong>Senha:</strong> <span id="password"><?php echo htmlspecialchars($password); ?></span></p>
            </div>
            <div class="buttons">
                <button onclick="copyCredentials()">Copiar Credenciais</button>
                <button class="whatsapp" onclick="sendToWhatsApp()">Enviar via WhatsApp</button>
            </div>
        <?php elseif ($errorMessage): ?>
            <p class="message error"><?php echo htmlspecialchars($errorMessage); ?></p>
        <?php else: ?>
            <p class="message">Clique no botão abaixo para redefinir o usuário e a senha para 'admin'/'admin'.</p>
        <?php endif; ?>
        <form method="POST" class="buttons">
            <button type="submit" name="reset" class="reset">Resetar Senha</button>
        </form>
        <form action="index.php" method="GET">
            <button type="submit" name="logout" class="logout-btn">Sair</button>
        </form>
    </div>

    <script>
        function copyCredentials() {
            const panelAddress = document.getElementById('panelAddress').innerText;
            const username = document.getElementById('username').innerText;
            const password = document.getElementById('password').innerText;
            const textToCopy = `Endereço do Painel: ${panelAddress}\nUsuário: ${username}\nSenha: ${password}`;
            navigator.clipboard.writeText(textToCopy).then(() => {
                alert('Credenciais copiadas para a área de transferência!');
            }).catch(err => {
                console.error('Erro ao copiar: ', err);
            });
        }

        function sendToWhatsApp() {
            const panelAddress = document.getElementById('panelAddress').innerText;
            const username = document.getElementById('username').innerText;
            const password = document.getElementById('password').innerText;
            const message = `Olá! Suas novas credenciais de acesso são:\n\nEndereço do Painel: ${panelAddress}\nUsuário: ${username}\nSenha: ${password}\n\nPor favor, guarde-as em segurança.`
            const whatsappUrl = `https://api.whatsapp.com/send?text=${encodeURIComponent(message)}`;
            window.open(whatsappUrl, '_blank');
        }
    </script>
</body>
</html>
