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

// Only admin can reset passwords
if (!isset($_SESSION['role_id']) || $_SESSION['role_id'] != 1) {
    echo json_encode(["success" => false, "message" => "Unauthorized."]);
    exit;
}

// Get JSON data from POST request
$data = json_decode(file_get_contents("php://input"), true);
$id = isset($data['id']) ? intval($data['id']) : 0;

if ($id <= 0) {
    echo json_encode(["success" => false, "message" => "Invalid user ID."]);
    exit;
}

// Prevent admin from resetting their own password
if ($_SESSION['user_id'] === $id) {
    echo json_encode(["success" => false, "message" => "You cannot reset your own password here."]);
    exit;
}

// Check if user exists
$stmt = $conn->prepare("SELECT id FROM users WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    echo json_encode(["success" => false, "message" => "User not found."]);
    exit;
}

// Define default password (fallback to 'Reset123!')
$defaultPlainPassword = defined('DEFAULT_PASSWORD') ? DEFAULT_PASSWORD : 'Reset123!';
$defaultHashedPassword = password_hash($defaultPlainPassword, PASSWORD_DEFAULT);

// Update user password and force change on next login
$reset = $conn->prepare("
    UPDATE users 
    SET password = ?, password_reset = 1, password_changed = 0 
    WHERE id = ?
");
$reset->bind_param("si", $defaultHashedPassword, $id);

if ($reset->execute()) {
    echo json_encode([
        "success" => true,
        "message" => "Password reset to default: $defaultPlainPassword"
    ]);
} else {
    echo json_encode(["success" => false, "message" => "Failed to reset password."]);
}
?>
