<?php
require_once('common.php');
if (session_status() === PHP_SESSION_NONE) {
    session_start(); // Start session for captcha handling
}

$errors = [];

// Handle form submission
if (isset($_POST['submit'])) {
    // Input validation
    if (trim($_POST['author_name'] ?? '') == '') {
        $errors['author_name'] = 'Please enter your first name.';
    }

    if (trim($_POST['author_lastname'] ?? '') == '') {
        $errors['author_lastname'] = 'Please enter your last name.';
    }

    if (trim($_POST['email'] ?? '') == '') {
        $errors['email'] = 'Please enter your email address.';
    } elseif (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        $errors['email'] = 'The email address you entered is not valid.';
    } elseif (poetEmailExists(trim($_POST['email']))) {
        $errors['email'] = 'This email is already registered. If you forgot your password, please use the <a href="forgot-password.php">Forgot Password</a> utility.';
    }

    $password = (string)($_POST['password'] ?? '');
    if ($password === '') {
        $errors['password'] = 'Please enter a password.';
    } elseif (strlen($password) < 8 || !preg_match('/[A-Z]/', $password) || !preg_match('/[a-z]/', $password) || !preg_match('/[0-9]/', $password) || !preg_match('/[^\w]/', $password)) {
        $errors['password'] = 'Password must be at least 8 characters long and contain uppercase, lowercase letters, a number, and a special character.';
    } elseif ($password !== (string)($_POST['repassword'] ?? '')) {
        $errors['repassword'] = 'The passwords do not match.';
    }

    if (!isset($_POST['tos']) || $_POST['tos'] != 1) {
        $errors['tos'] = 'You must agree to the terms.';
    }

    if (function_exists('captcha_verify') && !captcha_verify($_POST)) {
        $errors['captcha'] = 'Please complete the verification and try again.';
    }

    // If no errors, proceed with signup
    if (!count($errors)) {

        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        $confirm_token   = bin2hex(random_bytes(32));

        try {
            // id is AUTO_INCREMENT; let the database assign it.
            $stmt = $pdo->prepare(
                "INSERT INTO sm_poets
                    (password, email, author_name, author_lastname, signup_date,
                     email_confirmed, confirm_token, show_accepted_message, no_authors_page)
                 VALUES
                    (:password, :email, :author_name, :author_lastname, :signup_date,
                     0, :confirm_token, 1, 0)"
            );
            $stmt->execute([
                ':password'        => $hashed_password,
                ':email'           => trim($_POST['email']),
                ':author_name'     => trim($_POST['author_name']),
                ':author_lastname' => trim($_POST['author_lastname']),
                ':signup_date'     => date('Y-m-d H:i:s'),
                ':confirm_token'   => $confirm_token,
            ]);

            // Send the confirmation email via the configured SMTP settings.
            $smtp = [];
            foreach ($pdo->query("SELECT setting_key, setting_value FROM mail_settings") as $r) {
                $smtp[$r['setting_key']] = $r['setting_value'];
            }

            require_once('phpmailer/src/PHPMailer.php');
            require_once('phpmailer/src/SMTP.php');
            require_once('phpmailer/src/Exception.php');

            $mail = new PHPMailer\PHPMailer\PHPMailer(true);
            $mail->isSMTP();
            $mail->Host       = $smtp['mail_host'] ?? '';
            $mail->SMTPAuth   = true;
            $mail->Username   = $smtp['mail_username'] ?? '';
            $mail->Password   = $smtp['mail_password'] ?? '';
            $mail->SMTPSecure = $smtp['mail_encryption'] ?? 'ssl';
            $mail->Port       = (int)($smtp['mail_port'] ?? 465);
            $mail->CharSet    = 'UTF-8';
            $mail->setFrom($smtp['mail_from_address'] ?? $smtp['mail_username'], $smtp['mail_from_name'] ?? $site_name);
            $mail->addAddress(trim($_POST['email']), trim($_POST['author_name'] . ' ' . $_POST['author_lastname']));
            $mail->Subject = 'Please confirm your ' . $site_name . ' registration';

            $confirm_link = rtrim($site_url, '/') . '/confirm-email.php?token=' . $confirm_token;
            $html  = 'Hello ' . htmlspecialchars(trim($_POST['author_name']), ENT_QUOTES, 'UTF-8') . ',<br/><br/>';
            $html .= 'Thanks for signing up. Please confirm your email address by clicking the link below:<br/>';
            $html .= '<a href="' . htmlspecialchars($confirm_link, ENT_QUOTES, 'UTF-8') . '">' . htmlspecialchars($confirm_link, ENT_QUOTES, 'UTF-8') . '</a><br/><br/>';
            $html .= 'If you did not request this, you can ignore this email.';
            $mail->msgHTML($html);
            $mail->send();

            $signupMsg = 'We have sent a confirmation link to your email. Please click it to finish creating your account.';
        } catch (PHPMailer\PHPMailer\Exception $e) {
            error_log('signup.php mail error: ' . $e->getMessage());
            $signupMsg = 'Your account was created, but we could not send the confirmation email. Please contact us so we can confirm it manually.';
        } catch (PDOException $e) {
            error_log('signup.php DB error: ' . $e->getMessage());
            $errors['general'] = 'A temporary error occurred. Please try again.';
        }
    }
}

include_once('header.php');
include_once('menu.php');
?>

<!-- Signup form with modern design and error handling -->
<div class="signup-container">
    <h1 class="signup-title">Signup</h1>

    <?php if (!empty($errors['general'])) { ?>
        <p class="error"><?php echo htmlspecialchars($errors['general'], ENT_QUOTES, 'UTF-8'); ?></p>
    <?php } ?>

    <?php if (isset($signupMsg)) { ?>
        <p class="message"><?php echo $signupMsg; ?></p>
    <?php } else { ?>
        <form method="post" action="signup.php" class="signup-form">
            <div class="form-group">
                <label for="author_name">First Name:</label>
                <input id="author_name" name="author_name" value="<?php echo htmlspecialchars($_POST['author_name'] ?? '', ENT_QUOTES); ?>" type="text" />
                <span class="error"><?php echo $errors['author_name'] ?? ''; ?></span>
            </div>

            <div class="form-group">
                <label for="author_lastname">Last Name:</label>
                <input id="author_lastname" name="author_lastname" value="<?php echo htmlspecialchars($_POST['author_lastname'] ?? '', ENT_QUOTES); ?>" type="text" />
                <span class="error"><?php echo $errors['author_lastname'] ?? ''; ?></span>
            </div>

            <div class="form-group">
                <label for="email">Email:</label>
                <input id="email" name="email" value="<?php echo htmlspecialchars($_POST['email'] ?? '', ENT_QUOTES); ?>" type="text" />
                <span class="error"><?php echo $errors['email'] ?? ''; ?></span>
            </div>

            <div class="form-group">
                <label for="password">Password:</label>
                <input id="password" name="password" value="<?php echo htmlspecialchars($_POST['password'] ?? '', ENT_QUOTES); ?>" type="password" />
                <span class="error"><?php echo $errors['password'] ?? ''; ?></span>
            </div>

            <div class="form-group">
                <label for="repassword">Retype Password:</label>
                <input id="repassword" name="repassword" value="<?php echo htmlspecialchars($_POST['repassword'] ?? '', ENT_QUOTES); ?>" type="password" />
                <span class="error"><?php echo $errors['repassword'] ?? ''; ?></span>
            </div>

            <div class="form-group captcha-group">
                <?= function_exists('captcha_widget') ? captcha_widget() : '' ?>
                <span class="error"><?php echo $errors['captcha'] ?? ''; ?></span>
            </div>

           <p>
    <input name="tos" type="checkbox" value="1" <?php echo isset($_POST['tos']) && $_POST['tos'] == 1 ? 'checked="checked"' : ''; ?> />
    I agree to the <a href="guidelines.php" target="_new">guidelines</a>.
</p>
            <span class="error"><?php echo $errors['tos'] ?? ''; ?></span>

            <input name="submit" value="Signup" type="submit" class="button-primary">
        </form>

        <!-- Link to login page -->
        <p class="login-link">Already have an account? <a href="login.php">Go to Login...</a></p>
    <?php } ?>
</div>

<?php include_once('footer.php'); ?>

<!-- Modern Styling for Signup Form -->
<style>
.signup-container {
    max-width: 500px;
    margin: 40px auto;
    padding: 30px;
    background-color: #ffffff;
    border-radius: 10px;
    box-shadow: 0 8px 15px rgba(0, 0, 0, 0.1);
    text-align: center;
}

.signup-title {
    font-size: 28px;
    color: #1A73E8;
    margin-bottom: 20px;
}

/* Form groups for better alignment */
.form-group {
    text-align: left;
    margin-bottom: 20px;
}

.form-group label {
    display: block;
    font-weight: bold;
    color: #333;
    margin-bottom: 5px;
}

.form-group input {
    width: calc(100% - 20px);
    padding: 10px;
    border-radius: 5px;
    border: 1px solid #ccc;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.form-group input:focus {
    border-color: #1A73E8;
}

/* Primary button */
.button-primary {
    width: 100%;
    padding: 12px;
    background-color: #1A73E8;
    color: white;
    border: none;
    border-radius: 5px;
    font-size: 16px;
    cursor: pointer;
}

.button-primary:hover {
    background-color: #0D47A1;
}

/* Error messages */
.error {
    color: #dc3545;
    font-size: 12px;
}

/* Flex layout for checkbox and guidelines - compact and aligned */
.tos-section {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 15px;
}

.tos-section input[type="checkbox"] {
    margin-right: 10px;
}

.tos-section label {
    font-size: 14px;
    color: #333;
}

/* Login link */
.login-link {
    margin-top: 20px;
}

.login-link a {
    color: #1A73E8;
    text-decoration: none;
}

.login-link a:hover {
    text-decoration: underline;
}
</style>
