<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generate Duke Energy 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: #005eb8; } /* Duke Energy Blue */
        .form-group { margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; font-weight: bold; }
        input[type="text"], input[type="date"], 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: #0072ce; /* Another Duke Energy Blue */
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }
        button:hover { background-color: #005eb8; }
        #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; }
        h2 { margin-top: 30px; border-bottom: 1px solid #eee; padding-bottom: 5px; color: #333; }
    </style>
</head>
<body>

    <div class="container">
        <h1>Generate Duke Energy PDF</h1>

        <form id="pdfForm">
            <h2>General Information</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="MR OSCAR GUARIN" required>
                </div>
                <div class="form-group">
                    <label for="account_number">Account Number:</label>
                    <input type="text" id="account_number" name="account_number" value="9100 9029 1504" required>
                </div>
                <div class="form-group">
                    <label for="bill_date">Bill Date (e.g., Jul 25, 2022):</label>
                    <input type="text" id="bill_date" name="bill_date" value="Jul 25, 2022" placeholder="Mon DD, YYYY" required>
                </div>
                 <div class="form-group">
                    <label for="total_amount_due_date">Total Amount Due Date (e.g., Aug 19):</label>
                    <input type="text" id="total_amount_due_date" name="total_amount_due_date" value="Aug 19" placeholder="Mon DD" required>
                </div>
            </div>

            <h2>Service Address</h2>
            <div class="grid-container">
                <div class="form-group full-width">
                    <label for="service_address_line1">Service Address Line 1:</label>
                    <input type="text" id="service_address_line1" name="service_address_line1" value="5021 CELBRIDGE PL" required>
                </div>
                <div class="form-group full-width">
                    <label for="service_address_line2">Service Address Line 2 (City ST ZIP):</label>
                    <input type="text" id="service_address_line2" name="service_address_line2" value="RALEIGH NC 27613" required>
                </div>
            </div>

             <h2>Service Period</h2>
            <div class="grid-container">
                <div class="form-group">
                    <label for="service_period_from">Service From (e.g., Jun 22):</label>
                    <input type="text" id="service_period_from" name="service_period_from" value="Jun 22" placeholder="Mon DD" required>
                </div>
                <div class="form-group">
                    <label for="service_period_to">Service To (e.g., Jul 21):</label>
                    <input type="text" id="service_period_to" name="service_period_to" value="Jul 21" placeholder="Mon DD" required>
                </div>
            </div>

            <h2>Billing Summary</h2>
            <div class="grid-container">
                <div class="form-group">
                    <label for="previous_amount_due">Previous Amount Due ($):</label>
                    <input type="text" id="previous_amount_due" name="previous_amount_due" value="$195.28" required>
                </div>
                 <div class="form-group">
                    <label for="payment_received_date">Payment Received Date (e.g., Jul 22):</label>
                    <input type="text" id="payment_received_date" name="payment_received_date" value="Jul 22" placeholder="Mon DD" required>
                </div>
                <div class="form-group">
                    <label for="payment_received_amount">Payment Received Amount ($):</label>
                    <input type="text" id="payment_received_amount" name="payment_received_amount" value="-195.28" required>
                </div>
                <div class="form-group">
                    <label for="current_electric_charges">Current Electric Charges ($):</label>
                    <input type="text" id="current_electric_charges" name="current_electric_charges" value="287.05" required>
                </div>
                <div class="form-group">
                    <label for="current_lighting_charges">Current Lighting Charges ($):</label>
                    <input type="text" id="current_lighting_charges" name="current_lighting_charges" value="3.27">
                </div>
                <div class="form-group">
                    <label for="taxes">Taxes ($):</label>
                    <input type="text" id="taxes" name="taxes" value="20.32" required>
                </div>
                <div class="form-group full-width">
                    <label for="total_amount_due_value">Total Amount Due ($):</label>
                    <input type="text" id="total_amount_due_value" name="total_amount_due_value" value="$310.64" required>
                </div>
            </div>

            <h2>Usage Snapshot</h2>
            <div class="grid-container">
                <div class="form-group">
                    <label for="electric_usage_current_month_kwh">Current Month kWh:</label>
                    <input type="text" id="electric_usage_current_month_kwh" name="electric_usage_current_month_kwh" value="2,427">
                </div>
                <div class="form-group">
                    <label for="electric_usage_jul_2021_kwh">Jul 2021 kWh (Example):</label>
                    <input type="text" id="electric_usage_jul_2021_kwh" name="electric_usage_jul_2021_kwh" value="0">
                </div>
                 <div class="form-group">
                    <label for="electric_usage_12_month_avg_kwh">12-Month Avg kWh:</label>
                    <input type="text" id="electric_usage_12_month_avg_kwh" name="electric_usage_12_month_avg_kwh" value="1,182">
                </div>
            </div>

            <h2>Remittance Slip Details</h2>
             <div class="grid-container">
                <div class="form-group full-width">
                    <label for="remit_address_line2">Remittance Address Line 2 (City ST ZIP-Ext):</label>
                    <input type="text" id="remit_address_line2" name="remit_address_line2" value="RALEIGH NC 27613-6206">
                </div>
                <div class="form-group full-width">
                    <label for="barcode_number">Barcode Number (Bottom):</label>
                    <input type="text" id="barcode_number" name="barcode_number" value="8891009029150400055000000003106400000310649">
                </div>
            </div>

<!--             <h2>Page 3 Details (Simplified)</h2>
            <div class="grid-container">
                <div class="form-group">
                    <label for="meter_number">Meter Number:</label>
                    <input type="text" id="meter_number" name="meter_number" value="336269538">
                </div>
                <div class="form-group">
                    <label for="energy_used_kwh">Energy Used (e.g., 2,381 kWh):</label>
                    <input type="text" id="energy_used_kwh" name="energy_used_kwh" value="2,381 kWh">
                </div>
                <div class="form-group">
                    <label for="basic_customer_charge">Basic Customer Charge ($):</label>
                    <input type="text" id="basic_customer_charge" name="basic_customer_charge" value="$14.00">
                </div>
                <div class="form-group">
                    <label for="energy_charge_details">Energy Charge Details (e.g., kWh @ rate):</label>
                    <input type="text" id="energy_charge_details" name="energy_charge_details" value="2,381.000 kWh @ $0.11160000">
                </div>
                <div class="form-group">
                    <label for="energy_charge_amount">Energy Charge Amount ($):</label>
                    <input type="text" id="energy_charge_amount" name="energy_charge_amount" value="265.72">
                </div>
                <div class="form-group">
                    <label for="total_taxes_detail">Total Taxes Detail (e.g., Sales Tax For Utility):</label>
                    <input type="text" id="total_taxes_detail" name="total_taxes_detail" value="Sales Tax For Utility">
                </div>
                <div class="form-group">
                    <label for="total_taxes_amount">Total Taxes Amount ($):</label>
                    <input type="text" id="total_taxes_amount" name="total_taxes_amount" value="$20.32">
                </div>
            </div> -->

            <button type="submit">Generate and Download Duke Energy PDF</button>
        </form>

        <div id="status"></div>
        <!-- Скрытая ссылка для скачивания -->
        <a id="downloadLink" style="display: none;"></a>
    </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;
            });

            const apiUrl = '/pdfgen/api/v1/DukeEnergy'; // Убедитесь, что этот URL правильный
            const bearerToken = "43QAwPldLuuQTErY303m16lY5dSeDUy1OVKBzy5HTDG2KxfVC0m1o1cfZ49gbBRu"; // Ваш Bearer токен

            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}`;
                    try {
                        const errorJson = await response.json();
                        errorText += ` - ${errorJson.error || JSON.stringify(errorJson)}`;
                    } catch (e) {
                        const textError = await response.text();
                        if (textError) errorText += ` - ${textError}`;
                    }
                    throw new Error(errorText);
                }

                const contentDisposition = response.headers.get('content-disposition');
                let filename = "generated_duke_energy.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);

                // Динамически создаем элемент <a>
                const a = document.createElement('a');
                a.style.display = 'none'; // Делаем его невидимым
                a.href = downloadUrl;
                a.download = filename;

                document.body.appendChild(a); // Добавляем на страницу, чтобы можно было симулировать клик
                a.click(); // Симулируем клик

                // Удаляем созданный элемент и освобождаем URL
                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>