<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <title>Generate Verizon PDF</title>
    <style>
        body { font-family: sans-serif; margin: 20px; background-color: #f4f4f4; color: #333; }
        .container { background-color: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); max-width: 650px; margin: auto; }
        h1, h2 { text-align: center; color: #CD040B; } /* Verizon Red */
        h3 { margin-top: 30px; border-bottom: 1px solid #eee; padding-bottom: 5px; color: #333; }
        .form-group { margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; font-weight: bold; }
        input[type="text"] { width: calc(100% - 18px); padding: 8px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; }
        button { display: block; width: 100%; padding: 10px 15px; background-color: #CD040B; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; margin-top: 20px; }
        button:hover { background-color: #a80309; }
        #status { margin-top: 20px; font-weight: bold; text-align: center; }
        .grid-container { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; }
        .grid-3-col { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 15px; }
        .full-width { grid-column: 1 / -1; }
    </style>
</head>
<body>
    <div class="container">
        <h1>Generate Verizon PDF</h1>
        <form id="pdfForm">
            <h3>Основная информация</h3>
            <div class="grid-container">
                <div class="form-group">
                    <label>Account Number:</label>
                    <input type="text" name="account_number" value="326890199-00001">
                </div>
                <div class="form-group">
                    <label>Invoice Number:</label>
                    <input type="text" name="invoice_number" value="8614432777">
                </div>
                <div class="form-group">
                    <label>Customer Name:</label>
                    <input type="text" name="customer_name" value="GERMECIA JOSEPH">
                </div>
                <div class="form-group">
                    <label>Customer Address:</label>
                    <input type="text" name="customer_address" value="9400 ROBERTS DR">
                </div>
                <div class="form-group full-width">
                    <label>Customer City/State/ZIP:</label>
                    <input type="text" name="customer_city_st_zip" value="ATLANTA, GA 30350-2041">
                </div>
                <div class="form-group">
                    <label>Total Due Date (e.g., Feb 12):</label>
                    <input type="text" name="total_due_date" value="Feb 12">
                </div>
                <div class="form-group">
                    <label>Full Due Date (e.g., February 12, 2024):</label>
                    <input type="text" name="full_due_date" value="February 12, 2024">
                </div>
                <div class="form-group">
                    <label>Bill Month (e.g., January):</label>
                    <input type="text" name="bill_month" value="January">
                </div>
                <div class="form-group">
                    <label>Payment Received Amount:</label>
                    <input type="text" name="payment_received" value="$0.00">
                </div>
            </div>

            <h3>Детализация начислений (со стр. 4)</h3>
            <div class="grid-container grid-3-col">
                <div class="form-group">
                    <label>Activation fee:</label>
                    <input type="text" name="activation_fee" value="35.00">
                </div>
                <div class="form-group">
                    <label>Unlimited Ultimate Plan:</label>
                    <input type="text" name="plan_ultimate" value="100.00">
                </div>
                <div class="form-group">
                    <label>Apple One Individual:</label>
                    <input type="text" name="perk_apple_one" value="10.00">
                </div>
                <div class="form-group">
                    <label>Fed Universal Service Charge:</label>
                    <input type="text" name="surcharge_fus" value="6.20">
                </div>
                <div class="form-group">
                    <label>Regulatory Charge:</label>
                    <input type="text" name="surcharge_regulatory" value="0.16">
                </div>
                <div class="form-group">
                    <label>Admin & Telco Recovery:</label>
                    <input type="text" name="surcharge_admin" value="3.30">
                </div>
                <div class="form-group">
                    <label>GA Local 911 Surcharge:</label>
                    <input type="text" name="tax_911" value="1.50">
                </div>
                <div class="form-group">
                    <label>GA State Sls Tax:</label>
                    <input type="text" name="tax_ga_state" value="2.15">
                </div>
                <div class="form-group">
                    <label>Fulton Cnty Sls Tax:</label>
                    <input type="text" name="tax_fulton_county" value="2.01">
                </div>
            </div>

            <h3>Отрывной купон и штрих-код</h3>
            <div class="form-group full-width">
                <label>Barcode Number (низ страницы):</label>
                <input type="text" name="barcode_number" value="86144327770103268901990000100000016032000000160329">
            </div>
            
            <button type="submit">Generate and Download PDF</button>
        </form>
        <div id="status"></div>
    </div>

    <script>
        // ... (Ваш JavaScript код для отправки формы остается БЕЗ ИЗМЕНЕНИЙ) ...
        document.getElementById('pdfForm').addEventListener('submit', async function(event) {
            event.preventDefault();

            const statusDiv = document.getElementById('status');
            statusDiv.textContent = 'Generating PDF, please wait...';
            statusDiv.style.color = 'orange';

            const formData = new FormData(event.target);
            const data = {};
            formData.forEach((value, key) => { data[key] = value; });

            // try {
            //     data.usage_history_data = JSON.parse(data.usage_history_data);
            // } catch (e) {
            //     alert('Ошибка в JSON данных для истории потребления!');
            //     return; // Прервать отправку
            // }

            const apiUrl = '/pdfgen/api/v1/Verizon';
            const bearerToken = "43QAwPldLuuQTErY303m16lY5dSeDUy1OVKBzy5HTDG2KxfVC0m1o1cfZ49gbBRu";

            try {
                const response = await fetch(apiUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${bearerToken}`
                    },
                    body: JSON.stringify(data)
                });

                if (!response.ok) {
                    let errorText = `Error: ${response.status} ${response.statusText}`;
                    const responseBodyText = await response.text();
                    try {
                        const errorJson = JSON.parse(responseBodyText);
                        errorText += ` - ${errorJson.error || JSON.stringify(errorJson)}`;
                    } catch (e) {
                        if (responseBodyText) {
                            errorText += ` - ${responseBodyText}`;
                        }
                    }
                    throw new Error(errorText);
                }

                const contentDisposition = response.headers.get('content-disposition');
                let filename = "generated_aep_ohio.pdf";
                if (contentDisposition) {
                    const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                    const matches = filenameRegex.exec(contentDisposition);
                    if (matches != null && matches[1]) {
                        filename = matches[1].replace(/['"]/g, '');
                    }
                }

                const blob = await response.blob();
                const downloadUrl = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.style.display = 'none';
                a.href = downloadUrl;
                a.download = filename;
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(downloadUrl);
                document.body.removeChild(a);

                statusDiv.textContent = 'PDF downloaded successfully!';
                statusDiv.style.color = 'green';
            } catch (error) {
                console.error('Request failed:', error);
                statusDiv.textContent = `Failed to generate PDF: ${error.message}`;
                statusDiv.style.color = 'red';
            }
        });
    </script>
</body>
</html>