<?php
require_once dirname(__DIR__) . '/api/bootstrap.php';
$action = $_GET['action'] ?? '';
try {
    if ($action === 'session') json_response(['ok'=>true,'user'=>$_SESSION['user'] ?? null,'csrf'=>csrf_token(),'config'=>['app_name'=>app_config()['app_name'] ?? 'FlowReports','store'=>app_config()['store']['name'] ?? 'Cartório']]);
    if ($action === 'login' && $_SERVER['REQUEST_METHOD']==='POST') {
        $input=json_decode(file_get_contents('php://input'), true) ?: $_POST; $email=trim($input['email'] ?? ''); $pass=(string)($input['password'] ?? '');
        $st=Database::pdo()->prepare('SELECT * FROM users WHERE email=? AND active=1 LIMIT 1'); $st->execute([$email]); $u=$st->fetch();
        if (!$u || !password_verify($pass, $u['password_hash'])) json_response(['ok'=>false,'message'=>'Usuário ou senha inválidos.'], 422);
        $_SESSION['user']=['id'=>$u['id'],'name'=>$u['name'],'email'=>$u['email'],'role'=>$u['role']]; json_response(['ok'=>true,'user'=>$_SESSION['user'],'csrf'=>csrf_token()]);
    }
    if ($action === 'logout') { session_destroy(); json_response(['ok'=>true]); }
    require_auth();
    $reports = new ReportService();
    $intel = new OrderIntelligenceService();
    if ($action === 'dashboard') json_response(['ok'=>true,'data'=>$reports->dashboard($_GET)]);
    if ($action === 'smart_cards') json_response(['ok'=>true,'data'=>$reports->smartCards($_GET)]);
    if ($action === 'report_totals') json_response(['ok'=>true,'data'=>$reports->reportTotals($_GET)]);
    if ($action === 'orders') json_response(['ok'=>true,'data'=>$reports->orders($_GET)]);
    if ($action === 'order') json_response(['ok'=>true,'data'=>$reports->orderDetail((int)($_GET['id'] ?? 0))]);
    if ($action === 'report_options') json_response(['ok'=>true,'data'=>$reports->options()]);
    if ($action === 'report_rows') json_response(['ok'=>true,'data'=>$reports->reportRows($_GET)]);
    if ($action === 'operational_rows') json_response(['ok'=>true,'data'=>$reports->operationalRows($_GET)]);
    if ($action === 'intelligence_status') json_response(['ok'=>true,'data'=>$intel->status()]);
    if ($action === 'intelligence_reprocess') { require_csrf(); $limit=(int)($_GET['limit'] ?? $_POST['limit'] ?? 250); json_response(['ok'=>true,'data'=>$intel->reprocess($limit)]); }
    if ($action === 'presets') json_response(['ok'=>true,'data'=>(new ReportPresetService())->all()]);
    if ($action === 'preset_save' && $_SERVER['REQUEST_METHOD']==='POST') { require_csrf(); $input=json_decode(file_get_contents('php://input'), true) ?: []; json_response(['ok'=>true,'data'=>(new ReportPresetService())->save($input, (int)$_SESSION['user']['id'])]); }
    if ($action === 'preset_delete' && $_SERVER['REQUEST_METHOD']==='POST') { require_csrf(); (new ReportPresetService())->delete((int)($_POST['id'] ?? 0)); json_response(['ok'=>true]); }
    if ($action === 'import' && $_SERVER['REQUEST_METHOD']==='POST') { require_csrf(); if (empty($_FILES['xml']['tmp_name'])) json_response(['ok'=>false,'message'=>'Envie um arquivo XML.'], 422); $result=(new ImportService())->importUploadedXml($_FILES['xml']['tmp_name'], $_FILES['xml']['name'] ?? 'orders.xml'); json_response(['ok'=>true,'data'=>$result]); }
    if ($action === 'imports') { $rows=Database::pdo()->query('SELECT * FROM imports ORDER BY id DESC LIMIT 50')->fetchAll(); json_response(['ok'=>true,'data'=>$rows]); }
    $export = new ExportService($reports);
    if ($action === 'export_csv') $export->csv($_GET);
    if ($action === 'export_xls') $export->xls($_GET);
    if ($action === 'export_html') $export->html($_GET);
    if ($action === 'export_docx') $export->docx($_GET);
    json_response(['ok'=>false,'message'=>'Ação não encontrada.'],404);
} catch (Throwable $e) { json_response(['ok'=>false,'message'=>$e->getMessage()],500); }
