<?php session_start();
require_once '../connections/meekro/db.class.php';

$message = '';

if (isset($_POST['passwordUpdate'])) {
    $new_password = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];

    if ($new_password !== $confirm_password) {
        $message = "New passwords do not match!";
    } else {
        // Update password in the database
        $query = DB::queryFirstRow("SELECT * FROM users WHERE svn=%s AND status=%s", $_SESSION['svn'], 'Active');
        if ($query) {
            $hashed_password = password_hash($new_password, PASSWORD_BCRYPT);
            DB::query("UPDATE users SET password=%s, pass_change=%i  WHERE svn=%s", $hashed_password, 1, $_SESSION['svn']);
            $message = "Password successfully updated! Redirecting...";
             $_SESSION['pass_change']  = 1;
                       echo  '<script>
                            setTimeout(() => {
                                window.location.href = "index.php";
                            }, 2000);
                        </script>';
        } else {
            $message = "User not found or inactive!";
        }
    }
}


?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Change Password</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/parsleyjs@2.9.3/dist/parsley.min.js"></script>
    <style>
        body {
            background: linear-gradient(135deg, #f0f6f2, #f9fcfb);
            color: white;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .card {
            background: white;
            color: black;
            box-shadow: 0px 4px 15px rgba(0, 0, 0, 0.2);
            border-radius: 10px;
        }
        .password-policy {
            font-size: 0.9rem;
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            padding: 15px;
            border-radius: 5px;
            color: #5a5c69;
        }
        .progress {
            height: 5px;
        }
        .progress-bar {
            transition: width 0.4s;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="card mx-auto" style="max-width: 500px;">
            <div class="card-body">
                <div class="text-center border-top border-3 border-success"><img src="../../assets2/img/favicon.png" height="150px " /></div>
                <h4 class="card-title text-center text-success">Change Password</h4>
                <p class="text-center">Welcome, <strong><?php echo htmlspecialchars($_SESSION['svn']); ?></strong>!</p>

                <?php if ($message): ?>
                    <div class="alert alert-info text-center"><?php echo htmlspecialchars($message); ?></div>
                <?php endif; ?>

                <form id="change-password-form" method="POST" action="">
                    <div class="mb-3">
                        <label for="new_password" class="form-label">New Password</label>
                        <input 
                            type="password" 
                            class="form-control" 
                            id="new_password" 
                            name="new_password" 
                            required
                            data-parsley-minlength="8"
                            data-parsley-uppercase="1"
                            data-parsley-lowercase="1"
                            data-parsley-number="1"
                            data-parsley-special="1"
                        >
                        <div class="progress mt-2">
                            <div class="progress-bar" role="progressbar" style="width: 0%;"></div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="confirm_password" class="form-label">Confirm New Password</label>
                        <input 
                            type="password" 
                            class="form-control" 
                            id="confirm_password" 
                            name="confirm_password" 
                            required
                            data-parsley-equalto="#new_password"
                        >
                    </div>
                    <button type="submit" name="passwordUpdate" class="btn btn-success w-100">Change Password</button>
                </form>

                <div class="password-policy mt-4">
                    <h6>Password Policy:</h6>
                    <ul>
                        <li>Must be at least 8 characters long.</li>
                        <li>Include both uppercase and lowercase letters.</li>
                        <li>Contain at least one numeric digit.</li>
                        <li>Contain at least one special character (e.g., @, #, $, %).</li>
                    </ul>
                </div>
            </div>
        </div>
    </div> 

    <script>
        // Password Strength Progress Bar
        $('#new_password').on('keyup', function () {
            const password = $(this).val();
            const progress = $('.progress-bar');
            let strength = 0;

            // Strength Rules
            if (password.length >= 8) strength += 20;
            if (/[A-Z]/.test(password)) strength += 20;
            if (/[a-z]/.test(password)) strength += 20;
            if (/[0-9]/.test(password)) strength += 20;
            if (/[^A-Za-z0-9]/.test(password)) strength += 20;

            // Update Progress Bar
            progress.css('width', strength + '%');
            if (strength < 40) {
                progress.removeClass().addClass('progress-bar bg-danger');
            } else if (strength < 80) {
                progress.removeClass().addClass('progress-bar bg-warning');
            } else {
                progress.removeClass().addClass('progress-bar bg-success');
            }
        });

        // Parsley Custom Validations
        window.Parsley.addValidator('uppercase', {
            validateString: function (value) {
                return /[A-Z]/.test(value);
            },
            messages: { en: 'Must contain at least one uppercase letter.' }
        });
        window.Parsley.addValidator('lowercase', {
            validateString: function (value) {
                return /[a-z]/.test(value);
            },
            messages: { en: 'Must contain at least one lowercase letter.' }
        });
        window.Parsley.addValidator('number', {
            validateString: function (value) {
                return /[0-9]/.test(value);
            },
            messages: { en: 'Must contain at least one number.' }
        });
        window.Parsley.addValidator('special', {
            validateString: function (value) {
                return /[^A-Za-z0-9]/.test(value);
            },
            messages: { en: 'Must contain at least one special character.' }
        });

        // Initialize Parsley
        $('#change-password-form').parsley();
    </script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
