<?php
session_start();
header('Content-Type: application/json');
require_once '../config/database.php';

// Only admin can reset passwords
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    echo json_encode(['success' => false, 'error' => 'unauthorized']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $userId = isset($_POST['user_id']) ? (int)$_POST['user_id'] : 0;
    $newPassword = trim($_POST['new_password'] ?? '');

    if ($userId <= 0 || strlen($newPassword) < 6) {
        echo json_encode(['success' => false, 'error' => 'invalid_params']);
        exit();
    }

    // Prevent admin from resetting own password here (optional)
    if ($userId === (int)$_SESSION['user_id']) {
        echo json_encode(['success' => false, 'error' => 'self_reset_not_allowed']);
        exit();
    }

    try {
        $hash = password_hash($newPassword, PASSWORD_DEFAULT);
        $stmt = $pdo->prepare('UPDATE users SET password = ? WHERE id = ?');
        $stmt->execute([$hash, $userId]);
        echo json_encode(['success' => true]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => 'db_error']);
    }
    exit();
}

echo json_encode(['success' => false, 'error' => 'invalid_method']);