<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors',1);

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

if(!isset($_SESSION['id'])){
    die("Session expired");
}

$user_id = (int)$_SESSION['id'];

$msg = "";
$type = "";

/* ======================
UPDATE PASSWORD
====================== */
if(isset($_POST['update'])){

    $current = $_POST['current_password'];
    $new = $_POST['new_password'];
    $confirm = $_POST['confirm_password'];

    $stmt = $conn->prepare("SELECT password FROM users WHERE id=?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $user = $stmt->get_result()->fetch_assoc();

    if(!$user || !password_verify($current, $user['password'])){
        $msg = "Current password is incorrect";
        $type = "error";
    }
    else if($new !== $confirm){
        $msg = "Passwords do not match";
        $type = "error";
    }
    else if($current === $new){
        $msg = "New password cannot be same as current password";
        $type = "error";
    }
    else if(
        strlen($new) < 7 ||
        !preg_match('/[A-Z]/', $new) ||
        !preg_match('/[a-z]/', $new) ||
        !preg_match('/[0-9]/', $new) ||
        !preg_match('/[\W]/', $new)
    ){
        $msg = "Weak password format";
        $type = "error";
    }
    else{

        $hash = password_hash($new, PASSWORD_DEFAULT);

        $stmt = $conn->prepare("UPDATE users SET password=? WHERE id=?");
        $stmt->bind_param("si", $hash, $user_id);
        $stmt->execute();

        $msg = "Password updated successfully";
        $type = "success";
    }
}
?>

<?php include("../../../templates/header.php"); ?>
<?php include("../../../templates/sidebar.php"); ?>

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

<div class="page-content">
<div class="page-inner">

    <h2 class="page-title">Change Password</h2>

    <!-- SERVER MESSAGE -->
    <?php if($msg): ?>
        <div class="alert <?= $type ?>" id="serverAlert">
            <?= $msg ?>
        </div>
    <?php endif; ?>

    <form method="post" class="form-box">

        <div class="rule-text">
            * Must include uppercase, lowercase, number, symbol, min 7 characters
        </div>

        <label>Current Password</label>
        <input type="password" name="current_password" id="current_password" required>

        <label>New Password</label>
        <input type="password" name="new_password" id="new_password" required>

        <!-- STRENGTH -->
        <div class="strength-box">
            <div id="strengthBar"></div>
            <span id="strengthText"></span>
        </div>

        <label>Confirm Password</label>
        <input type="password" name="confirm_password" id="confirm_password" required>

        <div id="matchText"></div>

        <button type="submit" name="update" class="btn-update-password">
            Update Password
        </button>

    </form>

</div>
</div>

<!-- TOAST -->
<div id="toast"></div>

<script>
document.addEventListener("DOMContentLoaded", function () {

    const newPass = document.getElementById("new_password");
    const confirmPass = document.getElementById("confirm_password");

    const bar = document.getElementById("strengthBar");
    const text = document.getElementById("strengthText");
    const match = document.getElementById("matchText");

    const toast = document.getElementById("toast");
    const serverAlert = document.getElementById("serverAlert");

    /* ================= TOAST SYSTEM ================= */
    function notify(message, type = "success", duration = 4000) {

        if (!toast) return;

        toast.className = "";
        toast.innerText = "";

        setTimeout(() => {
            toast.innerText = message;
            toast.classList.add("show", type);
        }, 10);

        setTimeout(() => {
            toast.classList.remove("show", type);
        }, duration);
    }

    window.messageNotification = notify;

    /* ================= SERVER MESSAGE ================= */
    if (serverAlert) {

        let type = "error";
        if (serverAlert.classList.contains("success")) type = "success";

        notify(serverAlert.innerText.trim(), type);

        setTimeout(() => serverAlert.remove(), 5000);
    }

    /* ================= PASSWORD STRENGTH ================= */
    function checkStrength() {

        let p = newPass.value;
        let score = 0;

        if (p.length >= 7) score++;
        if (/[A-Z]/.test(p)) score++;
        if (/[a-z]/.test(p)) score++;
        if (/[0-9]/.test(p)) score++;
        if (/[\W]/.test(p)) score++;

        if (p.length === 0) {
            bar.style.width = "0%";
            text.innerHTML = "";
            return;
        }

        if (score <= 2) {
            bar.style.width = "30%";
            bar.style.background = "#e74c3c";
            text.innerHTML = "Weak";
            text.style.color = "#e74c3c";
        }
        else if (score <= 4) {
            bar.style.width = "65%";
            bar.style.background = "#f39c12";
            text.innerHTML = "Medium";
            text.style.color = "#f39c12";
        }
        else {
            bar.style.width = "100%";
            bar.style.background = "#27ae60";
            text.innerHTML = "Strong";
            text.style.color = "#27ae60";
        }
    }

    /* ================= MATCH CHECK ================= */
    function checkMatch() {

        if (confirmPass.value.length === 0) {
            match.innerHTML = "";
            return;
        }

        if (newPass.value === confirmPass.value) {
            match.innerHTML = "Passwords match ✔";
            match.style.color = "#27ae60";
        } else {
            match.innerHTML = "Passwords do not match ✖";
            match.style.color = "#e74c3c";
        }
    }

    newPass.addEventListener("input", function () {
        checkStrength();
        checkMatch();
    });

    confirmPass.addEventListener("input", checkMatch);

});
</script>