<?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');

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 ProductCostingService(db());
    $userId = current_user_id();
    if ($action === 'save_draft') {
        cost_require('costs.product.edit');
        $result = $service->saveDraft($_POST, $userId);
    } elseif ($action === 'approve_version') {
        cost_require('costs.product.approve');
        $result = $service->approveVersion((int)($_POST['version_id'] ?? 0), $userId);
    } elseif ($action === 'rebuild_snapshots') {
        cost_require('costs.product.approve');
        $result = $service->rebuildSnapshots($_POST['from'] ?? date('Y-m-01'), $_POST['to'] ?? date('Y-m-d'), $userId);
    } else {
        throw new InvalidArgumentException('Acción de costeo 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('product costing action error: ' . $e->getMessage());
        $message = 'No fue posible guardar el costeo. Revisa la migración v8.9 y los datos ingresados.';
    } else {
        $message = $e->getMessage();
    }
    echo json_encode(array('success' => false, 'message' => $message), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
