<?php
if (!defined('ABSPATH')) exit;

final class RFEC_Email_Renderer {
    public static function replace_placeholders($html, array $values) {
        $replace = [];
        foreach ($values as $key => $value) $replace['{'.$key.'}'] = esc_html((string)$value);
        return strtr(wpautop((string)$html), $replace);
    }

    public static function render(array $args) {
        $settings = $args['settings'];
        $lead = $args['lead'];
        $calc = $args['calculation'];
        $contractor = !empty($args['for_contractor']);
        $money = $args['money'];
        $values = [
            'contractor_name' => $settings['contractor_name'],
            'site_name' => get_bloginfo('name'),
            'lead_name' => $lead['name'],
            'estimate_range' => call_user_func($money, $calc['low']).' to '.call_user_func($money, $calc['high']),
            'booking_url' => $settings['booking_url'],
            'currency_code' => $settings['currency'],
        ];
        $rows = '';
        foreach ($calc['lines'] as $line) {
            $amount = isset($args['line_money']) ? call_user_func($args['line_money'], $line) : call_user_func($money, $line['amount']);
            $rows .= '<tr><td style="padding:10px 8px;border-bottom:1px solid #ddd;line-height:1.5">'.esc_html($line['label']).'</td><td style="padding:10px 8px;border-bottom:1px solid #ddd;text-align:right;line-height:1.5">'.esc_html($amount).'</td></tr>';
        }
        $contact = '<p><strong>'.esc_html($lead['name']).'</strong><br>'.esc_html($lead['email']).'<br>'.esc_html($lead['phone']).'<br>'.esc_html($lead['address']).'<br>'.esc_html($lead['city']).'<br>'.esc_html($lead['postal']).'</p>';
        $logo = '';
        if (!$contractor && !empty($settings['lead_email_show_logo']) && !empty($settings['lead_email_logo_id'])) {
            $logo_url = wp_get_attachment_image_url(absint($settings['lead_email_logo_id']), 'medium');
            if ($logo_url) $logo = '<p style="margin:0 0 24px"><img src="'.esc_url($logo_url).'" alt="'.esc_attr($settings['contractor_name']).'" style="display:block;height:auto;max-height:90px;max-width:260px;width:auto"></p>';
        }
        $intro = $contractor ? '' : self::replace_placeholders($settings['lead_email_intro'], $values);
        $schedule = '';
        if (!$contractor) {
            $schedule_content = self::replace_placeholders($settings['lead_email_schedule'], $values);
            if (!empty($settings['lead_email_show_schedule_button']) && $settings['booking_url']) {
                $schedule_content .= '<p style="display:block;margin:22px 0 0"><a href="'.esc_url($settings['booking_url']).'" style="display:inline-block;padding:12px 18px;background:#1d5dbf;color:#fff;text-decoration:none;border-radius:5px">Schedule a free on-site visit</a></p>';
            }
            $schedule = '<div style="clear:both;display:block;margin:24px 0 30px">'.$schedule_content.'</div>';
        }
        $signature = $contractor ? '' : '<div style="clear:both;display:block;margin:30px 0 0">'.self::replace_placeholders($settings['lead_email_signature'], $values).'</div>';
        $tax = empty($calc['tax_included']) ? '<p><em>'.esc_html($calc['tax_label'] ?? 'Applicable sales tax').' is not included in this estimate.</em></p>' : '';
        $extra = isset($args['extra_html']) ? (string)$args['extra_html'] : '';
        $footer = $contractor ? (string)$args['contractor_footer'] : '';
        $html = '<div style="box-sizing:border-box;font-family:Arial,sans-serif;max-width:700px;width:100%;margin:0 auto;color:#252a31;line-height:1.65">'.$logo.'<h2 style="line-height:1.25">'.esc_html($args['heading']).'</h2>'.$intro.$contact.$extra.'<table role="presentation" style="width:100%;border-collapse:collapse">'.$rows.'</table><h2 style="line-height:1.3">Estimated range: '.esc_html(call_user_func($money, $calc['low'])).' to '.esc_html(call_user_func($money, $calc['high'])).'</h2><p>Working midpoint: '.esc_html(call_user_func($money, $calc['total'])).'</p>'.$tax.'<p>This calculator provides a ballpark estimate only. It is not an official quote or offer to perform the work. Final pricing depends on an on-site review, measurements, local requirements, and the confirmed project scope. Homeowners may qualify for certain discounts.</p>'.$schedule.$signature.$footer.'</div>';
        return RFEC_Estimator_Core::regionalize($html, $settings);
    }
}
