// pdfFillDataVerizon.js
const fs = require('fs');
const path = require('path');
const pdfFillData = require('./pdfFillData'); // Родительский класс
const randomData = require('./randomDataGenerator');

class pdfFillDataVerizon extends pdfFillData {
    constructor() {
        super('Verizon');
        this.baselineCorrectionFactor = 0.85;

        this.fontMap = {
            'Helvetica': 0,
            'Arial-BoldMT': 1,
            'ArialMT': 2,
            'C0EX00U0_T1EX0000_0': 3, // Monospace/OCR
            'Kalypso': 4 // Placeholder
            // Примечание: реальные имена шрифтов из PDF могут быть 'C0GTBD12...' и т.д.
            // Их нужно будет сопоставить с вашими файлами.
        };

        // --- Основные данные из формы ---
        this.customer_name = '';
        this.customer_address = '';
        this.customer_city_st_zip = '';
        this.account_number = '';
        this.invoice_number = '';
        this.total_due_date = '';
        this.full_due_date = '';
        this.barcode_number = '';

        // --- Поля для детализации из формы ---
        this.activation_fee = 0;
        this.plan_ultimate = 0;
        this.perk_apple_one = 0;
        this.surcharge_fus = 0;
        this.surcharge_regulatory = 0;
        this.surcharge_admin = 0;
        this.tax_911 = 0;
        this.tax_ga_state = 0;
        this.tax_fulton_county = 0;

        // --- Расчетные и форматируемые поля ---
        this.balance_from_last_bill = '';
        this.total_amount_due = '';
        this.total_due_text = '';
        this.remit_total_due_text = '';
        this.surcharges_total = '';
        this.taxes_total = '';
        this.current_month_energy_charges = '';

        this.bill_month = '';
        this.payment_received = '';
        this.page3_header_text = '';
        this.page3_due_date_text = '';
        this.page3_payment_text = '';
    }

    _cleanAmount(amount) {
        if (typeof amount !== 'string') return 0;
        return parseFloat(amount.replace(/[^0-9.-]+/g, '')) || 0;
    }

    async setFields(fields) {
        if (!fields || Object.keys(fields).length === 0) {
            fields = randomData.verizon(); // <-- Замените на entergy(), aep_ohio() и т.д.
        }
        this.customer_name = fields.customer_name;
        this.customer_address = fields.customer_address;
        this.customer_city_st_zip = fields.customer_city_st_zip;
        this.account_number = fields.account_number;
        this.invoice_number = fields.invoice_number;
        this.total_due_date = fields.total_due_date;
        this.barcode_number = fields.barcode_number;
        
        // Принимаем числовые значения из формы
        this.activation_fee = this._cleanAmount(fields.activation_fee);
        this.plan_ultimate = this._cleanAmount(fields.plan_ultimate);
        this.perk_apple_one = this._cleanAmount(fields.perk_apple_one);
        this.surcharge_fus = this._cleanAmount(fields.surcharge_fus);
        this.surcharge_regulatory = this._cleanAmount(fields.surcharge_regulatory);
        this.surcharge_admin = this._cleanAmount(fields.surcharge_admin);
        this.tax_911 = this._cleanAmount(fields.tax_911);
        this.tax_ga_state = this._cleanAmount(fields.tax_ga_state);
        this.tax_fulton_county = this._cleanAmount(fields.tax_fulton_county);

        // Выполняем расчеты
        this.surcharges_total = this.surcharge_fus + this.surcharge_regulatory + this.surcharge_admin;
        this.taxes_total = this.tax_911 + this.tax_ga_state + this.tax_fulton_county;
        const totalAmountNum = this.activation_fee + this.plan_ultimate + this.perk_apple_one + this.surcharges_total + this.taxes_total;

        // --- Готовим форматированные строки для replacements ---
        this.balance_from_last_bill = '$0.00';
        this.total_amount_due = `$${totalAmountNum.toFixed(2)}`;
        this.total_due_text = `Total due on ${this.total_due_date}`;
        
        // Форматируем дату для купона (e.g., February 12, 2024)
        const dateObj = new Date(this.total_due_date);
        const longDate = !isNaN(dateObj.getTime()) ? dateObj.toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' }) : this.total_due_date;
        this.remit_total_due_text = `Total Amount Due by ${longDate}`;
        
        // Форматируем все денежные значения в строки со знаком $
        this.activation_fee = `$${this.activation_fee.toFixed(2)}`;
        this.plan_ultimate = `$${this.plan_ultimate.toFixed(2)}`;
        this.perk_apple_one = `$${this.perk_apple_one.toFixed(2)}`;
        this.surcharges_total = `$${this.surcharges_total.toFixed(2)}`;
        this.surcharge_fus = `$${this.surcharge_fus.toFixed(2)}`;
        this.surcharge_regulatory = `$${this.surcharge_regulatory.toFixed(2)}`;
        this.surcharge_admin = `$${this.surcharge_admin.toFixed(2)}`;
        this.taxes_total = `$${this.taxes_total.toFixed(2)}`;
        this.tax_911 = `$${this.tax_911.toFixed(2)}`;
        this.tax_ga_state = `$${this.tax_ga_state.toFixed(2)}`;
        this.tax_fulton_county = `$${this.tax_fulton_county.toFixed(2)}`;

        // --- ДАННЫЕ И ФОРМАТИРОВАНИЕ ДЛЯ СТР. 3 ---
        this.bill_month = fields.bill_month;
        this.payment_received = fields.payment_received; // Берем значение напрямую

        // Собираем комбинированные строки
        this.page3_header_text = `Your ${this.bill_month} bill is ${this.total_amount_due}`;
        this.page3_due_date_text = `Due ${this.total_due_date}`;
        this.page3_payment_text = `You paid ${this.payment_received}.`;
    }

    async draw() {
        const mapFilePath = path.join(__dirname, 'Verizon.map.json');
        const config = JSON.parse(fs.readFileSync(mapFilePath, 'utf8'));
        const { constants, replacements, map: dataMap } = config;

        for (const item of dataMap) {
            const page = this.getPageByIndex(item.ipage);
            const font = this.getCustomerFontByIndex(item.ifont);
            if (!page || !font) continue;

            const pageHeight = this.getPageHeight(item.ipage);
            
            let fieldText = replacements.hasOwnProperty(item.field)
                ? this[replacements[item.field]] || item.field
                : item.field;
            
            fieldText = `${fieldText || ''}`;
            // --- 2. Вычисляем базовые параметры ---
            const x_ill = this._evaluate(item.x_ill, constants);
            const y_ill = this._evaluate(item.y_ill, constants);
            const size = this._evaluate(item.size, constants);
            
            const y_pdf = pageHeight - y_ill - (size * this.baselineCorrectionFactor);
            let x_pdf = x_ill; // X по умолчанию (для align: 'left')

            // --- 3. НОВАЯ, УМНАЯ ЛОГИКА ВЫРАВНИВАНИЯ (ВАШ ПОДХОД) ---
            if (item.align) {

                if (item.align === 'right') {
                    const pageWidth = this.getPageWidth(item.ipage);
                    const rightMargin_pdf = pageWidth - x_ill;
                    x_pdf = await this.alignTextToRight(item.ipage, item.ifont, size, rightMargin_pdf, fieldText);
                } else if (item.align === 'center') {
                    // НОВЫЙ БЛОК: ВЫРАВНИВАНИЕ ПО ЦЕНТРУ
                    const textWidth = font.widthOfTextAtSize(fieldText, size);
                    x_pdf = x_ill - (textWidth / 2);

                }else {
                    x_pdf = x_ill;
                }

            }
            
            // --- 4. Отрисовка ---
            await super.draw(item.ipage, fieldText, x_pdf, y_pdf, size, item.ifont, 0, 0, 0); // Y координата в drawText использует y_ill, а не y_pdf.
        }
    }
}

module.exports = pdfFillDataVerizon;