<?php

require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/database.php';
require_once '../../core/permissions.php';
require_once '../../services/finance/FinanceCenterAssignmentService.php';

require_login();
header('Content-Type: application/json; charset=utf-8');
if (current_user_role() !== 'admin') {
    http_response_code(403);
    echo json_encode(array('success' => false, 'message' => 'No autorizado.'));
    exit;
}

try {
    $service = new FinanceCenterAssignmentService(db());
    $method = strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? 'GET'));
    if ($method === 'GET') {
        echo json_encode(array('success' => true, 'data' => $service->workspace()), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }
    if ($method !== 'POST') throw new RuntimeException('Método no permitido.');
    csrf_require_valid_request();
    $action = trim((string)($_POST['action'] ?? 'save_settings'));
    $result = null;
    if ($action === 'save_settings') {
        $result = $service->saveSettings($_POST, current_user_id());
    } elseif ($action === 'assign_supplier') {
        $service->assignSupplier($_POST['supplier_id'] ?? 0, $_POST['finance_center_id'] ?? 0);
    } elseif ($action === 'assign_category') {
        $service->assignCategory($_POST['category_id'] ?? 0, $_POST['finance_center_id'] ?? 0);
    } elseif ($action === 'apply_pending') {
        $result = $service->applyPending($_POST['period'] ?? '', current_user_id());
    } else {
        throw new InvalidArgumentException('Acción no reconocida.');
    }
    echo json_encode(array('success' => true, 'data' => $result), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
    http_response_code($e instanceof RuntimeException ? 409 : 400);
    echo json_encode(array('success' => false, 'message' => $e->getMessage()), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
