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

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

if (!user_can('billing.payables.bulk_pay') && !user_can('billing.payables.pay') && !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 registrar pagos masivos a proveedor.'));
    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 BillingPayablesService(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
    ), 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);
}
