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

$errors = array();

if (isset($_POST['submit'])) {
    // Sanitize inputs and validate required fields
    $author_name = trim($_POST['author_name'] ?? '');
    $author_lastname = trim($_POST['author_lastname'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = (string)($_POST['password'] ?? '');
    $repassword = (string)($_POST['repassword'] ?? '');
    $tos = $_POST['tos'] ?? '';
    $captcha = trim($_POST['captcha'] ?? '');

    if ($author_name == '') {
        $errors['author_name'] = '&nbsp; Please enter your first name. &nbsp;';
    }
    if ($author_lastname == '') {
        $errors['author_lastname'] = '&nbsp; Please enter your last name. &nbsp;';
    }
    if ($address == '') {
        $errors['address'] = '&nbsp; Please enter your street address. &nbsp;';
    }
    if ($phone == '') {
        $errors['phone'] = '&nbsp; Please enter your phone number. &nbsp;';
    }
    if ($email == '') {
        $errors['email'] = '&nbsp; Please enter your email address. &nbsp;';
    } elseif (!validEmail($email)) {
        $errors['email'] = '&nbsp; The email address you entered is not valid! &nbsp;';
    } elseif (editorEmailExists($email)) {
        $errors['email'] = '&nbsp; That email address is already on file. &nbsp;';
    }
    if ($password == '') {
        $errors['password'] = '&nbsp; Please enter your password. &nbsp;';
    }
    if ($password != $repassword) {
        $errors['repassword'] = '&nbsp; Please retype your password correctly. &nbsp;';
    }
    if ($tos != 1) {
        $errors['tos'] = '&nbsp; Please agree to the Reader Guidelines. &nbsp;';
    }
    if (!isset($_SESSION['security_code']) || strcasecmp(trim((string)$captcha), $_SESSION['security_code']) !== 0) {
        $errors['captcha'] = '&nbsp; Please enter the code above correctly. &nbsp;';
    }

    // If there are no errors, proceed with database insertion
    if (!count($errors)) {
        unset($_SESSION['security_code']); // one-time captcha
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);

        try {
            // New readers start as 'pending' for an administrator to approve.
            // They are NOT logged in here.
            $stmt = $pdo->prepare(
                "INSERT INTO sm_editors (password, email, first_name, last_name, address, phone, date_added, user_type)
                 VALUES (:password, :email, :first_name, :last_name, :address, :phone, :date_added, 'pending')"
            );
            $stmt->execute([
                ':password'   => $hashed_password,
                ':email'      => $email,
                ':first_name' => $author_name,
                ':last_name'  => $author_lastname,
                ':address'    => $address,
                ':phone'      => $phone,
                ':date_added' => date('Y-m-d H:i:s'),
            ]);

            $signUpOk = true;

            // Notify the applicant that we received their application.
            $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($email, $author_name . ' ' . $author_lastname);
            $mail->Subject = 'We Received Your Application';
            $html  = 'Dear ' . htmlspecialchars($author_name, ENT_QUOTES, 'UTF-8') . ',<br/><br/>';
            $html .= 'Thank you for applying to be a reader. Please wait patiently while we consider your application.<br/><br/>';
            $html .= 'Best regards,<br/><a href="' . htmlspecialchars($site_url, ENT_QUOTES, 'UTF-8') . '">' . htmlspecialchars($site_name, ENT_QUOTES, 'UTF-8') . '</a><br/>Editor';
            $mail->msgHTML($html);
            $mail->send();
        } catch (PHPMailer\PHPMailer\Exception $e) {
            error_log('reader-signup.php mail error: ' . $e->getMessage());
            // Application was still recorded; keep the success message.
            $signUpOk = true;
        } catch (PDOException $e) {
            error_log('reader-signup.php DB error: ' . $e->getMessage());
            $errors['general'] = '&nbsp; A temporary error occurred. Please try again. &nbsp;';
        }
    }
}

include_once('header.php');
?>

<center><h2>Reader's Signup</h2></center>
<center><table width="1000" align="center" cellpadding="15" border="5">
    <tr>
        <td>
            <p>Staff readers provide valuable opinions...</p>
            <hr />
            <br /><br />
            
            <?php if (isset($signUpOk)): ?>
                <p align="center">You have successfully applied to be a reader.<br />You will receive an email once we have finished reviewing your application.</p>
            <?php else: ?>
                <form method="post" action="reader-signup.php">
                    <p>First Name:<br />
                        <input value="<?php if (isset($_POST['author_name'])) echo htmlspecialchars($_POST['author_name'], ENT_QUOTES, 'UTF-8'); ?>" name="author_name" type="text">
                        <span class="error"><?php if (isset($errors['author_name'])) echo $errors['author_name']; ?></span>
                    </p>
                    <p>Last Name:<br />
                        <input value="<?php if (isset($_POST['author_lastname'])) echo htmlspecialchars($_POST['author_lastname'], ENT_QUOTES, 'UTF-8'); ?>" name="author_lastname" type="text">
                        <span class="error"><?php if (isset($errors['author_lastname'])) echo $errors['author_lastname']; ?></span>
                    </p>
                    <p>Your Mailing Address:<br />
                        <textarea name="address" rows="4" cols="50"><?php if (isset($_POST['address'])) echo htmlspecialchars($_POST['address'], ENT_QUOTES, 'UTF-8'); ?></textarea>
                        <span class="error"><?php if (isset($errors['address'])) echo $errors['address']; ?></span>
                    </p>
                    <p>Your Phone Number:<br />
                        <input name="phone" value="<?php if (isset($_POST['phone'])) echo htmlspecialchars($_POST['phone'], ENT_QUOTES, 'UTF-8'); ?>" type="text">
                        <span class="error"><?php if (isset($errors['phone'])) echo $errors['phone']; ?></span>
                    </p>
                    <p>Email:<br />
                        <input name="email" value="<?php if (isset($_POST['email'])) echo htmlspecialchars($_POST['email'], ENT_QUOTES, 'UTF-8'); ?>" type="text">
                        <span class="error"><?php if (isset($errors['email'])) echo $errors['email']; ?></span>
                    </p>
                    <p>Password:<br />
                        <input name="password" value="<?php if (isset($_POST['password'])) echo htmlspecialchars($_POST['password'], ENT_QUOTES, 'UTF-8'); ?>" type="password">
                        <span class="error"><?php if (isset($errors['password'])) echo $errors['password']; ?></span>
                    </p>
                    <p>Retype Password:<br />
                        <input name="repassword" value="<?php if (isset($_POST['repassword'])) echo htmlspecialchars($_POST['repassword'], ENT_QUOTES, 'UTF-8'); ?>" type="password">
                        <span class="error"><?php if (isset($errors['repassword'])) echo $errors['repassword']; ?></span>
                    </p>
                    <p><img src="captcha/CaptchaSecurityImages.php?width=160&height=50&characters=5&<?= time() ?>" /><br />
                        Enter The Code Above:<br />
                        <input name="captcha" type="text">
                        <span class="error"><?php if (isset($errors['captcha'])) echo $errors['captcha']; ?></span>
                    </p>
                    <p>
                        <input name="tos" type="checkbox" value="1" <?php if (isset($_POST['tos'])) echo $_POST['tos'] == 1 ? 'checked="checked"' : ''; ?> /> 
                        I agree to the 
                        <?php
                        $rg = $pdo->prepare("SELECT value FROM sm_settings WHERE var = 'readertos_url'");
                        $rg->execute();
                        $rgv = $rg->fetchColumn();
                        $val = ['value' => (is_string($rgv) && $rgv !== '') ? $rgv : '#'];
                        ?>
                        <a href="<?= htmlspecialchars($val['value'], ENT_QUOTES, 'UTF-8') ?>" target="_new"><font color="black">Reader Guidelines</font></a>.
                        <span class="error"><?php if (isset($errors['tos'])) echo $errors['tos']; ?></span>
                    </p>
                    <input type="hidden" name="user_type" value="pending" />
                    <br/><input name="submit" value="Signup" type="submit">
                </form>
            <?php endif; ?>
        </td>
    </tr>
</table></center>

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