<?php

namespace CarDealerPress\Includes\Functions;

use CarDealerPress\Includes\Database\Requests;
use CarDealerPress\includes\helpers\helpers as helpers;
use CarDealerPress\Includes\Helpers\Option;

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

class Sc_Run {

	private $vms;
	private $company;
	private $options;
	private $sc_atts;
	private $sc_content;
	public $sc_form;
	public $sc_search;
	public $sc_flag_saleclass;
	public $sc_default_saleclass;
	public $sc_dealer_id;
	public $use_vehicle_url;
	public $inventory_params;
	public $splide_params;

	public $fn_inventory;

	public $ext_functions;
	public $sc_views;
	public $theme_options;
	public $sc_image_size;
	public Requests $db_requests;


	public function __construct( $vms, $company, $options ) {
		$this->vms           = $vms;
		$this->company       = $company;
		$this->options       = $options;
		$this->fn_inventory  = new Fn_Inventory();
		$this->ext_functions = new Extender_Functions();
		$this->theme_options = Option::get_cdp_theme_options();
		$this->sc_views = new Sc_Views();
		$this->db_requests = new Requests();
	}

	public function inventory_list( $atts ) {
		$atts = empty( $atts ) ? array() : $atts;
		$atts = $this->escape_atts( $atts );

		// Shortcode Attributes.
		$sc_defaults = array(
			'saleclass'       => 'New',
			'make'            => '',
			'model'           => '',
			'trim'            => '',
			'vehicleclass'    => '',
			'price_from'      => '',
			'price_to'        => '',
			'certified'       => '',
			'tags'             => '', // icons.
			'limit'           => '10', // per_page.
			'style'           => 'newspaper',
			'dealer_id'       => 0,
			'image_size'      => 'small',
			'year_to'         => '',
			'year_from'       => '',
			'fuel_type'       => '',
			'use_vehicle_url' => false,
			'button'          => '',
		);
		extract( shortcode_atts( $sc_defaults, $atts ) );

		// Clean Arrays.
		$sc_atts  = array_merge( $sc_defaults, $atts );
		$sc_style = $sc_atts['style'];
		unset( $sc_atts['style'] );
		$sc_atts['per_page'] = $sc_atts['limit'];
		unset( $sc_atts['limit'] );
		$this->sc_image_size = $sc_atts['image_size'];
		unset( $sc_atts['image_size'] );
		$this->use_vehicle_url = $sc_atts['use_vehicle_url'];
		unset( $sc_atts['use_vehicle_url'] );

		foreach ( $sc_atts as $key => $att ) {
			if ( empty( $att ) ) {
				unset( $sc_atts[ $key ] );
			}
		}
		$this->sc_atts = $sc_atts;

		// Check and call File.
		if ( $this->vms ) {
			$this->sc_add_css_style( 'list', $sc_style );
			$this->get_sc_file( 'sc_inventory_list.php' );
		}

		// Display shortcode.
		return $this->sc_content;
	}

	public function inventory_detail( $atts ) {
		$atts = empty( $atts ) ? array() : $atts;
		$atts = $this->escape_atts( $atts );

		// Shortcode Attributes.
		$sc_defaults = array(
			'saleclass'    => 'all',
			'd_saleclass'  => 'all',
			'make'         => '',
			'model'        => '',
			'trim'         => '',
			'vehicleclass' => '',
			'tags'          => '', // icons.
			'limit'        => '10', // per_page.
			'style'        => '',
			'dealer_id'    => 0,
			'form_id'      => 0,
			'search'       => 0,
			'display'      => '',
			'fuel_type'    => '',
		);
		extract( shortcode_atts( $sc_defaults, $atts ) );
		// Clean Arrays.
		$sc_atts    = array_merge( $sc_defaults, $atts );
		$sc_display = ( empty( $sc_atts['display'] ) ? '' : '_' . $sc_atts['display'] );
		$sc_style   = ( empty( $sc_atts['style'] ) ? '' : '_' . $sc_atts['style'] );

		$this->sc_form              = $sc_atts['form_id'];
		$this->sc_search            = $sc_atts['search'];
		$this->sc_flag_saleclass    = strtolower( $sc_atts['saleclass'] );
		$this->sc_default_saleclass = 'all' === strtolower( $sc_atts['saleclass'] ) && 'all' !== strtolower( $sc_atts['d_saleclass'] ) ? strtolower( $sc_atts['d_saleclass'] ) : strtolower( $sc_atts['saleclass'] );
		$sc_atts['per_page']        = $sc_atts['limit'];
		$sc_atts['saleclass']       = $this->sc_default_saleclass;
		unset( $sc_atts['d_saleclass'] );
		unset( $sc_atts['style'] );
		unset( $sc_atts['limit'] );
		unset( $sc_atts['form_id'] );
		unset( $sc_atts['search'] );
		unset( $sc_atts['display'] );
		foreach ( $sc_atts as $key => $att ) {
			if ( empty( $att ) ) {
				unset( $sc_atts[ $key ] );
			}
		}
		$this->sc_atts = $sc_atts;

		$automall_check = false;
		$dealers        = empty( $this->company['automalls'] ) ? array() : $this->company['automalls'];
		if ( count( $dealers ) > 1 ) {
			$automall_check = true;
		}
		if ( $automall_check ) {
			$this->sc_dealer_id = $sc_atts['dealer_id'] ?? 0;
		} else {
			$this->sc_dealer_id = $sc_atts['dealer_id'] ?? helpers::company_id();
		}

		$dependent_scripts = array( 'jquery', 'jquery-ui-core', 'jquery-ui-dialog' );
		foreach ( $dependent_scripts as $dependent ) {
			wp_enqueue_script( $dependent );
		}

		if ( $this->vms ) {
			wp_enqueue_script( 'cdp_inventory_light_js', CDP_JS . 'jquery-lightbox/2.0/js/lightbox.js', array( 'jquery' ), '2.11.3', true );
			wp_enqueue_style( 'cdp_inventory_light', CDP_JS . 'jquery-lightbox/2.0/css/lightbox.css', array() ,'2.11.3' );

			$this->sc_add_js_script();
			$this->sc_add_css_style( 'detail', 'detail' . $sc_display . $sc_style );
			// Check and call File.
			$this->get_sc_file( 'sc_inventory_detail' . $sc_display . '.php' );
			$this->sc_add_ajax();

		}

		// Display shortcode.
		return $this->sc_content;
	}

	public function inventory_slider( $atts ) {
		$atts = empty( $atts ) ? array() : $atts;
		$atts = $this->escape_atts( $atts );

		// Shortcode Attributes.
		$sc_defaults = array(
			'saleclass'       => 'New',
			'make'            => '',
			'model'           => '',
			'trim'            => '',
			'vehicleclass'    => '',
			'tags'             => '', // icons.
			'limit'           => '10', // per_page # number of vehicles to get.
			'price'           => '',
			'mileage'         => '',
			'year'            => '',
			'dealer_id'       => '0',
			'fuel_type'       => '',
			'use_vehicle_url' => false,
			'image_size'      => 'small',
			'title'           => '',
			'show_attributes' => '0',
			'style'           => 'slider',
			'button'          => '',
			// Slider.
			'autoplay'        => true,
			'center'          => '0',
			'pagination'      => '0',
			'rewind'          => '1',
			'interval'        => 3000,
			'speed'           => 300,
		);
		extract( shortcode_atts( $sc_defaults, $atts ) );
		// rename old slick params to splide params
		$legacyMap = [
			'dots' => 'pagination',
			'autoplaySpeed' => 'interval',
			'infinite' => 'rewind',
			'is_slider' => 'autoplay',
		];
		$renamed = array_combine(array_map(function($el) use ($legacyMap) {
			if( ! array_key_exists( $el, $legacyMap ) ) {
				return $el;
			}
			return $legacyMap[$el];
		}, array_keys($atts)), array_values($atts));
		// Clean Arrays.
		$sc_atts          = array_merge( $sc_defaults, $renamed );
		$sc_style = $sc_atts['style'];
		$sc_atts['per_page'] = $sc_atts['limit'];
		unset( $sc_atts['limit'] );

		foreach ( $sc_atts as $key => $att ) {
			if ( $att !== '0' && empty( $att ) ) {
				unset( $sc_atts[ $key ] );
			}
		}

		// Extract price | mileage | year.
		foreach ( $sc_atts as $key => $value ) {
			if ( in_array( $key, array( 'price', 'mileage', 'year' ), true ) ) {
				$temp = explode( ',', $value );
				if ( 2 === count( $temp ) ) {
					$sc_atts[ $key . '_from' ] = $temp[0];
					$sc_atts[ $key . '_to' ]   = $temp[1];
				}
				unset( $sc_atts[ $key ] );
			}
		}

		$this->splide_params    = array();
		$this->inventory_params = array();
		$allowable_inventory_param_list   = array(
			'saleclass',
			'make',
			'model',
			'trim',
			'tags',
			'vehicleclass',
			'per_page',
			'price_from',
			'price_to',
			'year_from',
			'year_to',
			'mileage_to',
			'mileage_from',
			'dealer_id',
			'fuel_type',
			'title',
			'image_size',
			'use_vehicle_url',
			'show_attributes',
			'button',
		);
		$splide_param_list       = array(
			'autoplay',
			'pagination',
			'rewind',
			'interval',
			'speed',
		);
		foreach ( $sc_atts as $key => $value ) {
			if ( in_array( $key, $allowable_inventory_param_list, true ) ) {
				$this->inventory_params[ $key ] = $value;
			}
			$camel = lcfirst(str_replace('_', '', ucwords($key, '_')));
			if ( in_array( $camel , $splide_param_list, true ) ) {
				$this->splide_params[ $camel ] = $value;
			}
		}

		$this->sc_content = '';
		if ( $this->vms ) {
			wp_enqueue_script( 'cdp_splide_js', CDP_JS . 'splide/splide.min.js', array( 'jquery' ), '4.1.2', true );
			wp_enqueue_style( 'cdp_splide_style', CDP_CSS . 'splide/splide.min.css', array(), '4.1.2' );

			$this->sc_add_css_style( 'slider', $sc_style );
			$this->sc_add_js_script();

			$this->get_sc_file( 'sc_inventory_slider.php' );
		}

		return $this->sc_content;
	}

	public function inventory_counter( $atts ) {
		$atts = empty( $atts ) ? array() : $atts;
		$atts = $this->escape_atts( $atts );


		// Shortcode Attributes.
		$sc_defaults = array(
			'saleclass'        => 'New',
			'make'             => '',
			'model'            => '',
			'show_make_count'  => 1,
			'show_models'      => 1,
			'show_model_count' => 1,
			'show_trims'      => '',
			'show_trim_count' => '',
			'style'            => 'counter',
		);
		extract( shortcode_atts( $sc_defaults, $atts ) );
		$this->sc_atts    = array_merge( $sc_defaults, $atts );
		$this->sc_content = '';
		// Check and call File.
		$this->get_sc_file( 'sc_inventory_counter.php' );
		$this->sc_add_css_style( 'counter', $this->sc_atts['style'] );

		return $this->sc_content;
	}

	public function inventory_search( $atts ) {
		$atts              = empty( $atts ) ? array() : $atts;
		$atts = $this->escape_atts( $atts );

		$dependent_scripts = array( 'jquery', 'jquery-ui-core', 'jquery-ui-dialog' );
		foreach ( $dependent_scripts as $dependent ) {
			wp_enqueue_script( $dependent );
		}

		// Shortcode Attributes.
		$sc_defaults = array(
			'saleclass_display' => 0, // 0=New,Used,Certified, 1=New,Used 2=Used,Certified, 3=New, 4=Used, 5=Certified.
			'saleclass_default' => 0, // 0=Nothing, 1=New, 2=Used, 3=Certified.
			'show_model_codes'  => 0, // 0=Off, 1=On.
			'show_trims'        => 0, // 0=Off, 1=On.
			'show_search'       => 0, // 0=Off, 1=On.
			'show_counts'       => 0, // 0=Off, 1=On.
			'hide_labels'       => 0, // 0=Off, 1=On.
			'style'             => 'stack', // Stack/Wide/Inline.
			'wildcard' => 0, // 0=Off, 1=On.
		);
		extract( shortcode_atts( $sc_defaults, $atts ) );
		$this->sc_atts = array_merge( $sc_defaults, $atts );
		$this->sc_add_css_style( 'search', 'search' );
		$this->sc_content = '';

		// Check and call File.
		if ($this->sc_atts['wildcard']) {
			$this->sc_add_js_script('inventory-search-wildcard');
			$this->get_sc_file( 'sc_inventory_search_wildcard.php' );
		} else {
			$this->sc_add_js_script();
			$this->get_sc_file( 'sc_inventory_search.php' );
		}
		$this->sc_add_ajax();

		return $this->sc_content;

	}

	public function get_sc_file( $file_name ) {
		$handle = opendir( CDP_DIR_PATH . 'templates/shortcode/' );
		if ( $handle ) {
			while ( false !== ( $file = readdir( $handle ) ) ) {
				if ( $file === $file_name ) {
					include CDP_DIR_PATH . 'templates/shortcode/' . $file_name;
				}
			}
			closedir( $handle );
		} else {
			helpers::output_wp_kses(__FUNCTION__ . ' Could not open directory at: ' . dirname( __FILE__ ) . '/' . $file_name );

			return false;
		}
	}

	public function sc_add_css_style( $sc, $style ) {
		if ( 'clear' !== strtolower( $style ) ) {
			wp_enqueue_style( 'cdp-' . $sc . '-shortcode-' . $style, CDP_CSS . 'templates/shortcodes/sc_' . $style . '.css', false, CDP_VERSION );
		}
	}

	public function sc_add_js_script( $file_name = 'cdp-shortcodes') {
		wp_register_script( 'cdp_shortcodes_js', CDP_JS . 'templates/shortcodes/'.$file_name.'.js', 'jquery', CDP_VERSION, true );
		wp_enqueue_script( 'cdp_shortcodes_js' );
	}

	public function sc_add_ajax() {
		// adding wp ajax.
		$ajax_script = admin_url( 'admin-ajax.php' );
		wp_localize_script(
			'cdp_shortcodes_js',
			'ajax_object',
			array(
				'url'     => $ajax_script,
				'nonce'   => wp_create_nonce( 'cdp_nonce' ),
				'img_src' => CDP_IMG,
			)
		);
	}

	public function escape_atts( $atts ) {
		foreach ( $atts as $key => $value ) {
			if ( !empty( $value ) ) {
				$atts[$key] = esc_attr( $value );
			}
		}
		return $atts;
	}


}
