<?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.collect') && !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 recibidos.'));
    exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(array('success' => false, 'message' => 'Metodo no permitido.'));
    exit;
}

try {
    $service = new BillingReceivablesService(db());
    $result = $service->registerPayment($_POST['id'] ?? '', 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,
        'expected_collection_id' => $_POST['expected_collection_id'] ?? null,
        'expected_document_id' => $_POST['expected_document_id'] ?? null,
        'expected_balance' => $_POST['expected_balance'] ?? null,
        'idempotency_key' => $_POST['idempotency_key'] ?? null,
    ), current_user_id());
    echo json_encode(array('success' => true, 'document' => $result['document'], 'payments' => $result['payments'], 'idempotent_replay' => !empty($result['idempotent_replay']), 'payment_batch_id' => $result['payment_batch_id'] ?? null, 'payment_id' => $result['payment_id'] ?? null), 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);
}
