<?php
require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/database.php';
require_once '../../core/auth.php';
require_once '../../core/permissions.php';
require_once '../../services/billing/BillingPayablesService.php';
require_once '../../services/facto/FactoClient.php';
require_once '../../services/facto/FactoInboxDocumentsSyncService.php';

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

if (!user_can('billing.inbox.approve') && !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 aceptar o rechazar DTE.'));
    exit;
}

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

try {
    $environment = $_POST['environment'] ?? 'sandbox';
    $id = $_POST['id'] ?? '';
    $action = $_POST['action'] ?? '';
    $statusMap = array(
        'approve' => '2',
        'approve_objection' => '3',
        'reject' => '4',
        'receive_merchandise' => '5'
    );
    if (!isset($statusMap[$action])) {
        throw new Exception('Accion DTE no valida.');
    }

    $payables = new BillingPayablesService(db());
    $doc = $payables->getDocument($id, $environment);

    $client = new FactoClient($environment);
    $response = $client->patchInboxDocument($doc['inbox_document_id'], array(
        'inbox_document_status' => $statusMap[$action]
    ));

    $sync = new FactoInboxDocumentsSyncService($environment);
    $sync->refreshInboxDocument($doc['inbox_document_id'], false);

    if ($action === 'reject') {
        $payables->updateDocument($doc['id'], array(
            'environment' => $environment,
            'payment_status' => 'rechazado',
            'finance_center_id' => $doc['finance_center_id'],
            'payment_due_date' => $doc['payment_due_date'],
            'notes' => $_POST['notes'] ?? 'Documento rechazado desde ICYLAB OS.'
        ), current_user_id());
    }

    echo json_encode(array('success' => true, 'response' => $response, 'document' => $payables->getDocument($doc['id'], $environment)), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
    http_response_code(400);
    echo json_encode(array('success' => false, 'message' => $e->getMessage()), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
