<?php
session_start();
include '../config/config.php';
include '../config/functions.php';

$error = $msg = "";

if (!isset($_GET['token'])) {
    echo "<script>window.location.href = 'login.php' </script>";
}

$token = $_GET['token'];

// Verify token
$stmt = $conn->prepare("SELECT id, reset_expires FROM users WHERE reset_token=?");
$stmt->bind_param("s", $token);
$stmt->execute();
$stmt->store_result();

if ($stmt->num_rows == 0) {
    $error = "Invalid or expired token!";
} else {
    $stmt->bind_result($userId, $expiry);
    $stmt->fetch();
    
    if (strtotime($expiry) < time()) {
        $error = "Token has expired!";
    }
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $token = $_POST['token'];
    $newPass = text_input($_POST['newpass']);
    $confirmPass = text_input($_POST['conpass']);

    if ($newPass !== $confirmPass) {
        $error = "Passwords do not match!";
    } elseif (strlen($newPass) < 6) {
        $error = "Password must be at least 6 characters!";
    } else {

        // Update password in the database
        $stmt = $conn->prepare("UPDATE users SET password=?, reset_token=NULL, reset_expires=NULL WHERE reset_token=?");
        $stmt->bind_param("ss", $newPass, $token);
        
        if ($stmt->execute()) {
            $msg = "Password reset successfully! You can now login.";
            echo "<script>Swal.fire('Success!', '$msg', 'success');</script>";
        } else {
            $error = "Something went wrong!";
        }
    }

    if (isset($error)) {
        echo "<script>Swal.fire('Error!', '$error', 'error');</script>";
    }
}
?>

<!DOCTYPE html>
<html lang="en" class="dark">
  
<head>
    <!-- Meta tags  -->
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">

    <title><?=$sitename?> - Reset Password </title>
    <link rel="icon" type="image/png" href="images/favicon.png">

    <!-- CSS Assets -->
    <link rel="stylesheet" href="css/app.css">

    <!-- Javascript AssetAs -->
    <script src="js/app.js" defer=""></script>

    <!-- Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com/">
    <link rel="preconnect" href="https://fonts.gstatic.com/" crossorigin="">
    <link href="../css2-1?family=Inter:wght@400;500;600;700&amp;family=Poppins:ital,wght@0,300;0,400;0,500;0,600;0,700;1,300;1,400;1,500;1,600;1,700&amp;display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <link rel="stylesheet" href="../ajax/libs/animate.css/4.1.1/animate.min.css" integrity="sha512-c42qTSw/wPZ3/5LBzD+Bw5f7bSF2oxou6wEb+I/lqeaKV5FDIfMvvRp772y4jcJLKuGUOpbJMdg/BTl50fJYAw==" crossorigin="anonymous" referrerpolicy="no-referrer">
   <link rel="stylesheet" href="../ajax/libs/limonte-sweetalert2/11.1.9/sweetalert2.min.css" integrity="sha512-cyIcYOviYhF0bHIhzXWJQ/7xnaBuIIOecYoPZBgJHQKFPo+TOBA+BY1EnTpmM8yKDU4ZdI3UGccNGCEUdfbBqw==" crossorigin="anonymous" referrerpolicy="no-referrer">
   <script src="../ajax/libs/limonte-sweetalert2/11.1.9/sweetalert2.all.min.js" integrity="sha512-IZ95TbsPTDl3eT5GwqTJH/14xZ2feLEGJRbII6bRKtE/HC6x3N4cHye7yyikadgAsuiddCY2+6gMntpVHL1gHw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  </head>
  <body x-data="" class="is-header-blur" x-bind="$store.global.documentBody">

  <script>
document.addEventListener("DOMContentLoaded", function () {
    <?php if (!empty($error)) { ?>
        Swal.fire({
            icon: 'error',
            title: 'Oops...',
            text: '<?php echo $error; ?>',
            confirmButtonColor: '#d33'
        });
    <?php } ?>

    <?php if (!empty($msg)) { ?>
        Swal.fire({
            icon: 'success',
            title: 'Success!',
            text: '<?php echo $msg; ?>',
            confirmButtonColor: '#28a745'
        }).then((result) => {
            if (result.isConfirmed || result.isDismissed) {
                window.location.href = 'index.php'; // Change to your dashboard or home page
            }
        });
    <?php } ?>
});
</script>

   

    <!-- App preloader-->
    <div class="app-preloader fixed z-50 grid h-full w-full place-content-center bg-slate-50 dark:bg-navy-900">
      <div class="app-preloader-inner relative inline-block h-48 w-48"></div>
    </div>

    <!-- Page Wrapper -->
    <div id="root" class="min-h-100vh flex grow bg-slate-50 dark:bg-navy-900" x-cloak="">
      <div class="fixed top-0 hidden p-6 lg:block lg:px-12">
        <a href="#" class="flex items-center space-x-2">
          <img class="h-12 w-12" src="../favicon.png" alt="logo">
          <p class="text-xl font-semibold  text-slate-700 dark:text-navy-100">
           <?=$sitename?>
          </p>
        </a>
      </div>
      <div class="hidden w-full place-items-center lg:grid">
        <div class="w-full max-w-lg p-6">
          <img class="w-full" x-show="!$store.global.isDarkModeEnabled" src="images/illustrations/dashboard-check.svg" alt="image">
          <img class="w-full" x-show="$store.global.isDarkModeEnabled" src="images/illustrations/dashboard-check-dark.svg" alt="image">
        </div>
      </div>
      <main class="flex w-full flex-col items-center bg-white dark:bg-navy-700 lg:max-w-md">
        <div class="flex w-full max-w-sm grow flex-col justify-center p-5">
          <div class="text-center">
            <img class="mx-auto h-16 w-16 lg:hidden" src="../favicon.png" alt="logo">
            <div class="mt-4">
              <h2 class="text-2xl font-semibold text-slate-600 dark:text-navy-100">
                Reset Password
              </h2>
              <p class="text-slate-400 dark:text-navy-300">
                Please Enter E-mail to continue
              </p>
            </div>
          </div>
          <div class="mt-16">
            <form method="post">
            <input type="hidden" name="token" value="<?php echo htmlspecialchars($token); ?>">
            <label class="mt-4 block">
              <span>Password:</span>
              <span class="relative mt-1.5 flex">
                <input
                  class="form-input peer w-full rounded-lg border border-slate-300 bg-transparent px-3 py-2 pl-9 placeholder:text-slate-400/70 hover:z-10 hover:border-slate-400 focus:z-10 focus:border-primary dark:border-navy-450 dark:hover:border-navy-400 dark:focus:border-accent"
                  placeholder="Enter Password"
                  type="password"
                  name="newpass"
                  required
                />
                <span
                  class="pointer-events-none absolute flex h-full w-10 items-center justify-center text-slate-400 peer-focus:text-primary dark:text-navy-300 dark:peer-focus:text-accent"
                >
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    class="h-5 w-5 transition-colors duration-200"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                  >
                    <path
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      stroke-width="1.5"
                      d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"
                    />
                  </svg>
                </span>
              </span>
            </label>

            <label class="mt-4 block">
              <span>Confirm  Password:</span>
              <span class="relative mt-1.5 flex">
                <input
                  class="form-input peer w-full rounded-lg border border-slate-300 bg-transparent px-3 py-2 pl-9 placeholder:text-slate-400/70 hover:z-10 hover:border-slate-400 focus:z-10 focus:border-primary dark:border-navy-450 dark:hover:border-navy-400 dark:focus:border-accent"
                  placeholder="Enter Confirm Password"
                  type="password"
                  name="conpass"
                  required
                />
                <span
                  class="pointer-events-none absolute flex h-full w-10 items-center justify-center text-slate-400 peer-focus:text-primary dark:text-navy-300 dark:peer-focus:text-accent"
                >
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    class="h-5 w-5 transition-colors duration-200"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                  >
                    <path
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      stroke-width="1.5"
                      d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"
                    />
                  </svg>
                </span>
              </span>
            </label>
        
            <button style="background:#F3BA2F;color:white" class="btn mt-10 h-10 w-full bg-primary font-medium text-white hover:bg-primary-focus focus:bg-primary-focus active:bg-primary-focus/90 dark:bg-accent dark:hover:bg-accent-focus dark:focus:bg-accent-focus dark:active:bg-accent/90" type="submit" name="sub-login">
              Submit
            </button>
            </form>
            <div class="mt-4 text-center text-xs+">
              <p class="line-clamp-1">
                <span>Dont have Account?</span>

                <a class="text-primary transition-colors hover:text-primary-focus dark:text-accent-light dark:hover:text-accent" href="signup.php">Create account</a>
              </p>
            </div>
            
          </div>
        </div>
        <div class="my-5 flex justify-center text-xs text-slate-400 dark:text-navy-300">
          <a href="https://<?=$sitename?>ltd.com/privacy-policy.php">Privacy Notice</a>
          <div class="mx-3 my-1 w-px bg-slate-200 dark:bg-navy-500"></div>
          <a href="https://<?=$sitename?>ltd.com/tos.php">Term of service</a>
        </div>
      </main>
    </div>


    <!-- 
        This is a place for Alpine.js Teleport feature 
        @see https://alpinejs.dev/directives/teleport
      -->
    <div id="x-teleport-target"></div>
    <script>
      window.addEventListener("DOMContentLoaded", () => Alpine.start());
    </script>
     <script>
     function urbg(){
       //  alert(5);
element=document.getElementsByTagName("html")[0];         
  element.classList.add("dark");
     }
     
     setTimeout(urbg,1000);
 </script>
 
  </body>
</html>
