<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/initialize.php';
require_once __DIR__ . '/../includes/aclhelper.php';
require_once __DIR__ . '/../includes/policy-automator/bootstrap.php';

header('Content-Type: application/json; charset=utf-8');
$user = current_user() ?: [];
if ((int)($user['role_id'] ?? 0) !== 1) {
    $acl = acl_for('payroll-config/policy-automator.php');
    if (empty($acl['can_view'])) {
        http_response_code(403);
        echo json_encode(['ok' => false, 'error' => 'Access denied.']);
        exit;
    }
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'POST is required.']);
    exit;
}

$payload = json_decode((string)file_get_contents('php://input'), true);
if (!is_array($payload) || !verify_csrf($payload['_csrf'] ?? null)) {
    http_response_code(422);
    echo json_encode(['ok' => false, 'error' => 'Invalid request or expired session.']);
    exit;
}

try {
    $preview = (new PolicyAutomator($con))->preview(
        (array)($payload['answers'] ?? []),
        (array)($payload['payroll_location_ids'] ?? [])
    );
    echo json_encode(['ok' => true, 'preview' => $preview], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'Policy Automator preview is unavailable.']);
}
