<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

define("ROOT", $_SERVER['DOCUMENT_ROOT']."/SEAT");

include(ROOT."/config/db.php");

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

require ROOT.'/vendor/PHPMailer/src/PHPMailer.php';
require ROOT.'/vendor/PHPMailer/src/SMTP.php';
require ROOT.'/vendor/PHPMailer/src/Exception.php';

$msg="";
$type="";
$mode="forgot";

/* =========================================
   RESET MODE
========================================= */

if(isset($_GET['token'])){

    $mode="reset";
    $token=$_GET['token'];
}

/* =========================================
   SEND RESET EMAIL
========================================= */

if(isset($_POST['send'])){

    $email=trim($_POST['email']);

    $stmt=$conn->prepare("
    SELECT id
    FROM users
    WHERE email=?
    LIMIT 1
    ");

    $stmt->bind_param("s",$email);
    $stmt->execute();

    $user=$stmt->get_result()->fetch_assoc();

    if(!$user){

        header("Location: ?status=error");
        exit;
    }

    /* GENERATE TOKEN */
    $token=bin2hex(random_bytes(32));

    $expire=date(
        "Y-m-d H:i:s",
        strtotime("+1 hour")
    );

    /* SAVE TOKEN */
    $update=$conn->prepare("
    UPDATE users
    SET 
        reset_token=?,
        reset_expire=?
    WHERE email=?
    ");

    $update->bind_param(
        "sss",
        $token,
        $expire,
        $email
    );

    $update->execute();

    /* RESET LINK */
    $link=
    "https://".$_SERVER['HTTP_HOST'].
    "/SEAT/modules/User/auth/forgotpass.php?token=".$token;

    $mail=new PHPMailer(true);

    try{

        /* =========================================
           SMTP CONFIGURATION
        ========================================= */

        $mail->isSMTP();

        /* CPANEL SMTP HOST */
        $mail->Host='mail.mozabiz.com';

        /* ENABLE SMTP AUTH */
        $mail->SMTPAuth=true;

        /* CPANEL EMAIL */
        $mail->Username='noreply@mozabiz.com';

        /* CPANEL EMAIL PASSWORD */
        $mail->Password='Norshafiqa@241';

        /* SSL */
        $mail->SMTPSecure='ssl';

        /* PORT */
        $mail->Port=465;

        /* UTF8 */
        $mail->CharSet='UTF-8';

        /* OPTIONAL DEBUG */
        // $mail->SMTPDebug=2;
        // $mail->Debugoutput='html';

        /* =========================================
           EMAIL CONTENT
        ========================================= */

      $mail->setFrom('noreply@mozabiz.com', 'SEAT System');

        $mail->addAddress($email);

        $mail->isHTML(true);

        $mail->Subject="SEAT Password Reset";

        $mail->Body="
        <div style='font-family:Arial;padding:20px;'>

            <h2>Reset Password</h2>

            <p>
            Click button below to reset your password:
            </p>

            <p style='margin:30px 0;'>

                <a href='$link'
                style='
                    background:#6c3bff;
                    color:#fff;
                    padding:12px 20px;
                    text-decoration:none;
                    border-radius:8px;
                    font-weight:bold;
                '>

                Reset Password

                </a>

            </p>

            <p>
            Or copy this link:
            </p>

            <p>
            <a href='$link'>$link</a>
            </p>

            <p style='color:#888;'>
            This link expires in 1 hour.
            </p>

        </div>
        ";

        $mail->AltBody=
        "Reset your password here: ".$link;

        $mail->send();

        header("Location: ?status=sent");
        exit;

    }catch(Exception $e){

        $msg="Email failed to send";
        $type="error";

        /* SHOW SMTP ERROR */
        $msg .= "<br><small>".$mail->ErrorInfo."</small>";
    }
}

/* =========================================
   RESET PASSWORD
========================================= */

if(isset($_POST['reset'])){

    $token=$_POST['token'];

    $pass=$_POST['password'];
    $confirm=$_POST['confirm'];

    /* PASSWORD MATCH */
    if($pass!=$confirm){

        $msg="Password not match";
        $type="error";
    }

    /* PASSWORD VALIDATION */
    else if(

        strlen($pass)<7 ||

        !preg_match('/[A-Z]/',$pass) ||

        !preg_match('/[a-z]/',$pass) ||

        !preg_match('/[0-9]/',$pass) ||

        !preg_match('/[\W]/',$pass)

    ){

        $msg="
        Weak password
        <br>
        Min 7 characters with:
        uppercase,
        lowercase,
        number,
        symbol
        ";

        $type="error";
    }

    else{

        $q=$conn->prepare("
        SELECT id
        FROM users
        WHERE reset_token=?
        AND reset_expire > NOW()
        LIMIT 1
        ");

        $q->bind_param("s",$token);
        $q->execute();

        $user=$q->get_result()->fetch_assoc();

        if(!$user){

            $msg="Invalid or expired token";
            $type="error";

        }else{

            $hash=password_hash(
                $pass,
                PASSWORD_DEFAULT
            );

            $up=$conn->prepare("
            UPDATE users
            SET
                password=?,
                reset_token=NULL,
                reset_expire=NULL
            WHERE id=?
            ");

            $up->bind_param(
                "si",
                $hash,
                $user['id']
            );

            $up->execute();

            $msg="Password updated successfully";
            $type="success";

            $mode="done";
        }
    }
}

/* =========================================
   STATUS MESSAGE
========================================= */

if(isset($_GET['status'])){

    if($_GET['status']=="sent"){

        $msg="Reset link sent to your email";
        $type="success";
    }

    if($_GET['status']=="error"){

        $msg="Email not found";
        $type="error";
    }
}

?>

<!DOCTYPE html>
<html>

<head>

<title>Forgot Password</title>

<link rel="stylesheet"
href="../../../assets/css/auth/forgotpass.css">

</head>

<body>

<div class="card">

<div class="logo">

<img
src="../../../assets/images/logo4.png"
alt="Logo">

<h2>
Reset Password
</h2>

</div>

<?php if($msg!=""){ ?>

<div class="alert <?= $type ?>">

<?= $msg ?>

</div>

<?php } ?>

<!-- FORGOT PASSWORD -->

<?php if($mode=="forgot"){ ?>

<p class="desc">

Enter your registered email address
and we’ll send you a password reset link.

</p>

<form method="post">

<label>Email Address :</label>

<input
type="email"
name="email"
placeholder="example@email.com"
required>

<button name="send">

Send Reset Link

</button>

</form>

<div class="bottom">

<a href="../../../login.php"
class="back-link">

← Back to Login

</a>

</div>

<?php } ?>

<!-- RESET PASSWORD -->

<?php if($mode=="reset"){ ?>

<p class="desc">

Create your new password

</p>

<form method="post">

<input
type="hidden"
name="token"
value="<?= htmlspecialchars($token) ?>">

<input
type="password"
name="password"
id="password"
placeholder="New password"
required
oninput="validatePassword()">

<small id="passMsg"></small>

<input
type="password"
name="confirm"
id="confirm"
placeholder="Confirm password"
required
oninput="validateConfirm()">

<small id="confirmMsg"></small>

<button name="reset">

Reset Password

</button>

</form>

<div class="bottom">

<a href="../../../login.php">

Back to Login

</a>

</div>

<?php } ?>

<!-- DONE -->

<?php if($mode=="done"){ ?>



<div class="bottom">

<a
href="../../../login.php"
class="login-btn">

Login Now

</a>

</div>

<?php } ?>

</div>

<script>
const BASE="/SEAT";
</script>

<script src="modules/User/auth/register.js?v=2"></script>

</body>
</html>