<?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();
csrf_require_valid_request();
header('Content-Type: application/json; charset=utf-8');

if (!user_can('billing.receivables.bulk_collect')) {
    http_response_code(403);
    echo json_encode(array('success' => false, 'message' => 'No tienes permisos para ejecutar esta operación masiva.'));
    exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(array('success' => false, 'message' => 'Metodo no permitido.'));
    exit;
}

try {
    $rawIds = $_POST['ids'] ?? '';
    if (is_string($rawIds)) {
        $decoded = json_decode($rawIds, true);
        $ids = is_array($decoded) ? $decoded : explode(',', $rawIds);
    } else {
        $ids = is_array($rawIds) ? $rawIds : array();
    }
    $service = new BillingReceivablesService(db());
    $result = $service->registerBulkPayment($ids, array(
        'environment' => $_POST['environment'] ?? 'sandbox',
        'payment_date' => $_POST['payment_date'] ?? date('Y-m-d'),
        'amount' => $_POST['amount'] ?? 0,
        'payment_method_id' => $_POST['payment_method_id'] ?? null,
        'cash_account_id' => $_POST['cash_account_id'] ?? null,
        'external_reference' => $_POST['external_reference'] ?? null,
        'notes' => $_POST['notes'] ?? null,
        'full_payment' => !empty($_POST['full_payment']) && $_POST['full_payment'] !== '0' ? 1 : 0,
        'idempotency_key' => $_POST['idempotency_key'] ?? null,
        'selection_snapshot' => $_POST['selection_snapshot'] ?? null,
    ), current_user_id());
    echo json_encode(array('success' => true, 'result' => $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);
}
