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

require_login();

if (!user_can('module.billing') && !user_can('billing.prepare') && current_user_role() !== 'admin') {
    http_response_code(403);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(array('success' => false, 'message' => 'No tienes permisos para preparar facturacion.'));
    exit;
}

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

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

$quoteId = (int) ($_POST['quote_id'] ?? 0);
$documentKey = trim((string) ($_POST['document_key'] ?? 'invoice_electronic'));
$environment = trim((string) ($_POST['environment'] ?? (defined('FACTO_DEFAULT_ENVIRONMENT') ? FACTO_DEFAULT_ENVIRONMENT : 'sandbox')));

$options = array(
    'environment' => $environment,
    'issue_date' => $_POST['issue_date'] ?? date('Y-m-d'),
    'payment_terms' => $_POST['payment_terms'] ?? '',
    'custom_payment_days' => $_POST['custom_payment_days'] ?? null,
    'currency_code' => $_POST['currency_code'] ?? 'CLP',
    'exchange_rate_value' => $_POST['exchange_rate_value'] ?? null,
    'receiver_country_id' => $_POST['receiver_country_id'] ?? null,
    'sale_modality' => $_POST['sale_modality'] ?? null,
    'sale_clause' => $_POST['sale_clause'] ?? null,
    'guide_type' => $_POST['guide_type'] ?? null,
    'transfer_type' => $_POST['transfer_type'] ?? null,
    'shipping_address' => $_POST['shipping_address'] ?? null,
    'source_facto_document_id' => $_POST['source_facto_document_id'] ?? null,
    'reference_code' => $_POST['reference_code'] ?? null,
    'reference_description' => $_POST['reference_description'] ?? null
);

try {
    $service = new BillingIssueValidationService(db());
    $result = $service->validateQuoteForIssue($quoteId, $documentKey, $options);

    echo json_encode(array(
        'success' => true,
        'validation' => $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);
}
