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

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

if (!user_can('billing.inbox.bulk_receive') && !user_can('billing.inbox.decide') && !user_can('billing.inbox.approve') && !user_can('billing.admin') && !user_can('module.billing') && current_user_role() !== 'admin') {
    http_response_code(403);
    echo json_encode(array('success' => false, 'message' => 'No tienes permisos para recepcion masiva de DTE.'));
    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_json'] ?? '[]';
    $ids = json_decode($rawIds, true);
    if (!is_array($ids)) {
        $ids = array();
    }

    $service = new BillingInboxReceptionService(db());
    $result = $service->bulkDecide($ids, array(
        'environment' => $_POST['environment'] ?? 'sandbox',
        'decision_type' => $_POST['decision_type'] ?? '',
        'reception_confirmed' => !empty($_POST['reception_confirmed']),
        'reception_place' => $_POST['reception_place'] ?? '',
        'contact_email' => $_POST['contact_email'] ?? '',
        'notes' => $_POST['notes'] ?? ''
    ), current_user_id());

    http_response_code(200);
    echo json_encode($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);
}
