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

require_login();

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

if (!user_can('module.billing') && !user_can('billing.view') && !user_can('billing.prepare') && current_user_role() !== 'admin') {
    http_response_code(403);
    echo json_encode(array('success' => false, 'message' => 'No tienes permisos para enviar documentos tributarios.'));
    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);
$input = array(
    'log_id' => (int)($_POST['log_id'] ?? 0),
    'recipient_email' => $_POST['recipient_email'] ?? '',
    'cc_email' => $_POST['cc_email'] ?? '',
    'subject' => $_POST['subject'] ?? '',
    'body' => $_POST['body'] ?? '',
    'attach_pdf' => !empty($_POST['attach_pdf']),
    'attach_xml' => !empty($_POST['attach_xml'])
);

try {
    $service = new BillingDocumentEmailService(db());
    $result = $service->sendQuoteDocument($quoteId, $input);
    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);
}
