<?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');
if(strtoupper((string)($_SERVER['REQUEST_METHOD']??'GET'))!=='POST'){http_response_code(405);echo json_encode(array('success'=>false,'message'=>'Método no permitido.'));exit;}

try {
    csrf_require_valid_request();
    $action=trim((string)($_POST['action']??''));$service=new TreasuryService(db());$userId=current_user_id();$result=null;
    if($action==='save_opening'){
        treasury_require('treasury.edit');$result=$service->saveOpeningBalance($_POST,$userId);
    }elseif($action==='save_movement'){
        treasury_require('treasury.edit');$result=$service->saveManualMovement($_POST,$userId);
    }elseif($action==='void_movement'){
        treasury_require('treasury.edit');$service->voidManualMovement((int)($_POST['id']??0),$userId);
    }elseif($action==='save_transfer'){
        treasury_require('treasury.edit');$result=$service->saveTransfer($_POST,$userId);
    }elseif($action==='save_scenario_item'){
        treasury_require('treasury.scenarios');$result=$service->saveScenarioItem($_POST,$userId);
    }elseif($action==='save_forecast_coverage'){
        treasury_require('treasury.edit');$result=$service->saveForecastCoverage($_POST,$userId);
    }elseif($action==='cancel_scenario_item'){
        treasury_require('treasury.scenarios');$service->cancelScenarioItem((int)($_POST['id']??0),$userId);
    }elseif($action==='import_statement'){
        treasury_require('treasury.reconcile');$result=$service->importStatement((int)($_POST['cash_account_id']??0),$_FILES['statement_file']??array(),$userId);
    }elseif($action==='auto_reconcile'){
        treasury_require('treasury.reconcile');$result=$service->autoReconcile((int)($_POST['cash_account_id']??0),$userId);
    }elseif($action==='convert_statement_row'){
        treasury_require('treasury.reconcile');$result=$service->convertStatementRow((int)($_POST['id']??0),$userId);
    }elseif($action==='ignore_statement_row'){
        treasury_require('treasury.reconcile');$service->ignoreStatementRow((int)($_POST['id']??0),$userId,$_POST['notes']??'');
    }else{
        throw new InvalidArgumentException('Acción de tesorería no reconocida.');
    }
    echo json_encode(array('success'=>true,'data'=>$result),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 action error: '.$e->getMessage());$message='No fue posible guardar la información de Tesorería. Revisa duplicados o la instalación v9.0.';}else{$message=$e->getMessage();}
    echo json_encode(array('success'=>false,'message'=>$message),JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
}
