<?php

    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\SMTP;
    use PHPMailer\PHPMailer\Exception;

    require_once("includes/migration.php");

    $finished = false;

    if (!empty($_POST['reg'])&&empty($_POST['auth'])&&empty($_POST['fusername'])) {
        if (empty($_POST['rusername']) || empty($_POST['rpassword']) || empty($_POST['rpass']) || empty($_POST['email']) || $_POST['rpassword']!=$_POST['rpass'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) || !ctype_alnum($_POST['rusername']) || strlen($_POST['rusername'])<3 || strlen($_POST['rusername'])>15 || strlen($_POST['rpassword'])<6 || strlen($_POST['rpassword'])>15 || checkUsername($_POST['rusername'])==false || (strlen($_POST['referral']) > 0 && !checkCharExists($_POST['referral']))) {
            if (empty($_POST['rusername'])) {
                echo getPanel("danger","Missing Field","Username is empty");
            }
            if (empty($_POST['rpassword'])) {
                echo getPanel("danger","Missing Field","Password is empty");
            }
            if (empty($_POST['rpass'])) {
                echo getPanel("danger","Missing Field","Repeat Password is empty");
            }
            if (empty($_POST['email'])) {
                echo getPanel("danger","Missing Field","Email is empty");
            }
            if ($_POST['rpassword']!=$_POST['rpass']) {
                echo getPanel("danger","Field Error","Passwords did not match");
            }
            if (!ctype_alnum($_POST['rusername'])) {
                echo getPanel("danger","Field Error","Username must contain letters and numbers only");
            }
            if (strlen($_POST['rusername'])<3) {
                echo getPanel("danger","Field Error","Username is less than 3 characters long");
            }
            if (strlen($_POST['rusername'])>15) {
                echo getPanel("danger","Field Error","Username is more than 15 characters long");
            }
            if (strlen($_POST['rpassword'])<6) {
                echo getPanel("danger","Field Error","Password is less than 6 characters long");
            }
            if (strlen($_POST['rpassword'])>15) {
                echo getPanel("danger","Field Error","Password is more than 15 characters long");
            }
            if (checkUsername($_POST['rusername'])==false) {
                echo getPanel("danger","Field Error","Username is already taken");
            }
            if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
                echo getPanel("danger","Field Error","Please enter a valid Email Address. (Example: user@catseyexi.com");
            }
            if (!checkCharExists($_POST['referral'])) {
                echo getPanel("danger","Field Error","Referred character name '" . $_POST['referral'] . "' doesn't exist");
            }
        }
        else {
            // Assume QoL
            $type = 0;

            // Only set account type if valid
            if (
                !empty($_POST['acc']) &&
                is_numeric($_POST['acc']) &&
                $_POST['acc'] >= 0 &&
                $_POST['acc'] <= 2
            ) {
                $type = $_POST['acc'];
            }

            $lastid=getLastACCID();
            $id=$lastid+1;
            $today = date('Y-m-d H:i:s');
            $username=$_POST['rusername'];
            $email=$_POST['email'];
            $code = random_str(8);

            if (empty($_POST['referral'])) {
                $referral = "";
            } else {
                $referral = strtolower($_POST['referral']);
            }

            require_once $mailerpath;
            $mail = new PHPMailer(true);
            $mail->isSMTP();
            $mail->Host       = 'mail.smtp2go.com';
            $mail->Port       = 587;
            $mail->SMTPSecure = 'tls';
            $mail->SMTPAuth   = true;
            $mail->Username   = 'noreply@catseyexi.com';
            $mail->Password   = '072TDs8S73a6';
            $mail->SetFrom('noreply@catseyexi.com', 'Account Verification');
            $mail->addAddress($email, $username);
            $mail->IsHTML(true);

            $mail->Subject = 'Welcome to CatseyeXI';
            $mail->Body    = '
            <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Welcome to CatsEyeXI!</title>
  <style>
    body {
      font-family: "Arial", sans-serif;
      background-color: #f4f4f4;
      color: #333;
      margin: 0;
      padding: 0;
    }

    .container {
      max-width: 600px;
      margin: 20px auto;
      padding: 20px;
      background-color: #fff;
      border-radius: 8px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    }

    h1 {
      color: #333;
    }

    p {
      line-height: 1.6;
    }

    .btn-container {
      margin-top: 20px;
    }

    .btn {
      display: inline-block;
      padding: 10px 20px;
      font-size: 16px;
      text-align: center;
      text-decoration: none;
      background-color: #3498db;
      color: #fff;
      border-radius: 5px;
      transition: background-color 0.3s ease;
    }

    .btn:hover {
      background-color: #2980b9;
    }
  </style>
</head>
<body>
  <div class="container">
    <center><img src="https://www.catseyexi.com/images/NewLogo.png" width="250"></img>
    <h1>Welcome to CatsEyeXI!</h1></center>
    <p>Dear Adventurer,</p>
    <p>Thank you for joining CatsEyeXI, where your Final Fantasy XI experience is enhanced with brilliant custom content. <strong>Please login <a href=http://www.catseyexi.com/login.php?p=account>here</a> and verify your account by using code <b>'.$code.'</b></strong></p>
    <p>Explore the realms of CatsEyeXI and discover a world of new possibilities. To get started, check out the following links:</p>

    <div class="btn-container">
      <a href="https://www.catseyexi.com/install" class="btn">Download the Launcher</a><p>
      <a href="https://discord.gg/catseyexi" class="btn">Join our Discord community!</a><p>
      <a href="https://www.bg-wiki.com/ffxi/Category:CatsEyeXI#Guides" class="btn">New Player Guide (BGWiki)!</a>
    </div>

    <p>Feel free to reach out if you have any questions or need assistance. You will find community members waiting to help you in <a href="https://discord.gg/catseyexi">#installation-help on Discord!</a></p>

    <p>Best regards,<br><br><font color="red"><strong>[GM] Carver</p></strong></font>
  </div>
</body>
</html>';
            $mail->AltBody = 'Please Login at http://www.catseyexi.com/login.php?p=account to verify your account by using code'. $code;

            if (!$mail->send()) {
                echo getPanel("danger","Registration Incomplete","There was an issue with mail process preventing account creation");
                echo 'Mailer Error: ' . $mail->ErrorInfo;
            } else {
                echo getPanel("success","Registration Complete","Please Verify your account by checking your email.");
                createAccount($id, $username, $_POST['rpassword'], $email, $today, $type, $referral, $code);

                if ($type == 2) {
                    $wusername=$_POST['wusername'];
                    $wpassword=$_POST['wpassword'];

                    if (
                        !(empty($wusername)) &&
                        !(empty($wpassword))
                    ) {
                        $wings_accid = WingsMigration::getWingsAccId($wusername, $wpassword);

                        if (
                            $wings_accid > 0 &&
                            WingsMigration::createWings($id, $wings_accid)
                        ) {
                            echo getPanel("success", "Account Linked Succesfully", "Please log in to migrate your character(s).");
                        }
                        else {
                            echo getPanel("danger", "Account Linking Failed", "Please open a ticket in discord.");
                        }
                    }
                }

                $finished = true;
            }
        }
    }

    if (empty($_GET['referral'])) {
        $referral_value = "";
    } else {
        $referral_value = strtolower($_GET['referral']);
    }
?>

<style>
#account-info {
  margin-top: 140px;
}
.account-compare td {
    padding-left: 4px;
    padding-right: 4px;
}
.rates {
    margin: 16px auto 0;
}
.rates table, .rates td {
    border: 1px solid #ccc;
}

.hidden {
    display: none;
}

#wusername.link, #wpassword.link { color: #249655 !important}
#wusername.err, #wpassword.err { color: #962455 !important}

#creating-alert {
    font-size: 0.9rem;
}

#login-form {
    padding: 32px;
}

#already-have {
    margin-bottom: 16px;
}
</style>

<?php
class Mode {
    public $name;
    public $icon;
    public $desc;
    public $more;
    public $imgs;
    public $info;
    public $rate;

    function __construct($name, $icon, $desc, $more, $imgs, $info, $rate) {
        $this->name = $name;
        $this->icon = $icon;
        $this->desc = $desc;
        $this->more = $more;
        $this->imgs = $imgs;
        $this->info = $info;
        $this->rate = $rate;
    }
}

$accTypes = [
    new Mode(
        "CatsEye Accelerated",
        "ace",
        "This is a regular CatsEyeXI account with an accelerated game experience. Characters will have access to all conveniences such as Home Point warps and increased rates. ACE characters are eligible for the \"Free Item Campaign\" and a Relic Weapon upon obtaining 100 crafting.",
        "Dualboxing permitted",
        [
            "images/cw/registration1.png",
            "images/cw/overview4.png",
            "images/cw/overview6.png"
        ],
        [
            [true,  "Auction House/Trade/Bazaar"],
            [true,  "Home Points/Survival Guides"],
            [true,  "Mounts"],
            [true,  "Trusts (Max: 5)"],
            [true,  "Records of Eminence"]
        ],
        [
            ["EXP Rate", "1.5", "Additional: Access to Echad Ring / Sprout Beret (+150%)"],
            ["Craft Rate", "1.5", "Additional: Craft Amount Multiplier (2.0)"],
            ["Craft Cap", "110 / 70"],
            ["Inventory", "80, 8 Wardrobes"],
            ["Parties", "Unrestricted"],
        ],
    ),
    new Mode(
        "Crystal Warrior",
        "cw",
        "Crystal Warrior is a challenge mode where every item is self-found. Compete on leaderboards and earn unique armor for each job. Work together with other Crystal Warriors to explore a vast amount of exclusive new content built to support this refeshing take on classic era gameplay.",
        "Optional Hardcore mode",
        [
            "images/cw/intro1.png",
            "images/cw/overview1.png",
            "images/cw/restrictions1.png"
        ],
        [
            [false, "Auction House/Trade/Bazaar"],
            [false, "Home Points/Survival Guides"],
            [false, "Mounts"],
            [true,  "Trusts (Max: 2)", "Lv15: 1 trust, Lv40+: 2 trusts, (Unlock through new quests)"],
            [false, "Records of Eminence"]
        ],
        [
            ["EXP Rate", "1.0"],
            ["Craft Rate", "1.5"],
            ["Craft Cap", "All 110"],
            ["Inventory", "Era, Wardrobes unlock"],
            ["Parties", "Crystal Warrior Only"],
        ],
    ),
    new Mode(
        "Wings-Era Warrior",
        "wew",
        "This is our regular classic era offering, with era EXP rates and no trusts. Enjoy traditional party-based leveling and experience the game as it was in the Wings era, with additional new content to explore.",
        "If you have an existing WingsXI account, you can migrate it after selecting this option.",
        [
            "images/cw/registration2.png",
            "images/cw/overview3.png",
            "images/cw/restrictions3.png"
        ],
        [
            [true,  "Auction House/Trade/Bazaar"],
            [false, "Home Points/Survival Guides"],
            [false, "Mounts"],
            [false, "Trusts"],
            [false, "Records of Eminence"]
        ],
        [
            ["EXP Rate", "1.0"],
            ["Craft Rate", "1.0"],
            ["Craft Cap", "110 / 70"],
            ["Inventory", "Era, Wardrobes unlock"],
            ["Parties", "Unrestricted"],
        ],
    ),
];
?>

<?php if (!$finished) { ?>

<section id="account-type">
    <div class="container">
        <div class="row">
            <div class="col-lg text-center">
                <img src="images/NewArtLogo.png" width=80%>
            </div>
            <div class="col-lg" id="account-info">
                <p>CatsEyeXI is offered in three variations. Once your account is created, all characters on that account will inherit the account mode selected here. For more detailed information see the <a href="https://www.bg-wiki.com/ffxi/Category:CatsEyeXI#Account_Type_Comparisons">account comparison table</a>.</p>
                <p>Players are allowed accounts of each type:</p>
                <ul>
                    <li>2 CatsEye Accelerated accounts</li>
                    <li>1 Crystal Warrior account</li>
                    <li>1 Wings-Era Warrior account</li>
                </ul>
                <div class="text-center fs-6" id="already-have">Already have an account? <a href="?p=account">Login</a></div>
            </div>
        </div>
        <div class="row account-compare">
        <?php foreach ($accTypes as $accType) { ?>
            <div class="col-lg">
                <div class="card">
                    <span class="text-center"><img src="images/icons/<?= $accType->icon ?>.png" class="card-img-top" style="width: 96px;" alt="..."></span>
                    <div class="card-body">
                        <h5 class="card-title"><strong><?= sprintf("%s - %s", strtoupper($accType->icon), $accType->name) ?></strong></h5>
                        <p class="card-text"><?= $accType->desc ?></p>
                        <p><strong><?= $accType->more ?></strong></p>

                        <table>
                            <?php foreach ($accType->info as $feature) { ?>
                            <tr>
                            <?php if ($feature[0]) { ?>
                                <td>✔️</td>
                            <?php } else { ?>
                                <td>❌</td>
                            <?php } ?>
                                <td>
                                    <?= $feature[1] ?>
                                    <?php if (isset($feature[2])) { ?>
                                            <span class="d-inline-block" tabindex="0" data-toggle="tooltip" title="<?= $feature[2]?>">
                                            <svg xmlns="http://www.w3.org/2000/svg" style="cursor: pointer" width="16" height="16" fill="currentColor" class="bi bi-info-circle" viewBox="0 0 16 16">
                                                <path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"/>
                                                <path d="m8.93 6.588-2.29.287-.082.38.45.083c.294.07.352.176.288.469l-.738 3.468c-.194.897.105 1.319.808 1.319.545 0 1.178-.252 1.465-.598l.088-.416c-.2.176-.492.246-.686.246-.275 0-.375-.193-.304-.533L8.93 6.588zM9 4.5a1 1 0 1 1-2 0 1 1 0 0 1 2 0z"/>
                                            </svg>
                                        </span>
                                    <?php } ?>
                                </td>
                            </tr>
                            <?php } ?>
                        </table>

                        <table class="rates" class="py-3">
                            <?php foreach ($accType->rate as $rate) { ?>
                            <tr>
                                <td><?= $rate[0] ?></td>
                                <td><?= $rate[1] ?>
                                    <?php if (isset($rate[2])) { ?>
                                            <span class="d-inline-block" tabindex="0" data-toggle="tooltip" title="<?= $rate[2]?>">
                                            <svg xmlns="http://www.w3.org/2000/svg" style="cursor: pointer" width="16" height="16" fill="currentColor" class="bi bi-info-circle" viewBox="0 0 16 16">
                                                <path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"/>
                                                <path d="m8.93 6.588-2.29.287-.082.38.45.083c.294.07.352.176.288.469l-.738 3.468c-.194.897.105 1.319.808 1.319.545 0 1.178-.252 1.465-.598l.088-.416c-.2.176-.492.246-.686.246-.275 0-.375-.193-.304-.533L8.93 6.588zM9 4.5a1 1 0 1 1-2 0 1 1 0 0 1 2 0z"/>
                                            </svg>
                                        </span>
                                    <?php } ?>
                                </td>
                            </tr>
                            <?php } ?>
                        </table>

                        <div class="text-center py-4">
                            <a href="#" class="btn btn-outline-info" id="create-<?= $accType->icon ?>">Create <?= strtoupper($accType->icon); ?> Account</a>
                        </div>
                        <div class="text-center">
                            <img src="<?= $accType->imgs[0] ?>" height="80" />
                            <img src="<?= $accType->imgs[1] ?>" height="96" />
                            <img src="<?= $accType->imgs[2] ?>" height="80" />
                        </div>
                     </div>
                </div>
            </div>
        <?php } ?>
        </div>
    </div> <!-- /.container -->
</section>
<section id="account-details" class="hidden">
    <div class="container">
    <div class="row">
        <div class="col-0 col-md-7 text-center">
            <img src="images/NewArtLogo.png" width=80%>
        </div>
        <div class="col-12 col-md-5 border border-success rounded-4" id="login-form">
            <h1><center>Create an Account</center></h1>
            <div class="alert alert-warning" role="alert" id="creating-alert">
                <span class="form-alert form-alert-ace">
                    <img src="images/icons/ace.png" width="32" /> You're creating a <strong>CatsEye Accelerated</strong> Account
                </span>
                <span class="form-alert form-alert-cw">
                    <img src="images/icons/cw.png" width="32" /> You're creating a <strong>Crystal Warrior</strong> Account
                </span>
                <span class="form-alert form-alert-wew">
                    <img src="images/icons/wew.png" width="32" /> You're creating a <strong>Wings-Era Warrior</strong> Account
                </span>

                <div class="text-end py-2"><a id="account-back" href="#" class="btn btn-outline-info btn-sm">Change Account Type</a></div>
            </div>
            <form method="POST" action="login.php?p=signup">
                <div class="mb-3 mt-3">
                    Username <input type="text" class="form-control" id="rusername" placeholder="Username" name="rusername">
                    Password <input type="password" class="form-control" id="rpassword" placeholder="Password" name="rpassword">
                    Repeat Password <input type="password" class="form-control" id="rpass" placeholder="Repeat Password" name="rpass">
                    Email <input type="text" class="form-control" id="email" placeholder="Email" name="email">
                    <br />

                    <section id="link-wings">
                        <div><strong>Link your <img src="images/icons/wew.png" width="24" />WingsXI Account (Optional):</strong></div>
                        Username <input type="text" class="form-control" id="wusername" placeholder="Username" name="wusername">
                        Password <input type="password" class="form-control" id="wpassword" placeholder="Password" name="wpassword">
                        <br />
                        <a href="#" class="btn btn-outline-info" id="link-verify"><span id="checking" class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Verify Account</a>
                        <a href="#" class="btn btn-outline-info" id="link-verified" disabled>✔️ Account Verified</a>
                        <div id="link-fail"><sub>❌ Unable to match account details</sub></div>
                        <div id="link-found"><sub><span id="link-num">0</span> Character(s) found</sub></div>
                        <br />
                        <br />
                    </section>
                    <span class="d-inline-block" tabindex="0" data-toggle="tooltip" title="If you were referred to CatsEyeXI by an existing player, enter their character's name here for additional rewards!">
                        <svg xmlns="http://www.w3.org/2000/svg" style="cursor: pointer" width="16" height="16" fill="currentColor" class="bi bi-info-circle" viewBox="0 0 16 16">
                            <path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"/>
                            <path d="m8.93 6.588-2.29.287-.082.38.45.083c.294.07.352.176.288.469l-.738 3.468c-.194.897.105 1.319.808 1.319.545 0 1.178-.252 1.465-.598l.088-.416c-.2.176-.492.246-.686.246-.275 0-.375-.193-.304-.533L8.93 6.588zM9 4.5a1 1 0 1 1-2 0 1 1 0 0 1 2 0z"/>
                        </svg>
                    </span>
                    Referral (Optional)
                    <input type="text" class="form-control" id="referral" placeholder="Name" name="referral" value="<?= $referral_value ?>" />
                </div> <!-- /mb-3 m-3 -->

                <input type="hidden" name="acc" id="acct" value="0" />
                <input type="hidden" name="reg" value="1" />
                <button type="submit" class="btn btn-outline-info">Register</button>
            </form>
            <br>
        </div>
    </div>
    </div>
</section>

<?php } ?>

<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script type="text/javascript" src="assets/signup/signup.js"></script>
