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

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

if (!user_can('billing.payables') && !user_can('billing.payables.aging') && !user_can('module.billing') && current_user_role() !== 'admin') {
    http_response_code(403);
    echo json_encode(array('ok' => false, 'message' => 'No tienes permisos para ver aging proveedores.'), JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    $service = new BillingSupplierAgingService();
    $data = $service->summary(array(
        'environment' => isset($_GET['environment']) ? $_GET['environment'] : 'sandbox',
        'search' => isset($_GET['search']) ? $_GET['search'] : '',
        'bucket' => isset($_GET['bucket']) ? $_GET['bucket'] : 'all',
        'center_id' => isset($_GET['center_id']) ? $_GET['center_id'] : 'all',
        'limit' => isset($_GET['limit']) ? $_GET['limit'] : 5000,
    ));
    $data['centers'] = $service->listFinanceCenters();
    echo json_encode(array('ok' => true, 'data' => $data), JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(array('ok' => false, 'message' => $e->getMessage()), JSON_UNESCAPED_UNICODE);
}
