<?php
session_start(); 
include 'db.php';

if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: login.php");
    exit;
}

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

    $username = $_SESSION['admin_username'];

    $old_pass = md5($_POST['old_password']);
    $new_pass = md5($_POST['new_password']);
    $confirm_pass = md5($_POST['confirm_password']);

    // Get current password
    $stmt = $con->prepare("SELECT password FROM admin_users WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result()->fetch_assoc();

    if (!$result) {
        $error = "User not found!";
    }
    elseif ($result['password'] !== $old_pass) {
        $error = "Old password incorrect!";
    }
    elseif ($new_pass !== $confirm_pass) {
        $error = "New passwords do not match!";
    }
    else {
        $update = $con->prepare("UPDATE admin_users SET password = ? WHERE username = ?");
        $update->bind_param("ss", $new_pass, $username);
        $update->execute();

        $success = "Password changed successfully!";
    }
}
?>
<?php $title = "Change Password"; include 'include/header.php'; ?>

<div id="page-wrapper">
    <div id="page-inner">
        <div class="row">
            <div class="col-md-6 m-auto">

                <h2>Change Password</h2>

                <?php 
                if (isset($error)) echo "<div class='alert alert-danger'>$error</div>";
                if (isset($success)) echo "<div class='alert alert-success'>$success</div>";
                ?>

                <form method="post">
                    <div class="mb-3">
                        <input type="password" name="old_password" class="form-control" placeholder="Old Password" required>
                    </div>

                    <div class="mb-3">
                        <input type="password" name="new_password" class="form-control" placeholder="New Password" required>
                    </div>

                    <div class="mb-3">
                        <input type="password" name="confirm_password" class="form-control" placeholder="Confirm New Password" required>
                    </div>

                    <button type="submit" class="btn btn-danger" name="change_password">
                        <i class="fas fa-key"></i> Change Password
                    </button>
                </form>

            </div>
        </div>
    </div>
</div>

<?php include 'include/footer.php'; ?>
