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

if (!user_can('billing.payables') && !user_can('billing.payables.manage') && !user_can('module.billing') && current_user_role() !== 'admin') {
    http_response_code(403);
    echo json_encode(array('success' => false, 'message' => 'No tienes permisos para actualizar cuentas por pagar.'));
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(array('success' => false, 'message' => 'Metodo no permitido.'));
    exit;
}

try {
    $service = new BillingPayablesService(db());
    $id = $_POST['id'] ?? '';
    $result = $service->updateDocument($id, array(
        'environment' => $_POST['environment'] ?? 'sandbox',
        'finance_center_id' => $_POST['finance_center_id'] ?? null,
        'payment_due_date' => $_POST['payment_due_date'] ?? null,
        'payment_status' => $_POST['payment_status'] ?? 'por_pagar',
        'notes' => $_POST['notes'] ?? null,
        'materialize_collection' => !empty($_POST['materialize_collection']),
        'expected_inbox_document_id' => $_POST['expected_inbox_document_id'] ?? 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);
}
