<?php
session_start();
require_once('../includes/admin-security.php');
include_once('includes/config.php');

if (isset($_POST['submit'])) {
    $username = $_SESSION['alogin'];
    $current_password = $_POST['password'];
    $new_password = $_POST['newpassword'];
    $confirm_password = $_POST['confirmpassword'];

    if ($new_password !== $confirm_password) {
        $_SESSION['error'] = "New password and confirm password fields do not match!";
    } else {
        // 1. Fetch current hashed password from users table
        $stmt = $con->prepare("SELECT id, password FROM users WHERE username = ? AND role IN ('admin', 'staff', 'sales') LIMIT 1");
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows === 1) {
            $user = $result->fetch_assoc();

            // 2. Verify current password
            if (password_verify($current_password, $user['password'])) {
                // 3. Hash and update new password in users table
                $new_hash = password_hash($new_password, PASSWORD_DEFAULT);
                $update_stmt = $con->prepare("UPDATE users SET password = ? WHERE id = ?");
                $update_stmt->bind_param("si", $new_hash, $user['id']);
                
                if ($update_stmt->execute()) {
                    $_SESSION['msg'] = "Password Changed Successfully!";
                } else {
                    $_SESSION['error'] = "Error updating password. Please try again.";
                }
                $update_stmt->close();
            } else {
                $_SESSION['error'] = "Current password does not match!";
            }
        } else {
            $_SESSION['error'] = "Admin account not found!";
        }
        $stmt->close();
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <title>Change Password | Admin</title>
    <link href="css/styles.css" rel="stylesheet" />
    <link href="css/admin-professional.css" rel="stylesheet" />
    <script src="js/all.min.js" crossorigin="anonymous"></script>
</head>

<body class="sb-nav-fixed">
    <?php include_once('includes/header.php'); ?>
    <div id="layoutSidenav">
        <?php include_once('includes/sidebar.php'); ?>
        <div id="layoutSidenav_content">
            <main>
                <div class="container-fluid px-4">
                    <div class="page-header mt-4">
                        <div class="d-flex justify-content-between align-items-center">
                            <h1><i class="fas fa-key me-2"></i>Change Password</h1>
                        </div>
                    </div>

                    <?php if (isset($_SESSION['msg'])) { ?>
                        <div class="alert alert-success alert-dismissible fade show">
                            <?php echo $_SESSION['msg'];
                            unset($_SESSION['msg']); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php } ?>

                    <?php if (isset($_SESSION['error'])) { ?>
                        <div class="alert alert-danger alert-dismissible fade show">
                            <?php echo $_SESSION['error'];
                            unset($_SESSION['error']); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php } ?>

                    <div class="card mb-4 mx-auto" style="max-width: 600px;">
                        <div class="card-header">
                            <i class="fas fa-lock me-1"></i> Admin Change Password
                        </div>
                        <div class="card-body">
                            <form method="post" name="chngpwd" onSubmit="return valid();">
                                <div class="mb-3">
                                    <label class="form-label">Current Password</label>
                                    <input type="password" name="password" class="form-control"
                                        placeholder="Enter your current password" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">New Password</label>
                                    <input type="password" name="newpassword" class="form-control"
                                        placeholder="Enter your new password" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Confirm Password</label>
                                    <input type="password" name="confirmpassword" class="form-control"
                                        placeholder="Confirm your new password" required>
                                </div>
                                <button type="submit" name="submit" class="btn btn-primary">
                                    <i class="fas fa-save me-1"></i> Change Password
                                </button>
                            </form>
                        </div>
                    </div>
                </div>
            </main>
            <?php include_once('includes/footer.php'); ?>
        </div>
    </div>
    <script src="js/bootstrap.bundle.min.js"></script>
    <script src="js/scripts.js"></script>
    <script type="text/javascript">
        function valid() {
            if (document.chngpwd.password.value == "") {
                alert("Current Password Field is Empty !!");
                document.chngpwd.password.focus();
                return false;
            } else if (document.chngpwd.newpassword.value == "") {
                alert("New Password Field is Empty !!");
                document.chngpwd.newpassword.focus();
                return false;
            } else if (document.chngpwd.confirmpassword.value == "") {
                alert("Confirm Password Field is Empty !!");
                document.chngpwd.confirmpassword.focus();
                return false;
            } else if (document.chngpwd.newpassword.value != document.chngpwd.confirmpassword.value) {
                alert("Password and Confirm Password Field do not match !!");
                document.chngpwd.confirmpassword.focus();
                return false;
            }
            return true;
        }
    </script>
</body>

</html>
