<?php

set_time_limit(300);

require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/auth.php';
require_once '../../core/permissions.php';
require_once '../../services/facto/FactoInboxDocumentsSyncService.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(array('success' => false, 'message' => 'Método no permitido.'), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

if (
    !user_can('billing.inbox')
    && !user_can('billing.inbox.receive')
    && !user_can('billing.admin')
    && !user_can('module.billing')
    && current_user_role() !== 'admin'
) {
    http_response_code(403);
    echo json_encode(array('success' => false, 'message' => 'No tienes permisos para sincronizar DTE recibidos.'), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

try {
    $environment = strtolower(trim((string)($_POST['environment'] ?? 'production')));
    if (!in_array($environment, array('sandbox', 'production'), true)) {
        throw new InvalidArgumentException('Ambiente FACTO inválido.');
    }

    $count = (new FactoInboxDocumentsSyncService($environment))
        ->syncInboxDocuments(100, array(), false);

    echo json_encode(array(
        'success' => true,
        'count' => $count,
        'message' => 'Recepción FACTO actualizada: ' . $count . ' DTE guardados o actualizados.'
    ), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
    http_response_code(422);
    echo json_encode(array(
        'success' => false,
        'message' => $e->getMessage()
    ), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
