<?php
require __DIR__ . '/bootstrap.php';

use App\Core\Auth;
use App\Core\Csrf;
use App\Core\Response;
use App\Services\InactivityRulesService;

$user = Auth::requireUser();
if (!Auth::hasPermission('loyalty.manage', $user)) {
    Response::error('You do not have permission to manage loyalty rules.', 403);
}

$svc = new InactivityRulesService();
$input = request_input();
$method = $_SERVER['REQUEST_METHOD'];
$action = (string)($input['action'] ?? 'overview');

try {
    if ($method === 'GET' && $action === 'overview') {
        Response::ok([
            'tables_ready' => $svc->tableReady(),
            'rules' => $svc->rules(),
            'recent_runs' => $svc->recentRuns(12),
            'stats' => $svc->stats(),
        ]);
    }

    if ($method === 'GET' && $action === 'preview') {
        $ruleId = (int)($input['id'] ?? $input['rule_id'] ?? 0);
        Response::ok($svc->preview($ruleId, (int)($input['limit'] ?? 50)));
    }

    if ($method === 'POST' && $action === 'save') {
        Csrf::validateFromRequest();
        $id = $svc->saveRule($input, (int)$user['id']);
        Response::ok(['id' => $id], 'Rule saved.');
    }

    if ($method === 'POST' && $action === 'deactivate') {
        Csrf::validateFromRequest();
        $svc->deleteRule((int)($input['id'] ?? $input['rule_id'] ?? 0));
        Response::ok([], 'Rule deactivated.');
    }

    if ($method === 'POST' && $action === 'run') {
        Csrf::validateFromRequest();
        $ruleId = (int)($input['id'] ?? $input['rule_id'] ?? 0);
        $dryRun = !empty($input['dry_run']);
        $result = $svc->runRule($ruleId, (int)$user['id'], $dryRun);
        Response::ok($result, $dryRun ? 'Preview generated.' : 'Rule applied.');
    }

    if ($method === 'POST' && $action === 'run_all') {
        Csrf::validateFromRequest();
        $result = $svc->runAllActive((int)$user['id']);
        Response::ok(['results' => $result], 'All active rules applied.');
    }
} catch (Throwable $e) {
    Response::error($e->getMessage());
}

Response::error('Unsupported inactivity rule action.', 404);
