<?php
require_once __DIR__ . '/../../core/config.php';
require_once __DIR__ . '/../../core/session.php';
require_once __DIR__ . '/../../core/database.php';
require_once __DIR__ . '/../../core/auth.php';
require_once __DIR__ . '/../../core/permissions.php';
require_once __DIR__ . '/../../services/billing/BillingIssuedDocumentsService.php';
require_once __DIR__ . '/../../services/billing/BillingPayablesService.php';

require_login();
header('Content-Type: application/json; charset=utf-8');
if (!user_can('billing.documents') && !user_can('billing.view') && !user_can('module.billing') && current_user_role() !== 'admin') {
    http_response_code(403);
    echo json_encode(array('success'=>false,'message'=>'No tienes permisos para ver este documento.'));
    exit;
}
try {
    $environment = $_GET['env'] ?? (defined('FACTO_DEFAULT_ENVIRONMENT') ? FACTO_DEFAULT_ENVIRONMENT : 'production');
    $origin = strtolower(trim((string)($_GET['origin'] ?? 'issued')));
    if ($origin === 'received') {
        $doc = (new BillingPayablesService(db()))->getDocument($_GET['id'] ?? 0, $environment);
        $doc['document_origin'] = 'received';
        $doc['issue_date'] = $doc['document_date'] ?? null;
        $doc['counterparty_name'] = $doc['supplier_name'] ?: ($doc['issuer_name'] ?? null);
        $doc['counterparty_tax_id'] = $doc['supplier_tax_id'] ?: ($doc['issuer_tax_id_code'] ?? null);
        $doc['is_tax_exempt'] = (int)($doc['document_type_id'] ?? 0) === 33
            || (string)($doc['document_type_taxbureau'] ?? '') === '34' ? 1 : 0;
        $doc['can_adjust'] = false;
        $doc['can_create_guide'] = false;
        $doc['lines'] = array();
        $doc['references'] = array();
        $doc['operations'] = array();
        $doc['dispatch_guides'] = array();
    } else {
        $doc = (new BillingIssuedDocumentsService(db()))->getDocument($_GET['id'] ?? 0, $environment);
        $doc['document_origin'] = 'issued';
        $doc['counterparty_name'] = $doc['customer_legal_name'] ?: ($doc['customer_name'] ?: $doc['receiver_legal_name']);
        $doc['counterparty_tax_id'] = $doc['receiver_tax_id_code'] ?? null;
    }
    echo json_encode(array('success'=>true,'document'=>$doc), 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);
}
