<?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/BillingReceivablesService.php';

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

if (!user_can('billing.receivables') && !user_can('billing.payments') && !user_can('module.billing') && current_user_role() !== 'admin') {
    http_response_code(403);
    echo json_encode(array('success' => false, 'message' => 'No tienes permisos para ver cuentas por cobrar.'));
    exit;
}

try {
    $service = new BillingReceivablesService(db());
    $result = $service->listReceivables(array(
        'environment' => $_GET['env'] ?? (defined('FACTO_DEFAULT_ENVIRONMENT') ? FACTO_DEFAULT_ENVIRONMENT : 'production'),
        'status' => $_GET['status'] ?? 'open',
        'search' => $_GET['search'] ?? '',
        'date_from' => $_GET['date_from'] ?? '',
        'date_to' => $_GET['date_to'] ?? '',
        'limit' => $_GET['limit'] ?? 10000,
    ));
    $result['options'] = $service->getOptions($_GET['env'] ?? (defined('FACTO_DEFAULT_ENVIRONMENT') ? FACTO_DEFAULT_ENVIRONMENT : 'production'));
    $isBillingAdmin = user_can('billing.admin') || current_user_role() === 'admin';
    $result['options']['can_void_payments'] = $isBillingAdmin || user_can('billing.payments.reverse');
    $result['options']['can_repair_origin'] = $isBillingAdmin || user_can('billing.issue.production');
    $result['options']['can_reopen_receivable'] = $isBillingAdmin || user_can('billing.receivables.manage');
    echo json_encode(array('success' => true, 'data' => $result), 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);
}
