<?php
session_start();

$server = 'localhost';
$username = 'u669521264_abduscalandia';
$password = 'Bruhbruh123!';
$database = 'u669521264_abduscan';

$conn = new mysqli($server, $username, $password, $database);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$error_message = '';
$success_message = '';
$hcaptcha_secret = 'ES_91395394d002433e97cc511fde9889aa';

if (isset($_POST['register'])) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $password = password_hash($_POST['password'], PASSWORD_ARGON2ID);
    $hcaptcha_response = $_POST['h-captcha-response'];

    // Verificar hCaptcha
    $verify_url = 'https://hcaptcha.com/siteverify';
    $data = array(
        'secret' => $hcaptcha_secret,
        'response' => $hcaptcha_response
    );

    $options = array(
        'http' => array(
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',
            'content' => http_build_query($data),
        ),
    );

    $context  = stream_context_create($options);
    $result = file_get_contents($verify_url, false, $context);
    $verification = json_decode($result);

    if ($verification && $verification->success) {
        $stmt_check = $conn->prepare("SELECT COUNT(*) AS count FROM `tbl_user` WHERE `email` = ?");
        $stmt_check->bind_param("s", $email);
        $stmt_check->execute();
        $result_check = $stmt_check->get_result();
        $row = $result_check->fetch_assoc();

        if ($row['count'] > 0) {
            $error_message = 'The email is already in use.';
        } else {
            $stmt_insert = $conn->prepare("INSERT INTO `tbl_user`(`name`, `email`, `password`) VALUES (?, ?, ?)");
            $stmt_insert->bind_param("sss", $name, $email, $password);

            if ($stmt_insert->execute()) {
                $success_message = 'User registered successfully.';
            } else {
                $error_message = 'Error: ' . $stmt_insert->error;
            }
            $stmt_insert->close();
        }
        $stmt_check->close();
    } else {
        $error_message = 'Captcha verification failed.';
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['google_email'])) {
    $google_email = $_POST['google_email'];
    $google_name = $_POST['google_name'];

    $stmt_check = $conn->prepare("SELECT COUNT(*) AS count FROM `tbl_user` WHERE `email` = ?");
    $stmt_check->bind_param("s", $google_email);
    $stmt_check->execute();
    $result_check = $stmt_check->get_result();
    $row = $result_check->fetch_assoc();

    if ($row['count'] == 0) {
        $stmt_insert = $conn->prepare("INSERT INTO `tbl_user`(`name`, `email`) VALUES (?, ?)");
        $stmt_insert->bind_param("ss", $google_name, $google_email);
        $stmt_insert->execute();
        $stmt_insert->close();
    }

    $_SESSION['user'] = $google_name;
    $_SESSION['email'] = $google_email;

    echo json_encode(['success' => true]);
    exit();
}

$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Register</title>
    <link rel="stylesheet" href="style.css">
    <link rel="icon" href="badabun.ico" type="image/x-icon">
    <script src="https://hcaptcha.com/1/api.js" async defer></script>
    <script src="https://accounts.google.com/gsi/client" async defer></script>
</head>
<body>
    <div class="container">
        <div class="container-form">
            <img src="badabun.ico" alt="Logo" class="logo">
            <form method="post" action="index.php" class="sign-up">
                <h2>Register</h2>
                <div class="social-networks">
                    <!-- Botón de Google Sign-In -->
                    <div id="g_id_onload"
                         data-client_id="732072721097-hbo7a35pqubtdubn4qvs9qiaj5rteh9n.apps.googleusercontent.com"
                         data-callback="handleCredentialResponse">
                    </div>
                    <div class="g_id_signin" data-type="standard"></div>
                </div>
                                <?php if ($error_message && isset($_POST['register'])): ?>
                    <div class="error"><?php echo $error_message; ?></div>
                <?php endif; ?>
                                <?php if ($success_message && isset($_POST['register'])): ?>
                    <div class="success"><?php echo $success_message; ?></div>
                <?php endif; ?>
                <div class="abduscan">
                <span>Or use your email for registration</span>
                </div>
                <div class="input-container">
                    <input type="text" name="name" placeholder="Name" required>
                </div>
                <div class="input-container">
                    <input type="email" name="email" placeholder="Email" required>
                </div>
                <div class="input-container">
                    <input type="password" name="password" placeholder="Password" required>
                </div>
                <div class="h-captcha" data-sitekey="858eca8c-e502-474a-891c-d916ac18f3f2"></div>
                <a href="forgot_password.php">Forgot your password?</a>
                <button type="submit" name="register" class="button">Register</button>
                <a href="../log-in">Sign in</a>
            </form>
        </div>
    </div>

    <script>
        function handleCredentialResponse(response) {
            const data = jwt_decode(response.credential);
            const email = data.email;
            const name = data.name;

            fetch('endpoint.php', { // Endpoint para manejar Google sign-in
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ google_email: email, google_name: name })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    window.location.href = '../home'; // Redirigir tras el login exitoso
                } else {
                    alert('Error during Google sign-in');
                }
            })
            .catch(error => console.error('Error:', error));
        }
    </script>
    <script src="https://cdn.jsdelivr.net/npm/jwt-decode/build/jwt-decode.min.js"></script>
</body>
</html>
