<?php
require '../config/db.php'; 
require '../config/function/function.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['change_password'])) {
    $id = cleanInput($_POST['id']);
    $Password = cleanInput($_POST['password']);
    $compassword = cleanInput($_POST['compassword']);

    $url = $_SERVER['HTTP_REFERER']; 
    $location = "$url";
    $message = "";
    $type = "";
    $noError = "";

    if ($Password !== $compassword) {
        $message = 'Passwords do not match.';
        $type = 'error';
        redirectWithMessage($url, $message, $type);
        exit;
    }

    $hashedPassword = password_hash($Password, PASSWORD_BCRYPT);

    $query = "UPDATE admin SET password = ? WHERE id = ?";
    $stmt = $conn->prepare($query);

    if ($stmt) {
        $stmt->bind_param('si', $hashedPassword, $id);

        if ($stmt->execute()) {
            $message = 'Password changed successfully.';
            $type = 'success';
        } else {
            $message = 'Failed to change password. Please try again.';
            $type = 'error';
        }

        $stmt->close();
    } else {
        $message = 'Database error. Please contact support.';
        $type = 'error';
    }

    redirectWithMessage($url, $message, $type);
    exit;
}
?>