<?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/SimpleXlsxExporter.php';
require_once '../../services/billing/BillingIssuedDocumentsService.php';
require_once '../../services/billing/BillingReceivablesService.php';
require_once '../../services/billing/BillingPayablesService.php';
require_once '../../services/billing/BillingCustomerAgingService.php';
require_once '../../services/billing/BillingSupplierAgingService.php';

require_login();
$scope = trim((string)($_GET['scope'] ?? ''));
$environment = ($_GET['environment'] ?? 'production') === 'sandbox' ? 'sandbox' : 'production';
$selectedIds = array_values(array_filter(array_map('intval', explode(',', (string)($_GET['ids'] ?? '')))));
$includeRow = function ($row) use ($selectedIds) { return !$selectedIds || in_array((int)$row['id'], $selectedIds, true); };
$admin = current_user_role() === 'admin';
$allowed = array(
    'documents' => $admin || user_can('billing.documents') || user_can('billing.view') || user_can('module.billing'),
    'receivables' => $admin || user_can('billing.receivables') || user_can('billing.payments') || user_can('module.billing'),
    'payables' => $admin || user_can('billing.payables') || user_can('billing.inbox') || user_can('module.billing'),
    'customer_aging' => $admin || user_can('billing.receivables.aging') || user_can('billing.receivables') || user_can('module.billing'),
    'supplier_aging' => $admin || user_can('billing.payables.aging') || user_can('billing.payables') || user_can('module.billing'),
);
if (empty($allowed[$scope])) { http_response_code(403); die('Sin permisos para exportar esta información.'); }

try {
    $rows = array();
    if ($scope === 'documents') {
        $result = (new BillingIssuedDocumentsService())->listDocuments(array('environment'=>$environment,'search'=>$_GET['search']??'','family'=>$_GET['family']??'all','from'=>$_GET['from']??'','to'=>$_GET['to']??''));
        $headers = array('ID','Ambiente','Tipo','Folio','Fecha','Cliente','RUT','Neto','Impuestos','Total','Estado DTE','Estado cobro','Pagado','Saldo','FACTO document_id');
        foreach ($result['rows'] as $r) if ($includeRow($r)) $rows[] = array($r['id'],$r['environment'],$r['document_label'],$r['document_number'],$r['issue_date'],$r['customer_legal_name']?:($r['customer_name']?:$r['receiver_legal_name']),$r['receiver_tax_id_code'],$r['net_amount'],$r['taxes_amount'],$r['total_amount'],$r['document_status'],$r['collection_status'],$r['paid_amount'],$r['balance_amount'],$r['document_id']);
    } elseif ($scope === 'receivables') {
        $result = (new BillingReceivablesService())->listReceivables(array('environment'=>$environment,'search'=>$_GET['search']??'','status'=>$_GET['status']??'open','date_from'=>$_GET['from']??'','date_to'=>$_GET['to']??'','limit'=>5000));
        $headers = array('ID','Folio','Tipo','Fecha emisión','Vencimiento','Cliente','RUT','Total neto','Pagado neto equivalente','Saldo neto','Total bruto','Pagado bruto','Saldo bruto','Estado','Centro','Cotización','FACTO document_id');
        foreach ($result['rows'] as $r) if ($includeRow($r)) $rows[] = array($r['id'],$r['document_number'],$r['document_label'],$r['issue_date'],$r['due_date']?:$r['payment_due_date'],$r['customer_name']?:$r['receiver_legal_name'],$r['customer_tax_id']?:$r['receiver_tax_id_code'],$r['collection_net_total']??($r['net_amount_clp']??($r['net_amount']??0)),$r['paid_net_amount']??0,$r['net_balance_amount']??0,$r['collection_total']?:$r['total_amount'],$r['paid_amount'],$r['balance_amount'],$r['collection_status']?:$r['payment_status'],$r['finance_center_name'],$r['quote_number'],$r['document_id']);
    } elseif ($scope === 'payables') {
        $result = (new BillingPayablesService())->listPayables(array('environment'=>$environment,'search'=>$_GET['search']??'','status'=>$_GET['status']??'open','date_from'=>$_GET['from']??'','date_to'=>$_GET['to']??'','limit'=>1000));
        $headers = array('ID','Folio','Tipo','Fecha documento','Vencimiento','Proveedor','RUT','Total','Pagado','Saldo','Estado','Aprobación','Centro','FACTO inbox_id');
        foreach ($result['rows'] as $r) if ($includeRow($r)) $rows[] = array($r['id'],$r['document_number'],$r['document_label'],$r['document_date'],$r['due_date']?:$r['payment_due_date'],$r['supplier_name']?:$r['issuer_name'],$r['supplier_tax_id']?:$r['issuer_tax_id_code'],$r['collection_total']?:$r['total_amount'],$r['paid_amount'],$r['balance_amount'],$r['payment_status'],$r['document_approval_status'],$r['finance_center_name'],$r['inbox_document_id']);
    } elseif ($scope === 'customer_aging') {
        $result = (new BillingCustomerAgingService())->summary(array('environment'=>$environment,'search'=>$_GET['search']??'','bucket'=>$_GET['bucket']??'all','center_id'=>$_GET['center_id']??'all'));
        $headers = array('Cliente','RUT','Documentos','Saldo abierto neto','Vencido neto','No vencido neto','Por vencer 7d neto','1-30 neto','31-60 neto','61-90 neto','90+ neto','Centro');
        foreach ($result['rows'] as $r) $rows[] = array($r['customer_name'],$r['customer_tax_id'],$r['documents_count'],$r['open_balance'],$r['overdue_balance'],$r['current_balance'],$r['due_7_balance'],$r['bucket_1_30'],$r['bucket_31_60'],$r['bucket_61_90'],$r['bucket_90_plus'],$r['finance_center_name']??'');
    } else {
        $result = (new BillingSupplierAgingService())->summary(array('environment'=>$environment,'search'=>$_GET['search']??'','bucket'=>$_GET['bucket']??'all','center_id'=>$_GET['center_id']??'all','limit'=>5000));
        $headers = array('Proveedor','RUT','Documentos','Saldo abierto','Vencido','No vencido','Por vencer 7d','1-30','31-60','61-90','90+','Centro');
        foreach ($result['rows'] as $r) $rows[] = array($r['supplier_name'],$r['supplier_tax_id'],$r['documents_count'],$r['open_balance'],$r['overdue_balance'],$r['current_balance'],$r['due_7_balance'],$r['bucket_0_30'],$r['bucket_31_60'],$r['bucket_61_90'],$r['bucket_90_plus'],$r['finance_center_name']??'');
    }
    SimpleXlsxExporter::download('icylab_' . $scope . '_' . $environment . '_' . date('Ymd_His') . '.xlsx', $headers, $rows);
} catch (Throwable $e) {
    http_response_code(500);
    echo 'No se pudo generar el XLSX: ' . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8');
}
