const fs = require('fs');

try {
    // 1. UPDATE index.html
    let indexHtml = fs.readFileSync('index.html', 'utf8');
    
    const prefixes = ['sales', 'purchases', 'sales-returns', 'purchases-returns'];
    
    // Replace inputs
    prefixes.forEach(prefix => {
        const oldInput = `<div class="flex-col"><label>الخصم (قيمة)</label><input type="number" id="${prefix}-discount" min="0" value="0"></div>`;
        const newInput = `<div class="flex-col" style="flex:1">
            <label>الخصم</label>
            <div style="display:flex; gap:5px;">
              <input type="number" id="${prefix}-discount" min="0" value="0" style="width:70%;">
              <select id="${prefix}-discount-type" style="width:30%; padding: 5px;">
                <option value="value">قيمة</option>
                <option value="percent">%</option>
              </select>
            </div>
          </div>`;
        // Since we don't know exact spacing, let's use regex
        const regexInput = new RegExp(`<div class="flex-col">\\s*<label>الخصم \\(قيمة\\)<\\/label>\\s*<input type="number" id="${prefix}-discount" min="0" value="0">\\s*<\\/div>`, 'g');
        indexHtml = indexHtml.replace(regexInput, newInput);
        // Fallback exact replace without flex-col if needed
        const regexInput2 = new RegExp(`<label>الخصم \\(قيمة\\)<\\/label>\\s*<input type="number" id="${prefix}-discount" min="0" value="0">`, 'g');
        indexHtml = indexHtml.replace(regexInput2, `<label>الخصم</label><div style="display:flex; gap:5px;"><input type="number" id="${prefix}-discount" min="0" value="0" style="width:70%;"><select id="${prefix}-discount-type" style="width:30%; padding: 5px;"><option value="value">قيمة</option><option value="percent">%</option></select></div>`);
    });

    // Replace table headers
    indexHtml = indexHtml.replace(/<th>وصف الصنف<\/th>/g, '<th>الخصم</th>');
    
    indexHtml = indexHtml.replace(/v=\d+/g, 'v=' + Date.now());
    fs.writeFileSync('index.html', indexHtml, 'utf8');
    
    // 2. UPDATE app_final.js
    let appFinalJs = fs.readFileSync('app_final.js', 'utf8');
    
    // addSalesLine
    appFinalJs = appFinalJs.replace(
        /const discount = parseFloat\(document\.getElementById\('sales-discount'\)\.value\) \|\| 0;/g,
        `const discount = parseFloat(document.getElementById('sales-discount').value) || 0;\n  const discountType = document.getElementById('sales-discount-type').value || 'value';`
    );
    appFinalJs = appFinalJs.replace(
        /currentSalesLines\.push\({ item_id: itemId, qty, price, discount }\);/g,
        `currentSalesLines.push({ item_id: itemId, qty, price, discount, discountType });`
    );
    appFinalJs = appFinalJs.replace(
        /document\.getElementById\('sales-discount'\)\.value = 0;/g,
        `document.getElementById('sales-discount').value = 0;\n  if(document.getElementById('sales-discount-type')) document.getElementById('sales-discount-type').value = 'value';`
    );
    
    // renderSalesLines
    appFinalJs = appFinalJs.replace(
        /const lineDiscountValue = parseFloat\(line\.discount\) \|\| 0;/g,
        `let lineDiscountValue = parseFloat(line.discount) || 0;\n    if (line.discountType === 'percent') { lineDiscountValue = lineTotalBeforeDiscount * (lineDiscountValue / 100); }`
    );
    appFinalJs = appFinalJs.replace(
        /<td>\$\{\(parseFloat\(line\.discount\) \|\| 0\)\.toLocaleString\('en-US'\)\}<\/td>/g,
        `<td>\${line.discountType === 'percent' ? line.discount + '%' : (parseFloat(line.discount) || 0).toLocaleString('en-US')}</td>`
    );
    
    // addPurchasesLine
    appFinalJs = appFinalJs.replace(
        /const discount = parseFloat\(document\.getElementById\('purchases-discount'\)\.value\) \|\| 0;/g,
        `const discount = parseFloat(document.getElementById('purchases-discount').value) || 0;\n  const discountType = document.getElementById('purchases-discount-type').value || 'value';`
    );
    appFinalJs = appFinalJs.replace(
        /currentPurchasesLines\.push\({ item_id: itemId, qty, price, discount }\);/g,
        `currentPurchasesLines.push({ item_id: itemId, qty, price, discount, discountType });`
    );
    appFinalJs = appFinalJs.replace(
        /document\.getElementById\('purchases-discount'\)\.value = 0;/g,
        `document.getElementById('purchases-discount').value = 0;\n  if(document.getElementById('purchases-discount-type')) document.getElementById('purchases-discount-type').value = 'value';`
    );

    // renderPurchasesLines (already replaced by generic regex if it matches exactly, wait, let's just make sure)
    appFinalJs = appFinalJs.replace(
        /let lineDiscountValue = parseFloat\(line\.discount\) \|\| 0;/g, // just in case it was modified before
        `let lineDiscountValue = parseFloat(line.discount) || 0;\n    if (line.discountType === 'percent') { lineDiscountValue = lineTotalBeforeDiscount * (lineDiscountValue / 100); }`
    );

    fs.writeFileSync('app_final.js', appFinalJs, 'utf8');
    
    // 3. UPDATE vouchers_returns.js
    if (fs.existsSync('vouchers_returns.js')) {
        let vrJs = fs.readFileSync('vouchers_returns.js', 'utf8');
        
        // addSalesReturnsLine
        vrJs = vrJs.replace(
            /const discount = parseFloat\(document\.getElementById\('sales-returns-discount'\)\.value\) \|\| 0;/g,
            `const discount = parseFloat(document.getElementById('sales-returns-discount').value) || 0;\n  const discountType = document.getElementById('sales-returns-discount-type').value || 'value';`
        );
        vrJs = vrJs.replace(
            /currentSalesReturnLines\.push\({ item_id: itemId, qty, price, discount }\);/g,
            `currentSalesReturnLines.push({ item_id: itemId, qty, price, discount, discountType });`
        );
        vrJs = vrJs.replace(
            /document\.getElementById\('sales-returns-discount'\)\.value = 0;/g,
            `document.getElementById('sales-returns-discount').value = 0;\n  if(document.getElementById('sales-returns-discount-type')) document.getElementById('sales-returns-discount-type').value = 'value';`
        );
        
        // renderSalesReturnsLines
        vrJs = vrJs.replace(
            /const lineDiscountValue = parseFloat\(line\.discount\) \|\| 0;/g,
            `let lineDiscountValue = parseFloat(line.discount) || 0;\n    if (line.discountType === 'percent') { lineDiscountValue = lineTotalBeforeDiscount * (lineDiscountValue / 100); }`
        );
        vrJs = vrJs.replace(
            /<td>\$\{\(parseFloat\(line\.discount\) \|\| 0\)\.toLocaleString\('en-US'\)\}<\/td>/g,
            `<td>\${line.discountType === 'percent' ? line.discount + '%' : (parseFloat(line.discount) || 0).toLocaleString('en-US')}</td>`
        );
        
        // addPurchasesReturnsLine
        vrJs = vrJs.replace(
            /const discount = parseFloat\(document\.getElementById\('purchases-returns-discount'\)\.value\) \|\| 0;/g,
            `const discount = parseFloat(document.getElementById('purchases-returns-discount').value) || 0;\n  const discountType = document.getElementById('purchases-returns-discount-type').value || 'value';`
        );
        vrJs = vrJs.replace(
            /currentPurchasesReturnLines\.push\({ item_id: itemId, qty, price, discount }\);/g,
            `currentPurchasesReturnLines.push({ item_id: itemId, qty, price, discount, discountType });`
        );
        vrJs = vrJs.replace(
            /document\.getElementById\('purchases-returns-discount'\)\.value = 0;/g,
            `document.getElementById('purchases-returns-discount').value = 0;\n  if(document.getElementById('purchases-returns-discount-type')) document.getElementById('purchases-returns-discount-type').value = 'value';`
        );
        
        fs.writeFileSync('vouchers_returns.js', vrJs, 'utf8');
    }

    console.log('Discount patch applied successfully!');
} catch (err) {
    console.error('Error applying patch:', err);
}
