<?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/ProductCostingService.php';

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

try {
    cost_require('costs.product.view');
    $service = new ProductCostingService(db());
    if (!empty($_GET['product_id'])) {
        $data = $service->getProduct((int)$_GET['product_id']);
    } else {
        $data = $service->getWorkspace($_GET['from'] ?? date('Y-m-01'), $_GET['to'] ?? date('Y-m-d'));
        $data['permissions'] = array(
            'edit' => cost_can('costs.product.edit'),
            'approve' => cost_can('costs.product.approve'),
            'margin_view' => cost_can('costs.margin.view'),
        );
        if (!cost_can('costs.margin.view')) {
            $data['margins'] = array('summary' => null, 'by_product' => array(), 'by_customer' => array());
        }
    }
    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('product costing data error: ' . $e->getMessage());
        $message = 'No fue posible cargar el costeo. Verifica que la migración v8.9 esté instalada.';
    } else {
        $message = $e->getMessage();
    }
    echo json_encode(array('success' => false, 'message' => $message), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
