<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generate Entergy 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: #00938F; }
        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"], textarea {
            width: calc(100% - 18px); padding: 8px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box;
        }
        textarea { resize: vertical; }
        button { display: block; width: 100%; padding: 10px 15px; background-color: #00938F; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; margin-top: 20px; }
        button:hover { background-color: #007a76; }
        #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 Entergy PDF</h1>
        
        <form id="pdfForm">

            <h3>Основная информация</h3>
            <div class="grid-container">
                <div class="form-group">
                    <label>Customer Name:</label>
                    <input type="text" name="customer_name" value="James">
                </div>
                 <div class="form-group">
                    <label>Mail Date:</label>
                    <input type="text" name="mail_date" value="06/28/2023">
                </div>
                 <div class="form-group">
                    <label>Account #:</label>
                    <input type="text" name="account_number" value="193815735">
                </div>
                 <div class="form-group">
                    <label>Invoice #:</label>
                    <input type="text" name="invoice_number" value="70007737428">
                </div>
                <div class="form-group">
                    <label>QPC:</label>
                    <input type="text" name="qpc_code" value="07000">
                </div>
                <div class="form-group">
                    <label>Cycle:</label>
                    <input type="text" name="cycle_number" value="20">
                </div>
                 <div class="form-group">
                    <label>Amount Due by Date:</label>
                    <input type="text" name="amount_due_by_date" value="08/10/2023">
                </div>
                 <div class="form-group">
                    <label>Amount Due After Date:</label>
                    <input type="text" name="amount_due_after_date" value="08/10/2023">
                </div>
            </div>

            <h3>Адрес обслуживания</h3>
             <div class="form-group full-width">
                <label>Service Location (Line 1):</label>
                <input type="text" name="service_location_line1" value="844 Carmadelle St">
            </div>
            <div class="form-group full-width">
                <label>Service Location (Line 2):</label>
                <input type="text" name="service_location_line2" value="Marrero, LA 70072-1322">
            </div>

            <h3>Детализация начислений (со стр. 2)</h3>
            <div class="grid-3-col">
                <div class="form-group">
                    <label>Energy Charge ($):</label>
                    <input type="text" name="energy_charge" value="257.69">
                </div>
                 <div class="form-group">
                    <label>Federal EAC Rider ($):</label>
                    <input type="text" name="federal_eac_rider" value="0.12">
                </div>
                 <div class="form-group">
                    <label>Fuel Adjustment ($):</label>
                    <input type="text" name="fuel_adjustment" value="58.23">
                </div>
                 <div class="form-group">
                    <label>Storm Restoration Offset ($):</label>
                    <input type="text" name="storm_restoration_offset" value="-5.74">
                </div>
                 <div class="form-group">
                    <label>Storm Restoration Charge ($):</label>
                    <input type="text" name="storm_restoration_charge" value="46.03">
                </div>
                 <div class="form-group">
                    <label>Deposit ($) (опционально):</label>
                    <input type="text" name="deposit" value="150.00">
                </div>
                 <div class="form-group">
                    <label>Connect Fee ($) (опционально):</label>
                    <input type="text" name="connect_fee" value="12.50">
                </div>
            </div>

            <h3>Сумма к оплате после срока</h3>
             <div class="form-group">
                <label>Amount Due After ($):</label>
                <input type="text" name="amount_due_after_value" value="536.65">
            </div>

            <h3>Потребление (Billing Period)</h3>
            <div class="grid-container">
                 <div class="form-group">
                    <label>Billing Days:</label>
                    <input type="text" name="billing_days" value="25">
                </div>
                 <div class="form-group">
                    <label>kWh Used:</label>
                    <input type="text" name="kwh_used" value="2950">
                </div>
                 <div class="form-group">
                    <label>Avg kWh Per Day:</label>
                    <input type="text" name="avg_kwh_per_day" value="118.0">
                </div>
            </div>

            <h3>История потребления (JSON)</h3>
            <div class="form-group full-width">
                <label>Данные в формате JSON (массив):</label>
                <textarea name="usage_history_data" rows="5">[
                    {"month": "JAN", "kwh": 1000}, {"month": "FEB", "kwh": 900}, {"month": "MAR", "kwh": 850},
                    {"month": "APR", "kwh": 950}, {"month": "MAY", "kwh": 1200}, {"month": "JUN", "kwh": 2950},
                    {"month": "JUL", "kwh": 0}, {"month": "AUG", "kwh": 0}, {"month": "SEP", "kwh": 0},
                    {"month": "OCT", "kwh": 0}, {"month": "NOV", "kwh": 0}, {"month": "DEC", "kwh": 0}
                ]</textarea>
            </div>

            <h3>Детализация счетчика (со стр. 2)</h3>
            <div class="grid-container">
                <div class="form-group">
                    <label>Номер контракта:</label>
                    <input type="text" name="meter_reading_contract" value="22371189">
                </div>
                <div class="form-group">
                    <label>Номер счетчика (Meter #):</label>
                    <input type="text" name="meter_number" value="AM11627352">
                </div>
                <div class="form-group">
                    <label>Тариф (Rate):</label>
                    <input type="text" name="meter_rate" value="LA_RS">
                </div>
            </div>
            <div class="grid-container">
                <div class="form-group">
                    <label>Дата/Время текущего показания:</label>
                    <input type="text" name="current_meter_reading_datetime" value="06/26/2023 11:59 PM">
                </div>
                <div class="form-group">
                    <label>Значение текущего показания:</label>
                    <input type="text" name="current_meter_reading_value" value="77886">
                </div>
                <div class="form-group">
                    <label>Дата/Время предыдущего показания:</label>
                    <input type="text" name="previous_meter_reading_datetime" value="06/02/2023 00:00 AM">
                </div>
                <div class="form-group">
                    <label>Значение предыдущего показания:</label>
                    <input type="text" name="previous_meter_reading_value" value="74936">
                </div>
            </div>

            <h3>Отрывной купон</h3>
             <div class="form-group full-width">
                <label>Customer Name & Address (для купона):</label>
                <textarea name="remit_customer_address" rows="3">JAMES STUTES
844 CARMADELLE ST
MARRERO LA 70072-1322</textarea>
            </div>
            <div class="form-group full-width">
                <label>Barcode Number (низ страницы):</label>
                <input type="text" name="barcode_number" value="700000019381573500000000051883700000053665622206">
            </div>
            
            <button type="submit">Generate and Download PDF</button>
        </form>

        <div id="status"></div>
    </div>

    <script>
        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 данных для истории потребления!');
                statusDiv.textContent = 'Ошибка в JSON данных!';
                statusDiv.style.color = 'red';
                return;
            }

            const apiUrl = '/pdfgen/api/v1/Entergy'; // <--- API ЭНДПОИНТ
            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 {
                        errorText += ` - ${JSON.parse(responseBodyText).error || responseBodyText}`;
                    } catch (e) {
                        if (responseBodyText) errorText += ` - ${responseBodyText}`;
                    }
                    throw new Error(errorText);
                }

                const contentDisposition = response.headers.get('content-disposition');
                let filename = "generated_entergy.pdf";
                if (contentDisposition) {
                    const matches = /filename="([^"]+)"/.exec(contentDisposition);
                    if (matches != null && matches[1]) filename = matches[1];
                }

                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>