<?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/BillingCustomerAgingService.php';
require_login();
header('Content-Type: application/json; charset=utf-8');
if (!user_can('billing.receivables.aging') && !user_can('billing.receivables') && !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 clientes.')); exit;
}
try {
    $service = new BillingCustomerAgingService(db());
    $data = $service->summary(array(
        'environment'=>$_GET['environment'] ?? 'sandbox',
        'search'=>$_GET['search'] ?? '',
        'bucket'=>$_GET['bucket'] ?? 'all',
        'center_id'=>$_GET['center_id'] ?? 'all',
    ));
    echo json_encode(array('ok'=>true,'data'=>$data), JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
    http_response_code(400); echo json_encode(array('ok'=>false,'message'=>$e->getMessage()), JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
}
