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

final class RFEC_Admin_UI {
    private $option;
    private $prefix;

    public function __construct($option, $prefix) {
        $this->option = (string)$option;
        $this->prefix = sanitize_key($prefix);
    }

    public function field_name($key) {
        if (preg_match('/^([a-z0-9_]+)\[([a-z0-9_]+)\]$/i', $key, $parts)) return $this->option.'['.$parts[1].']['.$parts[2].']';
        return $this->option.'['.$key.']';
    }

    public function text_row($label,$key,$value,$type='text',$help='') {
        $id=$this->prefix.'-'.$key;
        echo '<tr><th scope="row"><label for="'.esc_attr($id).'">'.esc_html($label).'</label></th><td><input class="regular-text" id="'.esc_attr($id).'" type="'.esc_attr($type).'" name="'.esc_attr($this->field_name($key)).'" value="'.esc_attr($value).'">';
        if($help) echo '<p class="description">'.esc_html($help).'</p>';
        echo '</td></tr>';
    }

    public function textarea_row($label,$key,$value,$help='') {
        $id=$this->prefix.'-'.$key;
        echo '<tr><th scope="row"><label for="'.esc_attr($id).'">'.esc_html($label).'</label></th><td><textarea class="large-text" rows="3" id="'.esc_attr($id).'" name="'.esc_attr($this->field_name($key)).'">'.esc_textarea($value).'</textarea>';
        if($help) echo '<p class="description">'.esc_html($help).'</p>';
        echo '</td></tr>';
    }

    private function compatible_number_step($value, $step) {
        if ((string)$step === 'any') return 'any';
        $numeric_step=(float)$step;
        if ($numeric_step<=0) $numeric_step=0.01;
        $numeric_value=(float)$value;
        $quotient=$numeric_value/$numeric_step;
        if (abs($quotient-round($quotient))<0.0000001) return (string)$step;
        $text=rtrim(rtrim(number_format($numeric_value,6,'.',''),'0'),'.');
        $places=strpos($text,'.')===false?0:strlen(substr(strrchr($text,'.'),1));
        return $places>0 ? number_format(pow(10,-min(6,$places)),min(6,$places),'.','') : '1';
    }

    public function number_row($label,$key,$value,$step='0.01',$min=0,$max=null) {
        $step=$this->compatible_number_step($value,$step);
        $bounds=$min===null?'':' min="'.esc_attr($min).'"';
        if($max!==null) $bounds.=' max="'.esc_attr($max).'"';
        echo '<tr><th scope="row">'.esc_html($label).'</th><td><input type="number"'.$bounds.' step="'.esc_attr($step).'" name="'.esc_attr($this->field_name($key)).'" value="'.esc_attr($value).'"></td></tr>';
    }

    public function select_row($label,$key,$value,$options,$help='') {
        echo '<tr><th scope="row">'.esc_html($label).'</th><td><select name="'.esc_attr($this->field_name($key)).'">';
        foreach($options as $option=>$text) echo '<option value="'.esc_attr($option).'" '.selected($value,$option,false).'>'.esc_html($text).'</option>';
        echo '</select>';
        if($help) echo '<p class="description">'.esc_html($help).'</p>';
        echo '</td></tr>';
    }

    public function color_row($label,$key,$value,$help='') {
        $id=$this->prefix.'-'.$key;
        echo '<tr><th scope="row"><label for="'.esc_attr($id).'">'.esc_html($label).'</label></th><td><div class="'.$this->prefix.'-colour-control" style="align-items:center;display:flex;flex-wrap:wrap;gap:8px"><input type="color" data-'.$this->prefix.'-colour-picker value="'.esc_attr($value?:'#1d5dbf').'" aria-label="Choose accent colour"><input class="regular-text code" style="max-width:130px" id="'.esc_attr($id).'" data-'.$this->prefix.'-colour-hex type="text" name="'.esc_attr($this->field_name($key)).'" value="'.esc_attr($value).'" placeholder="#1d5dbf" pattern="#[0-9A-Fa-f]{3}([0-9A-Fa-f]{3})?" aria-describedby="'.esc_attr($id).'-status"><button type="button" class="button" data-'.$this->prefix.'-clear-colour>Clear</button><span id="'.esc_attr($id).'-status" style="color:#646970" data-'.$this->prefix.'-colour-status>'.($value?'Custom colour override':'Using theme default').'</span></div>';
        if($help) echo '<p class="description">'.esc_html($help).'</p>';
        echo '</td></tr>';
    }

    public function multiplier_group($title,$description,$group,$items,$values) {
        echo '<section class="'.$this->prefix.'-multiplier-group"><h3>'.esc_html($title).'</h3><p>'.esc_html($description).'</p><table><thead><tr><th>Option</th><th>Multiplier</th><th>Price effect</th></tr></thead><tbody>';
        foreach($items as $key=>$label) {
            $value=(float)($values[$key]??1); $change=round(($value-1)*100,1);
            $effect=$change==0?'No change':($change>0?'+'.number_format_i18n($change,1).'%':number_format_i18n($change,1).'%');
            echo '<tr><th scope="row">'.esc_html($label).'</th><td><input type="number" min="0" step="0.01" data-'.$this->prefix.'-multiplier name="'.esc_attr($this->field_name($group.'['.$key.']')).'" value="'.esc_attr($value).'"></td><td data-'.$this->prefix.'-effect>'.esc_html($effect).'</td></tr>';
        }
        echo '</tbody></table></section>';
    }

    public function email_editor($label,$key,$value,$help='',$media_buttons=false) {
        echo '<div class="'.$this->prefix.'-email-editor"><h3>'.esc_html($label).'</h3>';
        wp_editor($value,$this->prefix.'_'.$key,['textarea_name'=>$this->field_name($key),'textarea_rows'=>6,'media_buttons'=>$media_buttons,'teeny'=>true]);
        if($help) echo '<p class="description">'.esc_html($help).'</p>';
        echo '</div>';
    }

    public function email_logo_control($settings) {
        $image_id=absint($settings['lead_email_logo_id']??0);
        $image_url=$image_id?wp_get_attachment_image_url($image_id,'medium'):'';
        echo '<div class="'.$this->prefix.'-email-logo-control" data-'.$this->prefix.'-email-logo><div class="'.$this->prefix.'-email-logo-preview">';
        echo $image_url?'<img src="'.esc_url($image_url).'" alt="">':'<span>No logo selected</span>';
        echo '</div><input type="hidden" data-'.$this->prefix.'-email-logo-id name="'.esc_attr($this->field_name('lead_email_logo_id')).'" value="'.esc_attr($image_id).'"><p><button type="button" class="button" data-'.$this->prefix.'-select-email-logo>Select or upload logo</button> <button type="button" class="button-link-delete" data-'.$this->prefix.'-remove-email-logo '.($image_id?'':'hidden').'>Remove logo</button></p></div>';
    }

    public function welcome_panel(array $args, callable $optin_renderer) {
        $shortcode=(string)($args['shortcode']??'');
        $product_label=(string)($args['product_label']??'products, base prices and configuration');
        $toolkit_url=(string)($args['toolkit_url']??'');
        $has_test_tab=!empty($args['has_test_tab']);
        echo '<section class="'.esc_attr($this->prefix).'-settings-panel" data-'.esc_attr($this->prefix).'-panel="welcome"><h2>Start Here</h2><div class="'.esc_attr($this->prefix).'-welcome-grid">';
        echo '<div class="'.esc_attr($this->prefix).'-welcome-card"><h3>Access Calculator Training</h3><p>Get practical setup training, calculator improvements and contractor onboarding tactics from Quiet City Design. These updates are designed to help you turn more estimate requests into real sales conversations.</p>';
        call_user_func($optin_renderer, true);
        echo '</div><div class="'.esc_attr($this->prefix).'-welcome-card"><h3>Quick Setup Checklist</h3><ol>';
        echo '<li>Add your contractor name, lead email and booking link.</li><li>Review the '.esc_html($product_label).'.</li><li>Confirm the allowances and adjustments match how you price work.</li><li>Add <code>'.esc_html($shortcode).'</code> to the page where visitors should request an estimate.</li>';
        if($has_test_tab) echo '<li>Save your settings, then open the <button type="button" class="button-link" data-'.esc_attr($this->prefix).'-open-tab="test">Test Estimate Form</button> to check pricing without saving a lead.</li>';
        else echo '<li>Save your settings, publish the calculator page and complete a test estimate before sharing it.</li>';
        echo '</ol><div class="'.esc_attr($this->prefix).'-toolkit-callout"><h3>Need the follow-up system too?</h3><p>The Lead System Toolkit helps contractors reply faster, catch missed calls and keep every customer conversation in one inbox.</p>';
        if($toolkit_url) echo '<p><a class="button button-secondary" href="'.esc_url($toolkit_url).'" target="_blank" rel="noopener noreferrer">See The Lead System Toolkit</a></p>';
        echo '</div></div></div></section>';
    }

    public function save_actions() {
        echo '<div class="'.$this->prefix.'-tab-save">';
        echo '<button type="submit" name="submit" class="button button-primary" form="'.esc_attr($this->prefix.'-settings-form').'">Save Settings</button>';
        echo ' <button type="button" class="button button-secondary" data-'.$this->prefix.'-open-tab="test">Test Estimate Form</button><p class="description">Save changes before testing so the internal calculator uses the latest pricing.</p></div>';
    }
}
