<?php

require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/database.php';
require_once '../../services/treasury/TreasuryAccess.php';
require_once '../../services/treasury/TreasuryService.php';

require_login();
header('Content-Type: application/json; charset=utf-8');

try {
    treasury_require('treasury.view');
    $start = isset($_GET['start']) ? (string)$_GET['start'] : date('Y-m-d');
    $scenario = isset($_GET['scenario']) ? (string)$_GET['scenario'] : 'base';
    $accountId = !empty($_GET['account_id']) ? (int)$_GET['account_id'] : null;
    $service = new TreasuryService(db());
    $data = $service->getWorkspace($start, $scenario, $accountId);
    $data['permissions'] = array(
        'edit' => treasury_can('treasury.edit'),
        'reconcile' => treasury_can('treasury.reconcile'),
        'scenarios' => treasury_can('treasury.scenarios'),
    );
    echo json_encode(array('success'=>true,'data'=>$data),JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
    $status=http_response_code()===403?403:($e instanceof RuntimeException?409:400);http_response_code($status);
    if($e instanceof PDOException){error_log('treasury data error: '.$e->getMessage());$message='No fue posible cargar Tesorería. Verifica que la migración v9.0 esté instalada.';}else{$message=$e->getMessage();}
    echo json_encode(array('success'=>false,'message'=>$message),JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
}
