const fs = require('fs');
const file = 'c:/Users/kde/Desktop/wassili_V2/public_html/js/admin-dashboard.js';
let content = fs.readFileSync(file, 'utf8');

// Ensure escapeHtml exists globally here or we rely on index.html / config.js
// We will just inject it into the fields.

const replacements = [
    {
        find: "const clientName = order.client?.name || order.customer?.name || 'غير معروف';",
        replace: "const clientName = window.escapeHtml(order.client?.name || order.customer?.name || 'غير معروف');"
    },
    {
        find: "const captainName = order.captain?.name || '---';",
        replace: "const captainName = window.escapeHtml(order.captain?.name || '---');"
    },
    {
        find: "const pickup = order.pickup?.address || order.pickupLocation || 'غير محدد';",
        replace: "const pickup = window.escapeHtml(order.pickup?.address || order.pickupLocation || 'غير محدد');"
    },
    {
        find: "const dropoff = order.dropoff?.address || order.dropoffLocation || 'غير محدد';",
        replace: "const dropoff = window.escapeHtml(order.dropoff?.address || order.dropoffLocation || 'غير محدد');"
    },
    {
        find: "user.name, user.phone || user.email || '---',",
        replace: "window.escapeHtml(user.name || ''), window.escapeHtml(user.phone || user.email || '---'),"
    },
    {
        find: "<div class=\"captain-avatar\">${c.name ? c.name.charAt(0) : '?'}</div>\\n                <div class=\"captain-info\">\\n                    <h4>${c.name}</h4>\\n                    <p><i class=\"fas fa-phone\"></i> ${c.phone || c.email || '---'}</p>\\n                    <p><i class=\"fas fa-motorcycle\"></i> ${c.vehicleType || 'غير محدد'}</p>",
        replace: "<div class=\"captain-avatar\">${window.escapeHtml(c.name ? c.name.charAt(0) : '?')}</div>\\n                <div class=\"captain-info\">\\n                    <h4>${window.escapeHtml(c.name)}</h4>\\n                    <p><i class=\"fas fa-phone\"></i> ${window.escapeHtml(c.phone || c.email || '---')}</p>\\n                    <p><i class=\"fas fa-motorcycle\"></i> ${window.escapeHtml(c.vehicleType || 'غير محدد')}</p>"
    }
];

let replacedCount = 0;
for (const r of replacements) {
    let fnd = r.find.replace(/\\n/g, '\n');
    let rpl = r.replace.replace(/\\n/g, '\n');
    if (content.includes(fnd)) {
        content = content.replace(fnd, rpl);
        replacedCount++;
    } else {
        console.log("NOT FOUND:", fnd);
    }
}

fs.writeFileSync(file, content);
console.log(`Fixed admin-dashboard.js successfully. (${replacedCount} replacements)`);
