<?php
include "../../include/auth.php"; // Authentication
include "../../include/lskfjwfe.php"; // Database connection

header('Content-Type: application/json');

// Validate request method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

// Validate required fields
if (!isset($_POST['user_id'], $_POST['user_new_pass'])) {
    echo json_encode(['success' => false, 'message' => 'Missing required fields']);
    exit();
}

// Sanitize input
$user_id = intval($_POST['user_id']);
$new_password = password_hash($_POST['user_new_pass'], PASSWORD_BCRYPT); // Hash the password

// Ensure user exists and fetch username
$sql_check = "SELECT username FROM users WHERE id = ?";
$stmt_check = $db->prepare($sql_check);
$stmt_check->bind_param("i", $user_id);
$stmt_check->execute();
$result_check = $stmt_check->get_result();
if ($result_check->num_rows === 0) {
    echo json_encode(['success' => false, 'message' => 'User not found']);
    exit();
}
$user_data = $result_check->fetch_assoc();
$username = $user_data['username'];
$stmt_check->close();

// Update password
$sql_update = "UPDATE users SET password = ? WHERE id = ?";
$stmt_update = $db->prepare($sql_update);
$stmt_update->bind_param("si", $new_password, $user_id);
$update_success = $stmt_update->execute();

if ($update_success) {
    // Log the password change
    $admin_username = $_SESSION['username'];
    $log_action = "Changed Password";
    $log_message = "Password changed for user: $username by $admin_username";

    $log_sql = "INSERT INTO settings_log (username, action, setting_name, old_value, new_value, timestamp)
                VALUES (?, ?, 'Password Change', NULL, ?, NOW())";
    $stmt_log = $db2->prepare($log_sql);
    $stmt_log->bind_param("sss", $admin_username, $log_action, $log_message);
    $stmt_log->execute();
    $stmt_log->close();

    echo json_encode(['success' => true, 'message' => 'Password changed successfully']);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to change password']);
}
?>
