<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generate AEP Ohio 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: 600px; margin: auto; }
        h1 { text-align: center; color: #00609E; } /* AEP Blue */
        h2 { 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: #00609E;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            margin-top: 20px;
        }
        button:hover { background-color: #004c7e; }
        #status { margin-top: 20px; font-weight: bold; text-align: center; }
        .grid-container { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; }
        .full-width { grid-column: 1 / -1; }
    </style>
</head>
<body>

    <div class="container">
        <h1>Generate AEP Ohio PDF</h1>
        
        <form id="pdfForm">

            <h2>Основная информация</h2>
            <div class="grid-container">
                <div class="form-group">
                    <label for="customer_name">Customer Name:</label>
                    <input type="text" id="customer_name" name="customer_name" value="MAGGIORES WHOLESALE PUBLIC SALT">
                </div>
                 <div class="form-group">
                    <label for="attn_name">Attention Name (опционально):</label>
                    <input type="text" id="attn_name" name="attn_name" value="ATTN: TIM SALTER">
                </div>
                <div class="form-group full-width">
                    <label for="service_address">Service Address (полный адрес):</label>
                    <input type="text" id="service_address" name="service_address" value="2927 HARRISBURG RD NE, CANTON, OH 44705-2563">
                </div>
                <div class="form-group">
                    <label for="account_number">Account #:</label>
                    <input type="text" id="account_number" name="account_number" value="073-71205415">
                </div>
                <div class="form-group">
                    <label for="bill_mailing_date">Bill Mailing Date:</label>
                    <input type="text" id="bill_mailing_date" name="bill_mailing_date" value="Aug 15, 2018">
                </div>
                <div class="form-group">
                    <label for="amount_due_date">Amount Due Date:</label>
                    <input type="text" id="amount_due_date" name="amount_due_date" value="September 6, 2018">
                </div>
                <div class="form-group">
                     <label for="remit_pay_after_date_amount">Pay After Date Amount:</label>
                    <input type="text" id="remit_pay_after_date_amount" name="remit_pay_after_date_amount" value="Pay $533.41 after 09/06/2018">
                </div>
                 <div class="form-group full-width">
                    <label for="barcode_number">Barcode Number:</label>
                    <input type="text" id="barcode_number" name="barcode_number" value="0000526980000533410100000000000733129541515080809011900009">
                </div>
            </div>

            <h2>Период и потребление</h2>
             <div class="grid-container">
                 <div class="form-group">
                    <label for="billing_period_from">Billing From:</label>
                    <input type="text" id="billing_period_from" name="billing_period_from" value="07/17/18">
                </div>
                 <div class="form-group">
                    <label for="billing_period_to">Billing To:</label>
                    <input type="text" id="billing_period_to" name="billing_period_to" value="08/13/18">
                </div>
                <div class="form-group">
                    <label for="billing_period_days">Billing Days:</label>
                    <input type="text" id="billing_period_days" name="billing_period_days" value="(28 days)">
                </div>
                <div class="form-group">
                    <label for="current_charges_kwh">Current kWh:</label>
                    <input type="text" id="current_charges_kwh" name="current_charges_kwh" value="3,803">
                </div>
             </div>

            <h2>Детализация сборов AEP Ohio (для Delivery Charge)</h2>
            <div class="form-group">
                <label for="tariff_info_line">Строка тарифа:</label>
                <input type="text" id="tariff_info_line" name="tariff_info_line" value="Tariff 840 - Medium General Service 08/13/18">
            </div>
             <div class="form-group">
                <label for="service_delivery_identifier">Service Delivery Identifier:</label>
                <input type="text" id="service_delivery_identifier" name="service_delivery_identifier" value="00140060724501674">
            </div>
            <div class="grid-container">
                <div class="form-group">
                    <label for="transmission_service">Transmission Service ($):</label>
                    <input type="text" id="transmission_service" name="transmission_service" value="86.53">
                </div>
                <div class="form-group">
                    <label for="distribution_service">Distribution Service ($):</label>
                    <input type="text" id="distribution_service" name="distribution_service" value="155.81">
                </div>
                <div class="form-group">
                    <label for="customer_charge_detail">Customer Charge ($):</label>
                    <input type="text" id="customer_charge_detail" name="customer_charge_detail" value="22.79">
                </div>
                <div class="form-group">
                    <label for="retail_stability_rider">Retail Stability Rider ($):</label>
                    <input type="text" id="retail_stability_rider" name="retail_stability_rider" value="27.57">
                </div>
                <div class="form-group">
                    <label for="deferred_asset_rider">Deferred Asset Rider ($):</label>
                    <input type="text" id="deferred_asset_rider" name="deferred_asset_rider" value="7.30">
                </div>
                <div class="form-group">
                    <label for="phase_in_recovery_rider">Phase-In Recovery Rider ($):</label>
                    <input type="text" id="phase_in_recovery_rider" name="phase_in_recovery_rider" value="21.11">
                </div>
                <div class="form-group">
                    <label for="power_purchase_rider">Power Purchase Rider ($):</label>
                    <input type="text" id="power_purchase_rider" name="power_purchase_rider" value="0.25">
                </div>
            </div>

            <h2>Сборы поставщика (Supplier Charges)</h2>
            <div class="form-group">
                <label for="supplier_charges">Energy Supply ($):</label>
                <input type="text" id="supplier_charges" name="supplier_charges" value="198.52">
            </div>
            

            <hr>
            <h2>Предыдущие начисления (Previous Charges)</h2>
            <div class="grid-container">
                <div class="form-group">
                    <label for="total_amount_due_last_billing">Total Amount Due At Last Billing ($):</label>
                    <input type="text" id="total_amount_due_last_billing" name="total_amount_due_last_billing" value="782.05">
                </div>
                <div class="form-group">
                    <label for="payment_thank_you_date">Payment Date (e.g., 08/14/18):</label>
                    <input type="text" id="payment_thank_you_date" name="payment_thank_you_date" value="08/14/18">
                </div>
                <div class="form-group">
                    <label for="payment_thank_you_amount">Payment Received Amount ($):</label>
                    <input type="text" id="payment_thank_you_amount" name="payment_thank_you_amount" value="-782.05">
                </div>
                <div class="form-group">
                    <label for="late_payment_charge">Late Payment Charge ($):</label>
                    <input type="text" id="late_payment_charge" name="late_payment_charge" value="7.10">
                </div>
                <div class="form-group full-width">
                    <label for="previous_balance_due">Previous Balance Due ($):</label>
                    <input type="text" id="previous_balance_due" name="previous_balance_due" value="7.10">
                </div>
            </div>
            <hr>
            <h2>История потребления (Usage History)</h2>
            <div class="form-group full-width">
                <label for="usage_history_data">Данные в формате JSON (массив объектов):</label>
                <textarea id="usage_history_data" name="usage_history_data" rows="8">[
                    {"month": "Aug", "year": 2017, "kwh": 5605},
                    {"month": "Sep", "year": 2017, "kwh": 4379},
                    {"month": "Oct", "year": 2017, "kwh": 4876},
                    {"month": "Nov", "year": 2017, "kwh": 4676},
                    {"month": "Dec", "year": 2017, "kwh": 6952},
                    {"month": "Jan", "year": 2018, "kwh": 8434},
                    {"month": "Feb", "year": 2018, "kwh": 7836},
                    {"month": "Mar", "year": 2018, "kwh": 6225},
                    {"month": "Apr", "year": 2018, "kwh": 7420},
                    {"month": "May", "year": 2018, "kwh": 5991},
                    {"month": "Jun", "year": 2018, "kwh": 4404},
                    {"month": "Jul", "year": 2018, "kwh": 5175},
                    {"month": "Aug", "year": 2018, "kwh": 3803}
                ]
                </textarea>
            </div>

            <hr>
            <h2>Детали на странице 3 (маленькие графики)</h2>

            <h4>Usage (kWh)</h4>
            <div class="grid-container">
                <div class="form-group">
                    <label>Предыдущий год (e.g., Aug '17):</label>
                    <input type="text" name="usage_details_prev_year" value="5605">
                </div>
                <div class="form-group">
                    <label>Предыдущий месяц (e.g., Jul '18):</label>
                    <input type="text" name="usage_details_prev_month" value="5175">
                </div>
                <div class="form-group">
                    <label>Текущий месяц (e.g., Aug '18):</label>
                    <input type="text" name="usage_details_curr_month" value="3803">
                </div>
            </div>

            <h4>Avg. Daily Cost ($)</h4>
            <div class="grid-container">
                <div class="form-group">
                    <label>Предыдущий год (e.g., Aug '17):</label>
                    <input type="text" name="cost_details_prev_year" value="11.09">
                </div>
                <div class="form-group">
                    <label>Предыдущий месяц (e.g., Jul '18):</label>
                    <input type="text" name="cost_details_prev_month" value="11.48">
                </div>
                <div class="form-group">
                    <label>Текущий месяц (e.g., Aug '18):</label>
                    <!-- В оригинале это значение не показано, вводим примерное -->
                    <input type="text" name="cost_details_curr_month" value="11.75"> 
                </div>
            </div>

            <h4>Avg. Temperature (°F)</h4>
            <div class="grid-container">
                <div class="form-group">
                    <label>Предыдущий год (e.g., Aug '17):</label>
                    <input type="text" name="temp_details_prev_year" value="72">
                </div>
                <div class="form-group">
                    <label>Предыдущий месяц (e.g., Jul '18):</label>
                    <input type="text" name="temp_details_prev_month" value="73">
                </div>
                <div class="form-group">
                    <label>Текущий месяц (e.g., Aug '18):</label>
                    <input type="text" name="temp_details_curr_month" value="75">
                </div>
            </div>

            <hr>
            <h2>Квитанция о депозите (Deposit Receipt)</h2>
            <div class="grid-container">
                <div class="form-group">
                    <label for="area_office">Area Office:</label>
                    <input type="text" id="area_office" name="area_office" value="09210">
                </div>
                <div class="form-group">
                    <label for="cashier_number">Cashier Number:</label>
                    <input type="text" id="cashier_number" name="cashier_number" value="920">
                </div>
                <div class="form-group full-width">
                    <label for="deposit_number">Deposit Number:</label>
                    <input type="text" id="deposit_number" name="deposit_number" value="075050936 2537 003 20180813">
                </div>
                <div class="form-group">
                    <label for="deposit_date">Deposit Date:</label>
                    <input type="text" id="deposit_date" name="deposit_date" value="08/13/2018">
                </div>
                <div class="form-group">
                    <label for="deposit_amount">Deposit Amount ($):</label>
                    <input type="text" id="deposit_amount" name="deposit_amount" value="$157.00">
                </div>
            </div>

            <hr>
            <h2>Детализация потребления (Billed Usage & Meter Read)</h2>

            <h4>Таблица "Billed Usage"</h4>
            <div class="grid-container">
                <div class="form-group">
                    <label>Дата (e.g., 08/18):</label>
                    <input type="text" name="billed_usage_date" value="08/18">
                </div>
            </div>
            <div class="grid-container">
                <div class="form-group">
                    <label>kWh Usage:</label>
                    <input type="text" name="billed_usage_kwh_usage" value="3,803">
                </div>
                <div class="form-group">
                    <label>kWh Billed Usage:</label>
                    <input type="text" name="billed_usage_kwh_billed" value="3,803 kWh">
                </div>
                <div class="form-group">
                    <label>kW Usage:</label>
                    <input type="text" name="billed_usage_kw_usage" value="16.927">
                </div>
                <div class="form-group">
                    <label>kW Billed Usage:</label>
                    <input type="text" name="billed_usage_kw_billed" value="16.900 kW">
                </div>
            </div>

            <h4>Таблица "Meter Read Details"</h4>
            <div class="form-group">
                <label>Номер счетчика (Meter #):</label>
                <input type="text" name="meter_read_details_meter_no" value="92002912">
            </div>
            <h5>Строка kWh</h5>
            <div class="grid-container">
                <div class="form-group">
                    <label>Previous:</label>
                    <input type="text" name="meter_read_kwh_previous" value="86974">
                </div>
                <div class="form-group">
                    <label>Current:</label>
                    <input type="text" name="meter_read_kwh_current" value="90777">
                </div>
                <div class="form-group">
                    <label>Metered:</label>
                    <input type="text" name="meter_read_kwh_metered" value="3803">
                </div>
                <div class="form-group">
                    <label>Usage:</label>
                    <input type="text" name="meter_read_kwh_usage" value="3,803 kWh">
                </div>
            </div>
            <h5>Строка kW</h5>
            <div class="grid-container">
                 <div class="form-group">
                    <label>Current:</label>
                    <input type="text" name="meter_read_kw_current" value="16.927">
                </div>
                <div class="form-group">
                    <label>Metered:</label>
                    <input type="text" name="meter_read_kw_metered" value="16.927">
                </div>
                <div class="form-group">
                    <label>Usage:</label>
                    <input type="text" name="meter_read_kw_usage" value="16.927 kW">
                </div>
            </div>
            <div class="form-group">
                <label>Service Period:</label>
                <input type="text" name="meter_read_service_period" value="07/16 - 08/13">
            </div>
            <div class="form-group">
                <label>Next Read Date Info:</label>
                <input type="text" name="next_read_date_info" value="Next scheduled read date should be between Sep 11 and Sep 14.">
            </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/AEPOhio';
            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>