<?php
declare(strict_types=1);

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

$pageLink = 'payroll-config/policy-automator.php';
$user = current_user() ?: [];
$acl = (int)($user['role_id'] ?? 0) === 1
    ? ['can_view' => true, 'can_add' => true, 'can_edit' => true, 'can_delete' => true]
    : require_acl('can_view', $pageLink);
$errors = [];
$preview = null;
$answersText = trim((string)($_POST['answers_json'] ?? '{"late_track_enabled":true,"late_policy_action":"deduct","late_rule_unit":"rupees"}'));
$selectedLocations = array_values(array_unique(array_filter(array_map('intval', (array)($_POST['payroll_locations'] ?? [])))));

$locations = [];
$locationResult = $con->query("SELECT id,name FROM jos_app_payrolllocation WHERE status=1 ORDER BY name,id");
if ($locationResult) while ($row = $locationResult->fetch_assoc()) $locations[] = $row;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf($_POST['_csrf'] ?? null)) {
        $errors[] = 'Your session expired. Refresh the page and try again.';
    } else {
        $answers = json_decode($answersText, true);
        if (!is_array($answers)) {
            $errors[] = 'The policy answers are not valid JSON.';
        } else {
            try {
                $preview = (new PolicyAutomator($con))->preview($answers, $selectedLocations);
                $errors = array_merge($errors, (array)$preview['errors']);
                audit_log('policy_automator_preview', 'policy_automation', null, json_encode([
                    'locations' => $selectedLocations,
                    'summary' => $preview['summary'],
                ], JSON_UNESCAPED_SLASHES));
            } catch (Throwable $e) {
                $errors[] = 'Policy Automator is not initialized yet. Apply the foundation migration first.';
            }
        }
    }
}

$stats = ['catalog' => 0, 'verified' => 0, 'decisions' => 0, 'drafts' => 0];
foreach ([
    'catalog' => "SELECT COUNT(*) n FROM jos_app_component_kb_catalog WHERE active=1",
    'verified' => "SELECT COUNT(*) n FROM jos_app_component_kb_catalog WHERE active=1 AND review_status='verified'",
    'decisions' => "SELECT COUNT(*) n FROM jos_app_policy_kb_decision WHERE active=1",
    'drafts' => "SELECT COUNT(*) n FROM jos_app_policy_generated_setup WHERE status='draft'",
] as $key => $sql) {
    try {
        $result = $con->query($sql);
        if ($result) $stats[$key] = (int)($result->fetch_assoc()['n'] ?? 0);
    } catch (Throwable $e) {
        // The page remains readable before its migration is installed.
    }
}

console_header('Policy Automator', $pageLink);
?>
<div class="mb-6">
    <div class="text-xs font-extrabold uppercase tracking-[.18em] text-brand-600">Payroll Config</div>
    <h1 class="mt-1 text-2xl font-bold text-slate-900">Policy Automator</h1>
    <p class="mt-2 max-w-3xl text-sm text-slate-500">Convert simple attendance-policy answers into validated attendance outputs, salary components and payroll configuration plans.</p>
</div>

<div class="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
    <?php foreach ([['Component catalog',$stats['catalog'],'fa-layer-group'],['Verified components',$stats['verified'],'fa-circle-check'],['Decision rules',$stats['decisions'],'fa-code-branch'],['Draft setups',$stats['drafts'],'fa-file-pen']] as $card): ?>
    <div class="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm"><div class="flex items-center justify-between"><div class="text-sm font-semibold text-slate-500"><?= h($card[0]) ?></div><i class="fa-solid <?= h($card[2]) ?> text-brand-500"></i></div><div class="mt-3 text-3xl font-extrabold text-slate-900"><?= h((string)$card[1]) ?></div></div>
    <?php endforeach; ?>
</div>

<?php if ($errors): ?><div class="mt-6 rounded-xl border border-red-200 bg-red-50 p-4 text-sm font-semibold text-red-700"><ul class="list-inside list-disc"><?php foreach (array_unique($errors) as $error): ?><li><?= h($error) ?></li><?php endforeach; ?></ul></div><?php endif; ?>

<div class="mt-6 grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]">
    <form method="post" class="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
        <input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>">
        <div class="flex items-start justify-between gap-4"><div><h2 class="text-lg font-bold text-slate-900">Configuration preview</h2><p class="mt-1 text-sm text-slate-500">Dry run only. This does not create or assign components.</p></div><span class="rounded-full bg-amber-50 px-3 py-1 text-xs font-bold text-amber-700">SAFE MODE</span></div>
        <div class="mt-6"><div class="text-sm font-bold text-slate-800">Payroll locations</div><div class="mt-3 grid gap-2 md:grid-cols-2"><?php foreach ($locations as $location): ?><label class="flex items-center gap-3 rounded-xl border border-slate-200 p-3 text-sm font-semibold text-slate-700"><input type="checkbox" name="payroll_locations[]" value="<?= h((string)$location['id']) ?>" <?= in_array((int)$location['id'],$selectedLocations,true)?'checked':'' ?> class="rounded border-slate-300 text-brand-600"><span><?= h((string)$location['name']) ?></span></label><?php endforeach; ?></div></div>
        <label class="mt-6 block text-sm font-bold text-slate-800">Normalized policy answers<textarea name="answers_json" rows="9" spellcheck="false" class="mt-2 w-full rounded-xl border border-slate-200 bg-slate-950 p-4 font-mono text-xs leading-6 text-emerald-300 outline-none focus:border-brand-500"><?= h($answersText) ?></textarea><span class="mt-2 block text-xs font-normal text-slate-500">The Shift wizard will send this automatically after integration.</span></label>
        <button class="mt-5 inline-flex items-center gap-2 rounded-xl bg-brand-600 px-5 py-3 text-sm font-bold text-white hover:bg-brand-700"><i class="fa-solid fa-wand-magic-sparkles"></i>Generate dry run</button>
    </form>

    <aside class="h-fit rounded-2xl border border-slate-200 bg-white p-6 shadow-sm xl:sticky xl:top-5"><h2 class="font-bold text-slate-900">Safety sequence</h2><ol class="mt-4 space-y-4 text-sm text-slate-600"><?php foreach ([['1','Understand answers'],['2','Match approved decisions'],['3','Resolve component dependencies'],['4','Show create/reuse/conflict plan'],['5','Confirm before activation']] as $item): ?><li class="flex gap-3"><span class="flex h-7 w-7 flex-none items-center justify-center rounded-full bg-brand-50 text-xs font-extrabold text-brand-700"><?= h($item[0]) ?></span><span class="pt-1 font-semibold"><?= h($item[1]) ?></span></li><?php endforeach; ?></ol></aside>
</div>

<?php if ($preview): ?>
<section class="mt-6 rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
    <div class="flex flex-wrap items-center justify-between gap-3"><div><h2 class="text-lg font-bold text-slate-900">Generated plan</h2><p class="mt-1 text-sm text-slate-500"><?= h((string)$preview['summary']['decisions']) ?> decisions matched across <?= h((string)count($preview['payroll_location_ids'])) ?> payroll location(s).</p></div><div class="flex gap-2"><span class="rounded-lg bg-blue-50 px-3 py-2 text-xs font-bold text-blue-700"><?= h((string)$preview['summary']['create']) ?> create</span><span class="rounded-lg bg-emerald-50 px-3 py-2 text-xs font-bold text-emerald-700"><?= h((string)$preview['summary']['reuse']) ?> reuse</span><span class="rounded-lg bg-red-50 px-3 py-2 text-xs font-bold text-red-700"><?= h((string)$preview['summary']['blocked']) ?> blocked</span></div></div>
    <div class="mt-5 overflow-x-auto"><table class="min-w-full text-left text-sm"><thead class="bg-slate-50 text-xs uppercase text-slate-500"><tr><th class="px-4 py-3">Location</th><th class="px-4 py-3">Component</th><th class="px-4 py-3">Operation</th><th class="px-4 py-3">Action</th><th class="px-4 py-3">Reason</th></tr></thead><tbody class="divide-y divide-slate-100"><?php foreach ($preview['actions'] as $row): ?><tr><td class="px-4 py-3 font-semibold"><?= h((string)$row['payroll_location_id']) ?></td><td class="px-4 py-3"><div class="font-bold text-slate-800"><?= h((string)$row['component_name']) ?></div><div class="text-xs text-slate-500"><?= h((string)$row['semantic_key']) ?> · <?= h((string)$row['unit']) ?></div></td><td class="px-4 py-3"><?= h((string)$row['operation']) ?></td><td class="px-4 py-3"><span class="rounded-full px-2.5 py-1 text-xs font-bold <?= $row['action']==='reuse'?'bg-emerald-50 text-emerald-700':($row['action']==='create'?'bg-blue-50 text-blue-700':'bg-red-50 text-red-700') ?>"><?= h(strtoupper((string)$row['action'])) ?></span></td><td class="px-4 py-3 text-slate-600"><?= h((string)$row['reason']) ?></td></tr><?php endforeach; ?></tbody></table></div>
</section>
<?php endif; ?>
<?php console_footer(); ?>
