<?php
/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

if (empty($IN_SITE)) {
    die("Access denied.");
}
$badcode = false;
if (!empty($_POST['email'])) {
    if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        header("Location: ./?page=renew&msg=bademail");
        die("That email address doesn't look right.  Please try again.");
    }
    if (!$database->has("families", ['email' => strtolower($_POST['email'])])) {
        header("Location: ./?page=renew&msg=noemail");
        die("We don't have that email on file for any current families.");
    }

    $familyid = $database->get('families', 'familyid', ['email' => strtolower($_POST['email'])]);

    // Check expiration date
    $expires = (new Family())->load($familyid)->getExpires();
    if ($expires > strtotime("+6 months")) {
        header("Location: ./?page=renew&msg=tooearly&exp=$expires");
        die("This membership isn't expiring until " . date("F j, Y", $expires) . " and cannot be renewed yet.");
    }

    $code = mt_rand(100000, 999999);
    $_SESSION['code'] = $code;
    $_SESSION['maybefamily'] = $familyid;

    try {
        $verification = new Email();
        $verification->addTo(strtolower($_POST['email']));
        $verification->setFrom($SETTINGS["smtp"]["fromaddress"], $SETTINGS["smtp"]["fromname"]);
        $verification->setSMTP($SETTINGS["smtp"]["host"], $SETTINGS["smtp"]["port"], $SETTINGS["smtp"]["auth"], $SETTINGS["smtp"]["user"], $SETTINGS["smtp"]["password"], $SETTINGS["smtp"]["secure"]);
        $verification->setSubject("HACHE email verification");
        $verification->setBody("The verification code for renewing your HACHE membership is $code.");
        $verification->send();
    } catch (Exception $e) {
        die("There was a problem sending the verification email.  Try again later.");
    }
} else if (!empty($_POST['code'])) {
    if (empty($_SESSION['code'])) {
        header("Location: ./?page=renew&msg=sessionexpired");
        die("You took too long and were automatically logged out.  Please try again.");
    }
    if (preg_replace("/[^0-9]/", "", $_POST['code']) == $_SESSION['code']) {
        $_SESSION['familyid'] = $_SESSION['maybefamily'];
        header("Location: ./?page=signup");
        die("You are verified, go to ./?page=signup");
    }
    $badcode = true;
} else {
    header("Location: ./?page=renew&msg=bademail");
    die("That email address doesn't look right.  Please try again.");
}
?>
<div class="container mt-4">
    <div class="row justify-content-center">
        <div class="card mb-4 col-lg-8">
            <div class="card-body">

                <div class="text-center">
                    <img class="img-fluid mb-4" style="max-height: 100px; min-width: 100px;" src="static/hachelogo.svg" alt="HACHE: Helena Area Christian Home Educators"/>

                    <h1>Renew Your Membership</h1>

                    <div class="card-text">
                        <p>
                            Enter the code from the email we just sent you.
                            If you didn't get it, check your spam or junk folder.
                    </div>

                    <?php
                    if ($badcode) {
                        ?>
                        <div class="alert alert-danger">
                            The code you entered is incorrect.
                        </div>
                        <?php
                    }
                    ?>

                    <form action="./?page=verify" method="POST">
                        <div class="input-group">
                            <div class="input-group-prepend">
                                <span class="input-group-text">
                                    <span class="fa-layers fa-fw mr-2">
                                        <i class="fas fa-2x fa-hashtag"></i>
                                    </span>
                                </span>
                            </div>
                            <input type="text" class="form-control" style="font-size: 40px; letter-spacing: 10px;" name="code" placeholder="000000" maxLength="6" autofocus />
                            <div class="input-group-append">
                                <button type="submit" class="btn btn-primary">Verify <i class="fas fa-chevron-right"></i></button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>