const fs = require('fs');
let content = fs.readFileSync('index.html', 'utf8');

// Fix sales modal unit ID (in case it exists and was wrong)
content = content.replace(
    /<div class="flex-col"><label>الوحدة<\/label><select id="purchases-unit"/g,
    '<div class="flex-col"><label>الوحدة</label><select id="sales-unit"'
);

// Add purchases unit dropdown
if (!content.includes('<select id="purchases-unit"')) {
    content = content.replace(
        /<div class="flex-col" style="flex:2"><label>الصنف<\/label><select id="purchases-item"><\/select><\/div>/g,
        '<div class="flex-col" style="flex:2"><label>الصنف</label><select id="purchases-item" onchange="window.updatePurchasesUnitOptions && window.updatePurchasesUnitOptions()"></select></div>\n          <div class="flex-col"><label>الوحدة</label><select id="purchases-unit" style="min-width: 80px;"><option value="base">الأساسية</option></select></div>'
    );
}

// Add sales item onchange
if (content.includes('<select id="sales-item"></select>')) {
    content = content.replace(
        /<select id="sales-item"><\/select>/g,
        '<select id="sales-item" onchange="window.updateSalesUnitOptions && window.updateSalesUnitOptions()"></select>'
    );
}

// Add unit converter buttons to Headers
if (!content.includes('window.openUnitConverter()')) {
    content = content.replace(
        /<div class="header-actions"><h2>فواتير المشتريات<\/h2>/g,
        '<div class="header-actions"><h2>فواتير المشتريات</h2><button class="action-btn" style="background:#17a2b8; color:white; font-weight:bold; padding:8px 12px; border-radius:5px; border:none;" onclick="window.openUnitConverter()">محول الوحدات</button>'
    );

    content = content.replace(
        /<div class="header-actions"><h2>إدارة المخازن<\/h2>/g,
        '<div class="header-actions"><h2>إدارة المخازن</h2><button class="action-btn" style="background:#17a2b8; color:white; font-weight:bold; padding:8px 12px; border-radius:5px; border:none;" onclick="window.openUnitConverter()">محول الوحدات</button>'
    );
}

fs.writeFileSync('index.html', content, 'utf8');
console.log('Patched index.html for units and buttons');
