<?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/BillingRuntimeGate.php';
require_once '../../services/billing/BillingReceivablesService.php';
require_once '../../services/billing/BillingPayablesService.php';
require_once '../../services/facto/FactoDocumentsSyncService.php';

header('Content-Type: application/json; charset=UTF-8');
require_login();
csrf_require_valid_request();
$scope = trim((string)($_POST['scope'] ?? ''));
$environment = ($_POST['environment'] ?? 'production') === 'sandbox' ? 'sandbox' : 'production';
$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.payments') || user_can('billing.receivables') || user_can('module.billing'),
    'payables' => $admin || user_can('billing.payments') || user_can('billing.payables') || user_can('module.billing'),
    'customer_aging' => $admin || user_can('billing.payments') || user_can('billing.receivables') || user_can('module.billing'),
    'supplier_aging' => $admin || user_can('billing.payments') || user_can('billing.payables') || user_can('module.billing'),
);
if (empty($allowed[$scope])) {
    http_response_code(403);
    echo json_encode(array('success'=>false,'message'=>'No tienes permisos para actualizar estados masivamente.'));
    exit;
}

try {
    billing_assert_runtime_operation($scope === 'documents' ? 'sync' : 'finance', $environment, 'Actualización masiva de estados');
    if ($scope === 'documents') {
        $from = preg_match('/^\d{4}-\d{2}-\d{2}$/', (string)($_POST['from'] ?? '')) ? $_POST['from'] : date('Y-m-d', strtotime('-90 days'));
        $to = preg_match('/^\d{4}-\d{2}-\d{2}$/', (string)($_POST['to'] ?? '')) ? $_POST['to'] : date('Y-m-d');
        $affected = (new FactoDocumentsSyncService($environment))->syncIssuedDocuments($from, $to, 100, false);
        $message = 'Estados FACTO sincronizados: ' . (int)$affected . ' documentos procesados.';
    } elseif (in_array($scope, array('receivables','customer_aging'), true)) {
        (new BillingReceivablesService())->refreshCalculatedReceivableStatuses($environment);
        $affected = null;
        $message = 'Estados de cuentas por cobrar y aging recalculados.';
    } else {
        (new BillingPayablesService())->refreshAgingState($environment);
        $affected = null;
        $message = 'Estados de cuentas por pagar y aging recalculados.';
    }
    try {
        $stmt = db()->prepare('INSERT INTO billing_bulk_action_logs (environment,scope,action_key,selected_count,filters_json,result_message,created_by,created_at) VALUES (?,?,?,?,?,?,?,NOW())');
        $stmt->execute(array($environment,$scope,'refresh_statuses',0,json_encode($_POST,JSON_UNESCAPED_UNICODE),$message,function_exists('current_user_id')?current_user_id():null));
    } catch (Throwable $ignored) {}
    echo json_encode(array('success'=>true,'message'=>$message,'affected'=>$affected));
} catch (Throwable $e) {
    http_response_code(422);
    echo json_encode(array('success'=>false,'message'=>$e->getMessage()));
}
