<?php

require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/database.php';
require_once '../../services/costs/CostAccess.php';
require_once '../../services/costs/CostManagementService.php';

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

try {
    cost_require('costs.view');
    $period = isset($_GET['period']) ? $_GET['period'] : date('Y-m');
    $service = new CostManagementService(db());
    $data = $service->getWorkspace($period, cost_can('costs.payroll.view'));
    $data['permissions'] = array(
        'edit' => cost_can('costs.edit'),
        'approve' => cost_can('costs.approve'),
        'payroll_view' => cost_can('costs.payroll.view'),
        'payroll_edit' => cost_can('costs.payroll.edit'),
        'close' => cost_can('costs.close'),
    );
    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('costs data error: ' . $e->getMessage());
        $message = 'No fue posible cargar los costos. Verifica que la migración v8.8 esté instalada.';
    } else {
        $message = $e->getMessage();
    }
    echo json_encode(array('success' => false, 'message' => $message), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
