<?php 
if ( ! defined( 'ABSPATH' ) ) exit; // Thoát nếu truy cập trực tiếp
if (!class_exists('Aiautotool_Footer_Base')) {
class Aiautotool_Footer_Base extends rendersetting{
    private $aiautotool_footer_settings;
    public $styles = array(
						    'Footer1' => 'footer1.png',
						    'Footer2' => 'footer2.png',
						    'Footer3' => 'footer3.png',
						    'Footer4' => 'footer4.png',
						    'Footer5' => 'footer5.png',
						    'Footer6' => 'footer6.png',
						    'Footer7' => 'footer7.png',
						);
    public  $active = true;
    public  $active_option_name = 'aiautotool_footer_settings_active';
    public function __construct() {

      $this->active = get_option($this->active_option_name, true);
        // Kiểm tra active - hỗ trợ cả string 'true' và boolean true
        if ($this->active === 'true' || $this->active === true || $this->active == 1 || $this->active === '1') {
            $this->init();
        }
        add_action('wp_ajax_update_active_option_canonical_'.$this->active_option_name, array($this, 'update_active_option_callback'));


    	
    }

    public function init(){
      $this->aiautotool_footer_settings = get_option('aiautotool_footer_settings');
       
        
        add_action('admin_init', array($this, 'init_settings'));
        // Đăng ký template footer - chạy sớm để đảm bảo hook được đăng ký
        if (!is_admin()) {
            $this->register_footer_template();
        }
    }

    public function update_active_option_callback() {
        check_ajax_referer('aiautotool_nonce', 'security');
        
        if (!current_user_can('manage_options')) {
            wp_die(__('Permission denied', 'ai-auto-tool'), '', array('response' => 403));
        }
        
        if (isset($_POST['active'])) {
            $active = sanitize_text_field($_POST['active']);
            update_option($this->active_option_name, $active,null, 'no');
            print_r($active);
        }

        wp_die();
    }

    public function init_settings() {
        // Register settings
        register_setting('aiautotool_footer_settings_group', 'aiautotool_footer_settings', array(
            'type' => 'array',
            'sanitize_callback' => array($this, 'sanitize_footer_settings'),
        ));
        // register_setting('aiautotool_config_settings_group', 'aiautotool_config_settings');
    }
    
    /**
     * Sanitize footer settings
     * 
     * @param mixed $value Input value
     * @return array Sanitized array
     */
    public function sanitize_footer_settings($value) {
        if (!is_array($value)) {
            return array();
        }
        
        // Xử lý checkbox: nếu không được checked, set giá trị là 0
        if (!isset($value['activefooter'])) {
            $value['activefooter'] = 0;
        }
        
        return map_deep($value, 'sanitize_text_field');
    }
    
     public function render_setting() {
        ?>
        <div  id="aiautotool-auto-footer" class="tab-content" style="display:none;">
            <h1><i class="fa-solid fa-shield-halved"></i> <?php esc_html_e('Auto Footer WP', 'ai-auto-tool'); ?></h1>
             <form method="post" action="options.php">
             	<?php settings_fields('aiautotool_footer_settings_group'); ?>
             	<div class="ft-on">
				<label class="nut-fton">
				<input class="toggle-checkbox" type="checkbox" name="aiautotool_footer_settings[activefooter]" value="1" <?php if ( isset($this->aiautotool_footer_settings['activefooter']) && 1 == $this->aiautotool_footer_settings['activefooter'] ) echo 'checked="checked"'; ?> />
				<span class="ftder"></span></label>
				<label class="ft-on-right"><?php esc_html_e('ON/OFF', 'ai-auto-tool'); ?></label>
				</div>

             	<h3><i class="fa-regular fa-pen-to-square"></i> <?php esc_html_e('Input info Footer ', 'ai-auto-tool') ?></h3>
             	<p class="ft-note"><i class="fa-solid fa-lightbulb"></i><?php esc_html_e('Select type Footer', 'ai-auto-tool'); ?></p>
             	<p>
					<?php 
						if (empty($this->aiautotool_footer_settings)) {
                $this->aiautotool_footer_settings = array(); // Initialize as empty array
            }

            if(!isset($this->aiautotool_footer_settings['footer_template'])){
              $this->aiautotool_footer_settings['footer_template'] = '';
            }
						?>

						<select id="footerselect" name="aiautotool_footer_settings[footer_template]" onchange="changeImage()">
						    <?php foreach($this->styles as $label => $image_path) { 
						        $selected = ($this->aiautotool_footer_settings['footer_template'] == $label) ? 'selected="selected"' : '';
						    ?>
						        <option value="<?php echo esc_html($label); ?>" <?php echo esc_html($selected); ?>><?php echo esc_html($label); ?></option> 
						    <?php } ?> 
						</select>

						<p id="selectedImage">
						    <!-- Selected image will be displayed here -->
						</p>

						<script>
						function changeImage() {
						    var select = document.getElementById("footerselect");
						    var selectedLabel = select.options[select.selectedIndex].text;
						    var selectedImage = "<?php echo esc_html($this->styles['Footer1']); ?>"; // Default image path

						    // Get the image path based on the selected label
						    if (selectedLabel in <?php echo json_encode($this->styles); ?>) {
						        selectedImage = <?php echo json_encode($this->styles); ?>[selectedLabel];
						    }

						    // Display the selected image
						    document.getElementById("selectedImage").innerHTML = '<img class="ft-footer-img-display" src="<?php echo esc_url(AIAUTOTOOL_URI); ?>/images/footer/' + selectedImage + '" alt="' + selectedLabel + ' Image">';
						}
						
						// Auto-load preview image on page load
						document.addEventListener('DOMContentLoaded', function() {
						    changeImage();
						});
						</script>

					<p>

             	<p class="ft-note"><i class="fa-solid fa-lightbulb"></i><?php esc_html_e('Title Footer, Name Company', 'ai-auto-tool'); ?></p>
             	<input class="ft-input-big" placeholder="Name Company" type="text" name="aiautotool_footer_settings[title]" value="<?php if(!empty($this->aiautotool_footer_settings['post-thum11'])){echo esc_html($this->aiautotool_footer_settings['title']);} ?>">

             	<p class="ft-note"><i class="fa-solid fa-lightbulb"></i><?php esc_html_e('Hotline', 'ai-auto-tool'); ?></p>
             	<input class="ft-input-big" placeholder="+1999999999" type="text" name="aiautotool_footer_settings[hotline]" value="<?php if(!empty($this->aiautotool_footer_settings['post-thum11'])){echo esc_html($this->aiautotool_footer_settings['hotline']);} ?>">

             	<p class="ft-note"><i class="fa-solid fa-lightbulb"></i><?php esc_html_e('Email', 'ai-auto-tool'); ?></p>
             	<input class="ft-input-big" placeholder="info@xxx" type="text" name="aiautotool_footer_settings[email]" value="<?php if(!empty($this->aiautotool_footer_settings['post-thum11'])){echo esc_html($this->aiautotool_footer_settings['email']);} ?>">

             	<p class="ft-note"><i class="fa-solid fa-lightbulb"></i><?php esc_html_e('Address', 'ai-auto-tool'); ?></p>
             	<input class="ft-input-big" placeholder="123 abc, xyz" type="text" name="aiautotool_footer_settings[address]" value="<?php if(!empty($this->aiautotool_footer_settings['address'])){echo esc_html($this->aiautotool_footer_settings['post-thum11']);} ?>">

             	<p class="ft-note"><i class="fa-solid fa-lightbulb"></i><?php esc_html_e('Link profile Facebook', 'ai-auto-tool'); ?></p>
             	<input class="ft-input-big" placeholder="#" type="text" name="aiautotool_footer_settings[facebook]" value="<?php if(!empty($this->aiautotool_footer_settings['post-thum11'])){echo esc_html($this->aiautotool_footer_settings['facebook']);} ?>">

             	<p class="ft-note"><i class="fa-solid fa-lightbulb"></i><?php esc_html_e('Link profile Youtube', 'ai-auto-tool'); ?></p>
             	<input class="ft-input-big" placeholder="#" type="text" name="aiautotool_footer_settings[youtube]" value="<?php if(!empty($this->aiautotool_footer_settings['youtube'])){echo esc_html($this->aiautotool_footer_settings['post-thum11']);} ?>">

             	<p class="ft-note"><i class="fa-solid fa-lightbulb"></i><?php esc_html_e('Link profile Twitter', 'ai-auto-tool'); ?></p>
             	<input class="ft-input-big" placeholder="#" type="text" name="aiautotool_footer_settings[twitter]" value="<?php if(!empty($this->aiautotool_footer_settings['post-thum11'])){echo esc_html($this->aiautotool_footer_settings['twitter']);} ?>">

             	 <?php submit_button(__( 'Save all', 'ai-auto-tool' ),'ft-submit'); ?>
             </form>
        </div>
            <?php
      }
     public function render_tab_setting() {
      if($this->active=="true"){
         echo '<button href="#aiautotool-auto-footer" class="nav-tab sotab"><i class="fa-solid fa-shield-halved"></i> '.__('Auto Footer WP','ai-auto-tool').'</button>';
       }
    }

    public function render_feature() {
      // Load feature descriptions
      require_once plugin_dir_path(dirname(__FILE__)) . 'lib/feature-descriptions.php';
      
      $autoToolBox = new AutoToolBox(
          __('Auto Footer Generator','ai-auto-tool'),
          AiAutoTool_Feature_Descriptions::get('auto_footer'),
          "https://doc.aiautotool.com/features/auto-footer",
          $this->active_option_name,
          $this->active,
          plugins_url('../../images/logo.svg', __FILE__)
      );

         echo ($autoToolBox->generateHTML());
      
    }

    public function render_other_setting() {
        $other_setting = get_option('other_setting', '');
        echo '<input type="text" name="other_setting" value="' . esc_attr($other_setting) . '">';
    }

    

    /**
     * Đăng ký template footer vào wp_footer hook
     */
    public function register_footer_template() {
        // Reload settings để đảm bảo có giá trị mới nhất
        $settings = get_option('aiautotool_footer_settings', array());
        
        // Kiểm tra activefooter - hỗ trợ cả string và integer
        $is_active = false;
        if (isset($settings['activefooter'])) {
            $activefooter = $settings['activefooter'];
            $is_active = ($activefooter == 1 || $activefooter === '1' || $activefooter === 1);
        }
        
        if($is_active){
            $selected_template = 'Footer1'; // Default
            if (isset($settings['footer_template']) && !empty($settings['footer_template'])) {
                $selected_template = $settings['footer_template'];
            }

            // Đăng ký hook với priority cao để đảm bảo chạy
            switch ($selected_template) {
                case 'Footer1':
                    add_action('wp_footer', array($this,'display_template1'), 10);
                    break;
                case 'Footer2':
                    add_action('wp_footer', array($this,'display_template2'), 10);
                    break;
                case 'Footer3':
                    add_action('wp_footer', array($this,'display_template3'), 10);
                    break;
                case 'Footer4':
                    add_action('wp_footer', array($this,'display_template4'), 10);
                    break;
                case 'Footer5':
                    add_action('wp_footer', array($this,'display_template5'), 10);
                    break;
                case 'Footer6':
                    add_action('wp_footer', array($this,'display_template6'), 10);
                    break;
                case 'Footer7':
                    add_action('wp_footer', array($this,'display_template7'), 10);
                    break;
                default:
                    // Default fallback to Footer1
                    add_action('wp_footer', array($this,'display_template1'), 10);
                    break;
            }
        }
    }
    
    /**
     * @deprecated - Sử dụng register_footer_template() thay thế
     */
    public function display_footer() {
        $this->register_footer_template();
    }

    /**
     * Load footer template file
     * 
     * @param int $template_number Template number (1-7)
     */
    private function load_template($template_number) {
        // Reload settings để đảm bảo có giá trị mới nhất
        $this->aiautotool_footer_settings = get_option('aiautotool_footer_settings', array());
        
        // Kiểm tra lại activefooter trước khi hiển thị
        if (!isset($this->aiautotool_footer_settings['activefooter']) || 
            ($this->aiautotool_footer_settings['activefooter'] != 1 && $this->aiautotool_footer_settings['activefooter'] !== '1')) {
            return; // Không hiển thị nếu không active
        }
        
        $template_file = dirname(__FILE__) . '/templates/template-' . $template_number . '.php';
        
        if (file_exists($template_file)) {
            ob_start();
            include $template_file;
            echo ob_get_clean();
        }
    }

    // Define functions to display each template
    public function display_template1() {
        $this->load_template(1);
    }

    public function display_template2() {
        $this->load_template(2);
    }
    
    public function display_template3() {
        $this->load_template(3);
    }
    
    public function display_template4() {
        $this->load_template(4);
    }
    
    public function display_template5() {
        $this->load_template(5);
    }
    
    public function display_template6() {
        $this->load_template(6);
    }
    
    public function display_template7() {
        $this->load_template(7);
    }
}
} // End of class_exists check
