<?php

if ( ! defined( 'ABSPATH' ) ) {
	die();
}

if(is_admin() || is_customize_preview(  )) {
	require_once dirname(__FILE__) . '/widget-framework.php';
}

// Widget Class
class kanews_widget_class_eczane extends WP_Widget {

  // Create
	public function __construct(){
		$widget_ops = array('classname' => 'kanews_widget_eczane');
		$control_ops = array('id_base' => 'kanews_widget_eczane');
		parent::__construct('kanews_widget_eczane', ''.KAN_THEME_NAME .' - '.__( "Nöbetçi Eczaneler" , 'kanews' ), $widget_ops, $control_ops );	
		add_action('admin_enqueue_scripts', array('Kanews_Form_Elements', 'enqueue_scripts'));
	}
  
  // Front-end
	public function widget($args, $instance)
	{
    $hide_mobile = isset($instance['hide_mobile']) ? 'on' : 'off';
		$hide_desktop = isset($instance['hide_desktop']) ? 'on' : 'off';

		if($hide_mobile == 'on') {
			if(kan_is_mobile())
			return;
		}

		if($hide_desktop == 'on') {
			if(!kan_is_mobile())
			return;
		}

    $title = apply_filters('widget_title', isset($instance['title']) ? $instance['title'] : '' );
    $grid = (!empty($instance['grid'])) ? $instance['grid'] : 'col-12';
    $pages = (!empty($instance['pages'])) ? $instance['pages'] : '';
    $region = (!empty($instance['il'])) ? $instance['il'] : '';
    $city = (!empty($instance['ilce'])) ? $instance['ilce'] : '';
    
    // Get pharmacy data using the API function
    $data = kanews_eczane_times_api($region, $city);
    $date = date('Y-m-d');
    
    // Slider options
    $enable_slider = isset($instance['enable_slider']) ? $instance['enable_slider'] : 'off';
    $show_nav = isset($instance['show_nav']) ? $instance['show_nav'] : 'off';
    $autoplay = isset($instance['autoplay']) ? $instance['autoplay'] : 'off';
    
    // Determine number of items to show based on grid width
    $item = 4;
    if(isset($args['id'])) {
      $sidebar = explode('-', $args['id']);
    } else {
      $sidebar = array('0' => 'home', '1' => 'content');
    }
    
    if(isset($sidebar[2]) && $sidebar[2] == 'full') {
      switch($grid) {
        case 'col-12':
          $item = 4;
          break;
        case 'col-12 col-lg-8':
          $item = 3;
          break;
        case 'col-12 col-lg-6':
          $item = 2;
          break;
        case 'col-12 col-lg-4':
          $item = 1;
          break;
      }
    } elseif($sidebar[1] == 'content') {
      $item = 3;
      $grid = 'col-12';
    } elseif($sidebar[1] == 'sidebar') {
      $item = 1;
      $grid = 'col-12';
    }
    
    // Slider options for Slick
    $slick_options = [
      'slidesToShow'  => $item,
      'dots'  => false,
      'adaptiveHeight'  => false,
      'arrows'  => $show_nav == 'on',
      'autoplay'  => $autoplay == 'on',
      'responsive'  => [
        [
          'breakpoint'  => 992,
          'settings'  => [
            'slidesToShow' => 3
          ]
        ],
        [
          'breakpoint'  => 525,
          'settings'  => [
            'slidesToShow' => 1
          ]
        ],
        [
          'breakpoint'  => 400,
          'settings'  => [
            'slidesToShow' => 1
          ]
        ],
      ]
    ];
    
    // Determine column classes based on number of items
    switch($item) {
      case 1:
        $item_Col = 'col-12 col-md-12';
        break;
      case 2:
        $item_Col = 'col-12 col-md-6';
        break;
      case 3:
        $item_Col = 'col-12 col-md-4';
        break;
      case 4:
        $item_Col = 'col-12 col-md-3';
        break;
    }

    ?>

    <div id="<?php echo $this->id; ?>" class="<?php echo $grid; ?> kanews-pharmacy-widget">
      <div class="kanews-section kanews-section-flat">
  

        <?php if (isset($data['data']) && !empty($data['data'][0]) && $data['data'] != 'error'): ?>
          <?php if ($enable_slider == 'on'): ?>
            <div class="kanews-slider-1">
              <div class="kanews-slider-wrapper kanews-slider-grid" data-slick='<?php echo wp_json_encode($slick_options); ?>'>
              
                <div class="<?php echo $item_Col; ?>" style="margin:0!important">
              
                <div class="kanews-icon-box kanews-section m-0 p-1">

<div class="kanews-icon-box-content d-flex flex-column gap-1 justify-content-start text-left">
<div class="kanews-icon-box-icon icon-135deg"><i class="icon-arrow-long"></i></div>

            <h4><?php echo esc_html($title); ?></h4>
            <p><?php echo sprintf(esc_html__('%s için %s %s bölgesinde nöbetçi eczanelerin listesi.', 'kanews'), $date, $region, $city); ?></p>
            <?php if($pages != '' && $pages != 'all'): ?>
            <a href="<?php echo get_page_link($pages); ?>" class="kanews-label kanews-label-widget"><?php esc_html_e( 'Tümünü Gör', 'kanews' ); ?></a></div><div style="height: 15px"></div>
            <?php endif; ?>
            </div>
                </div>
                <?php foreach($data['data'][0] as $key => $eczane): 
                  if (!empty($eczane['eczane_adi'])): ?>
                    <div class="<?php echo $item_Col; ?>" style="margin:0!important">
                      <div class="pharmacy-item">
                        <div>
                          <h4 class="pharmacy-name">
                            <img src="<?php echo get_template_directory_uri(); ?>/assets/img/static/eczane.jpg" loading="lazy" width="24" height="24" alt="e">
                            <?php echo $eczane['eczane_adi']; ?>
                          </h4>
                          <div class="pharmacy-adress"><?php echo $eczane['adres']; ?></div>
                        </div>
                        <div>
                          <div class="pharmacy-tel">
                            <a class="kanews-btn mb-0 bg-dark kanews-btn-sm kanews-btn-block" href="tel:<?php echo preg_replace('/\D/', '', $eczane['telefon']); ?>">
                              <?php esc_html_e('Telefon Et', 'kanews'); ?>: <?php echo $eczane['telefon']; ?>
                            </a>
                          </div>
                          <div class="pharmacy-maps">
                            <a class="kanews-btn kanews-btn-block kanews-btn-sm" target="_blank" rel="nofollow" href="https://maps.google.com/?q=<?php echo urlencode($eczane['adres']); ?>">
                              <?php esc_html_e('Yol tarifi', 'kanews'); ?>
                            </a>
                          </div>
                        </div>
                      </div>
                    </div>
                  <?php elseif($key == 'notice'): ?>
                    <div class="col-12">
                      <div class="kanews-response kanews-response-info" role="alert"><?php echo $eczane; ?></div>
                    </div>
                  <?php else: ?>
                    <div class="col-12">
                      <div class="kanews-response kanews-response-info" role="alert">
                        <?php printf(esc_html__('%s için %s/%s bölgesinde nöbetçi eczane kaydı bulunamadı.', 'kanews'), $date, $region, $city); ?>
                      </div>
                    </div>
                  <?php endif; ?>
                <?php endforeach; ?>
              </div>
            </div>
          <?php else: ?>
            <div class="row equal-height">
            <div class="col-12 col-md-6 col-lg-4">
              
              <div class="kanews-icon-box kanews-section m-0 p-1">

    <div class="kanews-icon-box-content d-flex flex-column gap-1 justify-content-start text-left">
    <div class="kanews-icon-box-icon"><i class="icon-arrow-long"></i></div>

                <h4><?php echo esc_html($title); ?></h4>
                <p><?php echo sprintf(esc_html__('%s için %s %s bölgesinde nöbetçi eczanelerin listesi.', 'kanews'), $date, $region, $city); ?></p>
                <?php if($pages != '' && $pages != 'all'): ?>
                <a href="<?php echo get_page_link($pages); ?>" class="kanews-label kanews-label-widget"><?php esc_html_e( 'Tümünü Gör', 'kanews' ); ?></a></div><div style="height: 15px"></div>
                <?php endif; ?>
                </div>
            </div>
              <?php foreach($data['data'][0] as $key => $eczane): 
                if (!empty($eczane['eczane_adi'])): ?>
                  <div class="col-12 col-md-6 col-lg-4">
                    <div class="pharmacy-item">
                      <div>
                        <h4 class="pharmacy-name">
                          <img src="<?php echo get_template_directory_uri(); ?>/assets/img/static/eczane.jpg" loading="lazy" width="24" height="24" alt="e">
                          <?php echo $eczane['eczane_adi']; ?>
                        </h4>
                        <div class="pharmacy-adress"><?php echo $eczane['adres']; ?></div>
                      </div>
                      <div>
                        <div class="pharmacy-tel">
                          <a class="kanews-btn mb-0 bg-dark kanews-btn-sm kanews-btn-block" href="tel:<?php echo preg_replace('/\D/', '', $eczane['telefon']); ?>">
                            <?php esc_html_e('Telefon Et', 'kanews'); ?>: <?php echo $eczane['telefon']; ?>
                          </a>
                        </div>
                        <div class="pharmacy-maps">
                          <a class="kanews-btn kanews-btn-block kanews-btn-sm" target="_blank" rel="nofollow" href="https://maps.google.com/?q=<?php echo urlencode($eczane['adres']); ?>">
                            <?php esc_html_e('Yol tarifi', 'kanews'); ?>
                          </a>
                        </div>
                      </div>
                    </div>
                  </div>
                <?php elseif($key == 'notice'): ?>
                  <div class="col-12">
                    <div class="kanews-response kanews-response-info" role="alert"><?php echo $eczane; ?></div>
                  </div>
                <?php else: ?>
                  <div class="col-12">
                    <div class="kanews-response kanews-response-info" role="alert">
                      <?php printf(esc_html__('%s için %s/%s bölgesinde nöbetçi eczane kaydı bulunamadı.', 'kanews'), $date, $region, $city); ?>
                    </div>
                  </div>
                <?php endif; ?>
              <?php endforeach; ?>
            </div>
          <?php endif; ?>
        <?php else: ?>
          <div class="col-12">
            <div class="kanews-response kanews-response-info" role="alert">
              <?php printf(esc_html__('%s için %s/%s bölgesinde nöbetçi eczane kaydı bulunamadı.', 'kanews'), $date, $region, $city); ?>
            </div>
          </div>
        <?php endif; ?>
   
        
      </div>
    </div>
  <?php
	}
  
  // Update Form
	public function update($new_instance, $old_instance)
	{
		$instance = $old_instance;

		$instance['title'] = $new_instance['title'];
		$instance['pages'] = $new_instance['pages'];
		$instance['grid'] = $new_instance['grid'];
		$instance['il'] = $new_instance['il'];
		$instance['ilce'] = $new_instance['ilce'];
    $instance['hide_desktop'] = $new_instance['hide_desktop'];
		$instance['hide_mobile'] = $new_instance['hide_mobile'];
    $instance['enable_slider'] = $new_instance['enable_slider'];
    $instance['show_nav'] = $new_instance['show_nav'];
    $instance['autoplay'] = $new_instance['autoplay'];
		
		return $instance;
	}

  // Back-end
	public function form($instance)
	{
		$defaults = array( 
      'title' => esc_html__( 'Nöbetçi Eczaneler', 'kanews' ), 
			'il' => 'Ankara', 
			'ilce' => '', 
			'grid' => 'col-12', 
      'pages' => 'all', 
      'hide_desktop' 	 => 'off',
			'hide_mobile' 	 => 'off',
      'enable_slider' => 'off',
      'show_nav' => 'off',
      'autoplay' => 'off',
    );
		$instance = wp_parse_args((array) $instance, $defaults); 
		
		// Genel Ayarlar
		Kanews_Form_Elements::render_accordion_field([
			'title' => __('Genel Ayarlar', 'kanews'),
			'content' => [
				[
					'type' => Kanews_Form_Elements::TYPE_TEXT,
					'id' => $this->get_field_id('title'),
					'name' => $this->get_field_name('title'),
					'label' => __('Başlık', 'kanews'),
					'value' => $instance['title']
				],
				[
					'type' => Kanews_Form_Elements::TYPE_SELECT,
					'id' => $this->get_field_id('grid'),
					'name' => $this->get_field_name('grid'),
					'label' => __('Genişlik', 'kanews'),
					'value' => $instance['grid'],
					'class' => 'kanews-grid-select-x',
					'options' => [
						'col' => 'Sığdır',
						'col-12' => '12/12',
						'col-12 col-lg-8' => '12/8',
						'col-12 col-lg-6' => '12/6',
						'col-12 col-lg-4' => '12/4'
					]
				]
			]
		]);

		// Konum Ayarları
		Kanews_Form_Elements::render_accordion_field([
			'title' => __('Konum Ayarları', 'kanews'),
			'content' => [
				[
					'type' => Kanews_Form_Elements::TYPE_TEXT,
					'id' => $this->get_field_id('il'),
					'name' => $this->get_field_name('il'),
					'label' => __('İl', 'kanews'),
					'value' => $instance['il']
				],
				[
					'type' => Kanews_Form_Elements::TYPE_TEXT,
					'id' => $this->get_field_id('ilce'),
					'name' => $this->get_field_name('ilce'),
					'label' => __('İlçe', 'kanews'),
					'value' => $instance['ilce']
				]
			]
		]);

		// Sayfa Ayarları
		Kanews_Form_Elements::render_accordion_field([
			'title' => __('Sayfa Ayarları', 'kanews'),
			'content' => [
				[
					'type' => Kanews_Form_Elements::TYPE_SELECT,
					'id' => $this->get_field_id('pages'),
					'name' => $this->get_field_name('pages'),
					'label' => __('Sayfa', 'kanews'),
					'value' => $instance['pages'],
					'class' => 'pages',
					'options' => Kanews_Form_Elements::get_pages_options()
				]
			]
		]);

    // Slider Ayarları
    Kanews_Form_Elements::render_accordion_field([
      'title' => __('Slider Ayarları', 'kanews'),
      'content' => [
        [
          'type' => Kanews_Form_Elements::TYPE_TOGGLE,
          'id' => $this->get_field_id('enable_slider'),
          'name' => $this->get_field_name('enable_slider'),
          'label' => __('Slider Kullan', 'kanews'),
          'value' => $instance['enable_slider']
        ],
        [
          'type' => Kanews_Form_Elements::TYPE_TOGGLE,
          'id' => $this->get_field_id('show_nav'),
          'name' => $this->get_field_name('show_nav'),
          'label' => __('Navigasyon Butonları', 'kanews'),
          'value' => $instance['show_nav']
        ],
        [
          'type' => Kanews_Form_Elements::TYPE_TOGGLE,
          'id' => $this->get_field_id('autoplay'),
          'name' => $this->get_field_name('autoplay'),
          'label' => __('Otomatik Oynat', 'kanews'),
          'value' => $instance['autoplay']
        ]
      ]
    ]);

		// Görünürlük Ayarları
		Kanews_Form_Elements::render_accordion_field([
			'title' => __('Görünürlük Ayarları', 'kanews'),
			'content' => [
				[
					'type' => Kanews_Form_Elements::TYPE_TOGGLE,
					'id' => $this->get_field_id('hide_desktop'),
					'name' => $this->get_field_name('hide_desktop'),
					'label' => __('Masaüstünde Gizle', 'kanews'),
					'value' => $instance['hide_desktop']
				],
				[
					'type' => Kanews_Form_Elements::TYPE_TOGGLE,
					'id' => $this->get_field_id('hide_mobile'),
					'name' => $this->get_field_name('hide_mobile'),
					'label' => __('Mobilde Gizle', 'kanews'),
					'value' => $instance['hide_mobile']
				]
			]
		]);
		
		// Add visibility script
		?>
		<script type="text/javascript">
		<?php if($instance['hide_mobile'] == 'on' && $instance['hide_desktop'] != 'on'): ?>
			jQuery('div[id*="<?php echo $this->id; ?>"').addClass('kan-widget-visible-desktop');
		<?php elseif($instance['hide_desktop'] == 'on' && $instance['hide_mobile'] != 'on'): ?>
			jQuery('div[id*="<?php echo $this->id; ?>"').addClass('kan-widget-visible-mobile');
		<?php else: ?>
			jQuery('div[id*="<?php echo $this->id; ?>"').addClass('kan-widget-visible-all');
		<?php endif; ?>
		</script>
		<?php
	}
}
?>