<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <title>Generate PG&E Energy Statement</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, h2 { text-align: center; color: #0077c8; }
        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: #0077c8; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; margin-top: 20px; }
        button:hover { background-color: #005a9c; }
        #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; }
        .note { font-size: 0.9em; color: #666; }
    </style>
</head>
<body>
    <div class="container">
        <h1>Generate PG&E Energy Statement</h1>
        
        <form id="pdfForm">

            <h3>Основная информация о счете</h3>
            <div class="grid-container">
                <div class="form-group">
                    <label>Account No:</label>
                    <input type="text" name="account_no" value="1234567890-1">
                </div>
                <div class="form-group">
                    <label>Statement Date:</label>
                    <input type="text" name="statement_date" value="09/07/2019">
                </div>
                <div class="form-group">
                    <label>Due Date:</label>
                    <input type="text" name="due_date" value="09/28/2019">
                </div>
            </div>

            <h3>Адрес обслуживания</h3>
            <div class="grid-container">
                 <div class="form-group">
                    <label>Service For (Name):</label>
                    <input type="text" name="service_for_name" value="SPARKY JOULE">
                </div>
                 <div class="form-group">
                    <label>Address Line:</label>
                    <input type="text" name="service_for_address" value="12345 ENERGY CT">
                </div>
            </div>

            <h3>Сводка по счету (Account Summary)</h3>
            <div class="grid-container">
                 <div class="form-group">
                    <label>Previous Statement ($):</label>
                    <input type="text" name="previous_statement" value="91.57">
                </div>
                 <div class="form-group">
                    <label>Payment Received ($):</label>
                    <input type="text" name="payment_received" value="-91.57">
                </div>
                 <div class="form-group">
                    <label>Previous Unpaid Balance ($):</label>
                    <input type="text" name="previous_unpaid_balance" value="0.00">
                </div>
                <div class="form-group">
                    <label>PG&E Delivery Charges ($):</label>
                    <input type="text" name="pge_delivery_charges" value="55.66">
                </div>
                <div class="form-group">
                    <label>SVCE Generation Charges ($):</label>
                    <input type="text" name="svce_generation_charges" value="32.48">
                </div>
                <div class="form-group">
                    <label>Total Amount Due Date (e.g., 08/28/2019):</label>
                    <input type="text" name="total_amount_due_date" value="08/28/2019">
                </div>
                <div class="form-group full-width">
                    <label>Total Amount Due ($):</label>
                    <input type="text" name="total_amount_due" value="88.14">
                </div>
            </div>

            <h3>Отрывной купон</h3>
            <div class="grid-container">
                <div class="form-group">
                    <label>Account Number (на купоне):</label>
                    <input type="text" name="remit_account_number" value="123456789-1">
                </div>
                <div class="form-group">
                    <label>Due Date (на купоне):</label>
                    <input type="text" name="remit_due_date" value="09/28/2019">
                </div>
                <div class="form-group">
                    <label>Total Amount Due (на купоне):</label>
                    <input type="text" name="remit_total_amount_due" value="88.14">
                </div>
            </div>

            <h3>Данные для графиков</h3>
            <div class="form-group full-width">
                <label>Monthly Billing History (JSON - массив объектов):</label>
                <textarea name="monthly_billing_history" rows="6">[
                    {"month": "8/07", "electric": "80", "gas": "20"},
                    {"month": "9/06", "electric": "75", "gas": "15"},
                    {"month": "10/04", "electric": "70", "gas": "30"},
                    {"month": "11/06", "electric": "90", "gas": "40"},
                    {"month": "12/06", "electric": "110", "gas": "50"},
                    {"month": "1/08", "electric": "130", "gas": "60"},
                    {"month": "2/06", "electric": "120", "gas": "55"},
                    {"month": "3/07", "electric": "100", "gas": "45"},
                    {"month": "4/08", "electric": "95", "gas": "35"},
                    {"month": "5/09", "electric": "85", "gas": "25"},
                    {"month": "6/06", "electric": "90", "gas": "20"},
                    {"month": "7/10", "electric": "105", "gas": "10"},
                    {"month": "8/07", "electric": "115", "gas": "5"}
                ]</textarea>
            </div>
            <div class="grid-container">
                <div class="form-group">
                    <label>Daily Electric (1 Year Ago):</label>
                    <input type="text" name="daily_usage_electric[year_ago]" value="0.12">
                </div>
                <div class="form-group">
                    <label>Daily Electric (Last Period):</label>
                    <input type="text" name="daily_usage_electric[last_period]" value="0.16">
                </div>
                 <div class="form-group">
                    <label>Daily Electric (Current):</label>
                    <input type="text" name="daily_usage_electric[current_period]" value="0.17">
                </div>
                <div class="form-group">
                    <label>Daily Gas (1 Year Ago):</label>
                    <input type="text" name="daily_usage_gas[year_ago]" value="12.50">
                </div>
                <div class="form-group">
                    <label>Daily Gas (Last Period):</label>
                    <input type="text" name="daily_usage_gas[last_period]" value="12.16">
                </div>
                 <div class="form-group">
                    <label>Daily Gas (Current):</label>
                    <input type="text" name="daily_usage_gas[current_period]" value="12.67">
                </div>
            </div>
            <!-- Вставьте этот блок в ваш pge_form.html -->

            <h3>Детализация Electric Charges (со стр. 2)</h3>
            <div class="grid-container grid-3-col">
                <div class="form-group">
                    <label>Conservation Incentive:</label>
                    <input type="text" name="electric_conservation_incentive" value="-9.50">
                </div>
                <div class="form-group">
                    <label>Transmission:</label>
                    <input type="text" name="electric_transmission" value="12.42">
                </div>
                <div class="form-group">
                    <label>Distribution:</label>
                    <input type="text" name="electric_distribution" value="35.08">
                </div>
                <div class="form-group">
                    <label>Electric Public Purpose:</label>
                    <input type="text" name="electric_public_purpose" value="4.71">
                </div>
                <div class="form-group">
                    <label>Nuclear Decommissioning:</label>
                    <input type="text" name="electric_nuclear_decommissioning" value="0.33">
                </div>
                <div class="form-group">
                    <label>DWR Bond Charge:</label>
                    <input type="text" name="electric_dwr_bond" value="1.91">
                </div>
                <div class="form-group">
                    <label>CTC:</label>
                    <input type="text" name="electric_ctc" value="0.42">
                </div>
                <div class="form-group">
                    <label>Energy Cost Recovery:</label>
                    <input type="text" name="electric_ecra" value="-0.22">
                </div>
                <div class="form-group">
                    <label>PCIA:</label>
                    <input type="text" name="electric_pcia" value="10.26">
                </div>
                <div class="form-group">
                    <label>Taxes and Other:</label>
                    <input type="text" name="electric_taxes_and_other" value="0.25">
                </div>
                <div class="form-group">
                    <label>Total Electric Charges:</label>
                    <input type="text" name="electric_total_charges" value="55.66">
                </div>
            </div> 

            <!-- Вставьте этот блок в ваш pge_form.html -->

            <h3>Детализация со страницы 3</h3>

            <h4>Информация о периоде и тарифе</h4>
            <div class="grid-container">
                <div class="form-group full-width">
                    <label>Период Delivery Charges (заменит '08/02/2019 - 08/31/2019 (30 billing days)'):</label>
                    <input type="text" name="delivery_charges_period" value="08/02/2019 - 08/31/2019 (30 billing days)">
                </div>
                <div class="form-group">
                    <label>Service Agreement ID (заменит '111111111'):</label>
                    <input type="text" name="service_agreement_id" value="111111111">
                </div>
                <div class="form-group">
                    <label>Rate Schedule (заменит 'E1 X Residential Service'):</label>
                    <input type="text" name="rate_schedule" value="E1 X Residential Service">
                </div>
            </div>

            <h4>Service Information (правая колонка)</h4>
            <div class="grid-container">
                <div class="form-group">
                    <label>Meter #:</label>
                    <input type="text" name="meter_number" value="1111111111">
                </div>
                <div class="form-group">
                    <label>Current Meter Reading:</label>
                    <input type="text" name="current_meter_reading" value="37,710">
                </div>
                <div class="form-group">
                    <label>Prior Meter Reading:</label>
                    <input type="text" name="prior_meter_reading" value="37,330">
                </div>
                <div class="form-group">
                    <label>Total Usage (kWh):</label>
                    <input type="text" name="total_usage_kwh" value="380.000000 kWh">
                </div>
                <div class="form-group">
                    <label>Baseline Territory:</label>
                    <input type="text" name="baseline_territory" value="X">
                </div>
                <div class="form-group">
                    <label>Heat Source:</label>
                    <input type="text" name="heat_source" value="B - Not Electric">
                </div>
            </div>

            <h4>Tier Usage Breakdown (таблица)</h4>
            <div class="grid-container">
                <div class="form-group">
                    <label>Tier 1 Allowance:</label>
                    <input type="text" name="tier1_allowance_detail" value="297.00 kWh (30 days x 9.9 kWh/day)">
                </div>
                <div class="form-group">
                    <label>Tier 1 Usage Amount ($):</label>
                    <input type="text" name="tier1_usage_amount" value="66.46">
                </div>
                <div class="form-group">
                    <label>Tier 2 Usage Amount ($):</label>
                    <input type="text" name="tier2_usage_amount" value="23.37">
                </div>
                <div class="form-group">
                    <label>Generation Credit ($):</label>
                    <input type="text" name="generation_credit" value="-44.68">
                </div>
                <div class="form-group">
                    <label>PCIA ($):</label>
                    <input type="text" name="pcia_adjustment" value="10.26">
                </div>
                <div class="form-group">
                    <label>Franchise Fee Surcharge ($):</label>
                    <input type="text" name="franchise_fee_surcharge" value="0.25">
                </div>
            </div>

            <h4>Диаграмма "Electric Usage This Period"</h4>
            <div class="form-group full-width">
                <label>Заголовок диаграммы (заменит 'Electric Usage This Period: ...'):</label>
                <input type="text" name="electric_usage_period_title" value="Electric Usage This Period: 380.000000 kWh, 30 billing days">
            </div>
            <div class="form-group full-width">
                <label>Данные для диаграммы (JSON - массив объектов):</label>
                <textarea name="daily_electric_usage_history" rows="5">[
                    {"day": "7/2", "kwh": 12}, {"day": "7/3", "kwh": 11}, {"day": "7/4", "kwh": 13}, 
                    {"day": "7/5", "kwh": 15}, {"day": "7/6", "kwh": 14}, {"day": "7/7", "kwh": 12}, 
                    {"day": "7/8", "kwh": 11}, {"day": "7/9", "kwh": 10}, {"day": "7/10", "kwh": 14}, 
                    {"day": "7/11", "kwh": 18}, {"day": "7/12", "kwh": 17}, {"day": "7/13", "kwh": 16}, 
                    {"day": "7/14", "kwh": 20}, {"day": "7/15", "kwh": 19}, {"day": "7/16", "kwh": 18}, 
                    {"day": "7/17", "kwh": 16}, {"day": "7/18", "kwh": 15}, {"day": "7/19", "kwh": 14}, 
                    {"day": "7/20", "kwh": 14}, {"day": "7/21", "kwh": 18}, {"day": "7/22", "kwh": 20}, 
                    {"day": "7/23", "kwh": 22}, {"day": "7/24", "kwh": 21}, {"day": "7/25", "kwh": 20}, 
                    {"day": "7/26", "kwh": 19}, {"day": "7/27", "kwh": 18}, {"day": "7/28", "kwh": 17}, 
                    {"day": "7/29", "kwh": 17}, {"day": "7/30", "kwh": 16}, {"day": "7/31", "kwh": 15}
                ]</textarea>
            </div>
            <div class="form-group">
                <label>Average Daily Usage (для линии на графике):</label>
                <input type="text" name="average_daily_usage" value="12.67">
            </div>  

            <!-- Вставьте этот блок в ваш pge_form.html -->

            <h3>Детализация со страницы 4 (Silicon Valley Clean Energy)</h3>
            <div class="grid-container">
                <div class="form-group">
                    <label>Rate Schedule (напр. 'E-1'):</label>
                    <input type="text" name="svce_rate_schedule" value="E-1">
                </div>
                <div class="form-group full-width">
                    <label>Generation - Total (детали):</label>
                    <input type="text" name="svce_generation_detail" value="380.000000 kWh @ $0.08519">
                </div>
                <div class="form-group">
                    <label>Generation - Total ($):</label>
                    <input type="text" name="svce_generation_amount" value="32.37">
                </div>
                <div class="form-group">
                    <label>Energy Commission Surcharge ($):</label>
                    <input type="text" name="svce_energy_surcharge" value="0.11">
                </div>
                <div class="form-group full-width">
                    <label>Total SVCE Charges ($):</label>
                    <input type="text" name="svce_total_charges" value="32.48">
                </div>
            </div>     

            <!-- Вставьте этот блок в ваш pge_form.html -->

            <h3>Детализация со страницы 5 (Gas Charges)</h3>

            <h4>Информация о периоде и тарифе (газ)</h4>
            <div class="grid-container">
                <div class="form-group full-width">
                    <label>Период Gas Charges:</label>
                    <input type="text" name="gas_charges_period" value="08/02/2019 - 08/31/2019 (30 billing days)">
                </div>
                <div class="form-group">
                    <label>Service Agreement ID (газ):</label>
                    <input type="text" name="gas_service_agreement_id" value="1111111111">
                </div>
                <div class="form-group">
                    <label>Rate Schedule (газ):</label>
                    <input type="text" name="gas_rate_schedule" value="G1 X Residential Service">
                </div>
            </div>

            <h4>Service Information (газ, правая колонка)</h4>
            <div class="grid-container grid-3-col">
                <div class="form-group">
                    <label>Meter #:</label>
                    <input type="text" name="gas_meter_number" value="11111111">
                </div>
                <div class="form-group">
                    <label>Current Reading:</label>
                    <input type="text" name="gas_current_reading" value="2,588">
                </div>
                <div class="form-group">
                    <label>Prior Reading:</label>
                    <input type="text" name="gas_prior_reading" value="2,583">
                </div>
                <div class="form-group">
                    <label>Difference:</label>
                    <input type="text" name="gas_difference" value="5">
                </div>
                <div class="form-group">
                    <label>Multiplier:</label>
                    <input type="text" name="gas_multiplier" value="1.031647">
                </div>
                <div class="form-group">
                    <label>Total Usage (Therms):</label>
                    <input type="text" name="gas_total_usage" value="5.000000 Therms">
                </div>
                <div class="form-group">
                    <label>Baseline Territory:</label>
                    <input type="text" name="gas_baseline_territory" value="X">
                </div>
                <div class="form-group">
                    <label>Serial:</label>
                    <input type="text" name="gas_serial" value="G">
                </div>
            </div>

            <h4>Tier Usage Breakdown (газ, таблица)</h4>
            <div class="grid-container">
                <div class="form-group full-width">
                    <label>Tier 1 Allowance Detail:</label>
                    <input type="text" name="gas_tier1_allowance_detail" value="17.70 Therms (30 days x 0.59 Therms/day)">
                </div>
                <div class="form-group">
                    <label>Tier 1 Usage Detail:</label>
                    <input type="text" name="gas_tier1_usage_detail" value="5.000000 Therms @ $1.28395">
                </div>
                <div class="form-group">
                    <label>Tier 1 Usage Amount ($):</label>
                    <input type="text" name="gas_tier1_usage_amount" value="6.42">
                </div>
                <div class="form-group">
                    <label>Gas PPP Surcharge Detail:</label>
                    <input type="text" name="gas_ppp_surcharge_detail" value="($0.09047 /Therm)">
                </div>
                <div class="form-group">
                    <label>Gas PPP Surcharge Amount ($):</label>
                    <input type="text" name="gas_ppp_surcharge_amount" value="0.45">
                </div>
                <div class="form-group">
                    <label>Total Gas Charges ($):</label>
                    <input type="text" name="gas_total_charges" value="6.87">
                </div>
            </div>

            <h4>Gas Procurement Costs (правая колонка)</h4>
            <div class="grid-container">
                <div class="form-group">
                    <label>Период:</label>
                    <input type="text" name="gas_procurement_period" value="07/02/2019 - 07/31/2019">
                </div>
                <div class="form-group">
                    <label>Стоимость ($/Therm):</label>
                    <input type="text" name="gas_procurement_amount" value="0.28462">
                </div>
            </div>


            <h4>Диаграмма "Gas Usage This Period"</h4>
            <div class="form-group full-width">
                <label>Заголовок диаграммы:</label>
                <input type="text" name="gas_usage_period_title" value="Gas Usage This Period: 5.000000 Therms, 30 billing days">
            </div>
            <div class="form-group">
                <label>Average Daily Usage (для линии):</label>
                <input type="text" name="gas_average_daily_usage" value="0.17">
            </div>
            <div class="form-group full-width">
                <label>Данные для диаграммы (JSON - массив объектов, kwh используется как 'value'):</label>
                <textarea name="daily_gas_usage_history" rows="10">[
                    {"day": "7/2", "gas": 0},
                    {"day": "7/3", "gas": 0},
                    {"day": "7/4", "gas": 0},
                    {"day": "7/5", "gas": 0},
                    {"day": "7/6", "gas": 0},
                    {"day": "7/7", "gas": 0},
                    {"day": "7/8", "gas": 0},
                    {"day": "7/9", "gas": 0.9},
                    {"day": "7/10", "gas": 0},
                    {"day": "7/11", "gas": 0},
                    {"day": "7/12", "gas": 0},
                    {"day": "7/13", "gas": 0},
                    {"day": "7/14", "gas": 1},
                    {"day": "7/15", "gas": 0},
                    {"day": "7/16", "gas": 0},
                    {"day": "7/17", "gas": 0},
                    {"day": "7/18", "gas": 0.9},
                    {"day": "7/19", "gas": 0},
                    {"day": "7/20", "gas": 0},
                    {"day": "7/21", "gas": 0},
                    {"day": "7/22", "gas": 0},
                    {"day": "7/23", "gas": 1},
                    {"day": "7/24", "gas": 0},
                    {"day": "7/25", "gas": 0},
                    {"day": "7/26", "gas": 0},
                    {"day": "7/27", "gas": 1},
                    {"day": "7/28", "gas": 0},
                    {"day": "7/29", "gas": 0},
                    {"day": "7/30", "gas": 0},
                    {"day": "7/31", "gas": 0}
                ]</textarea>
            </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';

            // Специальная обработка для вложенных объектов и JSON
            const formData = new FormData(event.target);
            let data = {};
            for (let [key, value] of formData.entries()) {
                if (key.includes('[')) { // Обработка полей типа name="daily_usage_electric[year_ago]"
                    const keys = key.replace(/\]/g, '').split('[');
                    let current = data;
                    for(let i = 0; i < keys.length; i++) {
                        if (i === keys.length - 1) {
                            current[keys[i]] = value;
                        } else {
                            current[keys[i]] = current[keys[i]] || {};
                            current = current[keys[i]];
                        }
                    }
                } else {
                    data[key] = value;
                }
            }

            try {
                data.monthly_billing_history = JSON.parse(data.monthly_billing_history);
            } catch (e) {
                statusDiv.textContent = 'Ошибка в JSON для Monthly Billing History!';
                statusDiv.style.color = 'red';
                return;
            }

            const apiUrl = '/pdfgen/api/v1/PGE'; // <--- API ЭНДПОИНТ ДЛЯ PG&E
            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_pge.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>