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

require_login();
csrf_require_valid_request();

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

$environment = billing_runtime_environment(null);
$isAdmin = user_can('billing.admin') || current_user_role() === 'admin';
$hasEnvironmentPermission = $environment === 'production'
    ? user_can('billing.issue.production')
    : user_can('billing.issue.sandbox');
if (!$isAdmin && !$hasEnvironmentPermission) {
    http_response_code(403);
    echo json_encode(array(
        'success' => false,
        'message' => $environment === 'production'
            ? 'No tienes el permiso billing.issue.production para emitir documentos reales.'
            : 'No tienes el permiso billing.issue.sandbox para emitir documentos de prueba.'
    ));
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    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'));

$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,
    'receiver_tax_id_code' => $_POST['receiver_tax_id_code'] ?? null,
    'receiver_tax_id_type' => $_POST['receiver_tax_id_type'] ?? null,
    'receiver_legal_name' => $_POST['receiver_legal_name'] ?? null,
    'receiver_address' => $_POST['receiver_address'] ?? null,
    'receiver_district' => $_POST['receiver_district'] ?? null,
    'receiver_city' => $_POST['receiver_city'] ?? null,
    'receiver_phone' => $_POST['receiver_phone'] ?? null,
    'receiver_activity' => $_POST['receiver_activity'] ?? null,
    'receiver_email' => $_POST['receiver_email'] ?? null,
    'export_pricing_mode' => $_POST['export_pricing_mode'] ?? 'convert_from_clp',
    '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,
    'confirmation' => $_POST['confirmation'] ?? '',
    'mark_as_paid' => filter_var($_POST['mark_as_paid'] ?? false, FILTER_VALIDATE_BOOLEAN),
    'payment_date' => $_POST['payment_date'] ?? date('Y-m-d'),
    'payment_method_id' => $_POST['payment_method_id'] ?? null,
    'payment_method' => $_POST['payment_method'] ?? null,
    'payment_method_label' => $_POST['payment_method_label'] ?? null,
    'cash_account_id' => $_POST['cash_account_id'] ?? null,
    'cash_account_key' => $_POST['cash_account_key'] ?? null,
    'cash_account_label' => $_POST['cash_account_label'] ?? null,
    'payment_reference' => $_POST['payment_reference'] ?? null,
    'payment_notes' => $_POST['payment_notes'] ?? null
);

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

    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);
}
