<?php
/**
 * Admin Password Reset Handler
 * Direct API for updating user passwords
 */

header('Content-Type: text/plain; charset=utf-8');

// Prevent any output except our responses
ob_start();

try {
    // Check if this is a password update request
    if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['ajax_password'])) {
        ob_end_clean();
        echo "INVALID_REQUEST";
        exit;
    }

    // Load required files
    require_once(__DIR__ . '/../config/config.php');
    require_once(__DIR__ . '/../classes/Database.php');

    // Get database instance
    $db = Database::getInstance();
    
    // Get POST data
    $user_id = intval($_POST['user_id'] ?? 0);
    $new_password = $_POST['new_password'] ?? '';

    // Validation
    if (!$user_id) {
        ob_end_clean();
        echo "INVALID_USER";
        exit;
    }

    if (empty($new_password) || strlen($new_password) < 6) {
        ob_end_clean();
        echo "INVALID_PASSWORD";
        exit;
    }

    // Check if user exists
    $user_check = $db->fetch("SELECT id FROM users WHERE id = ?", [$user_id]);
    if (!$user_check) {
        ob_end_clean();
        echo "USER_NOT_FOUND";
        exit;
    }

    // Hash the password
    $hashed_password = password_hash($new_password, PASSWORD_BCRYPT, ['cost' => 12]);

    // Update password in database
    $result = $db->query(
        "UPDATE users SET password = ? WHERE id = ?",
        [$hashed_password, $user_id]
    );

    ob_end_clean();
    
    if ($result) {
        echo "OK";
    } else {
        echo "UPDATE_FAILED";
    }

} catch (Exception $e) {
    ob_end_clean();
    error_log("Password reset error: " . $e->getMessage());
    echo "ERROR";
}

exit;
?>
