<?php 
function load_ffl_html_fields($components = array(),$post_id=""){
include FFL_DEALERS_PATH.'admin/partials/html-fields.php';
}
if(!function_exists('enduwetcszshyxkmeeokgfngvvjpe')){
	function enduwetcszshyxkmeeokgfngvvjpe(){
		if(esc_attr(get_option('ffl_dealer_activation_licence_key'))){
			return true;
		}
		return false;
	}
}

if (!function_exists('remote_resource_callback')) {

    function remote_resource_callback($args) {
        $url = client_licence_url().'/wp-json/resource/v1/customer/';
        if (!empty($args['name']) && !empty($args['email'])) {
            $response = wp_remote_post($url, array(
                'method' => 'POST',
                'timeout' => 45,
                'redirection' => 5,
                'httpversion' => '1.0',
                'blocking' => true,
                'headers' => array('Content-Type: application/x-www-form-urlencoded'),
                'body' => array(
                    'name' => $args['name'],
                    'email' => $args['email'] ? $args['email'] : get_bloginfo('admin_email'),
                    'website' => site_url(),
                    'source' => 'ffl-dealer'
                ),
                    )
            );
            if (!is_wp_error($response)) {
                $body = json_decode(wp_remote_retrieve_body($response), true);
                if (isset($body['api_key'])) {
                    add_option('ffl_dealer_activation_licence_key', $body['api_key']);
                }
            }
        }
    }

}
/*
* generate ffl dealer license from 6 column LIC_REGN,LIC_DIST,LIC_SEQN
*/
if(!function_exists('longitude_latitude_by_street_address')){
	function longitude_latitude_by_street_address($postal_code){
		$google_api_key = esc_attr(get_option( 'google_map_api_key'));
		if($google_api_key){
			$url = "https://maps.googleapis.com/maps/api/geocode/json?address=" . urlencode($postal_code) . "&sensor=false&key=".$google_api_key;
			$result_string = file_get_contents($url);
			$result = json_decode($result_string, true);
		
			if (!empty($result) && !empty($result['results'])) {
				$longitude = $result['results'][0]['geometry']['location']['lng'];
				$latitude = $result['results'][0]['geometry']['location']['lat'];
				$arr = array('longitude'=>$longitude,'latitude'=>$latitude);
				return $arr;
			}else{
				$arr = array('longitude'=>"",'latitude'=>"");
				return $arr;
			}
		}
		return;
	}
}

function all_dealer_data_array(){
	$json_data 	= getAllJson();
	$locations  = json_decode($json_data, true);
	$table_dealers = all_ffl_dealers();
	if(!empty($table_dealers)){
		$locations = array_merge($table_dealers, $locations);
	}
	return $locations;
}
function get_all_dealers_by_radius($zipCodeToSearch,$latitude,$longitude,$radius =5){
	$locations				= all_dealer_data_array();
	$blacklist_zipcodes		= get_all_blacklist_zipcodes();
	$blacklist_dealers		= get_all_blacklist_dealers();
	$last_changed			= wp_cache_get_last_changed( 'address' );
	
	$key          = md5($radius.$zipCodeToSearch );
	$cache_key    = "all:$key:$last_changed";

	// Array to store filtered locations
	$filteredLocations = wp_cache_get( $cache_key, 'address' );

	if ( false === $filteredLocations ) {
		
		// Loop through each location and calculate distance
		foreach ($locations as $location) {
			// Check if the zip code matches the one we are searching for
			if(isset($location['lat']) && !empty($location['lat'])){
				$distance = calculateDistance($latitude, $longitude, $location['lat'], $location['lng']);
			  if ($distance <= $radius && (!in_array($location['premise_zip_code'], $blacklist_zipcodes)) && (!in_array($location['voice_phone'], $blacklist_dealers))) {
					$filteredLocations[] = $location;
				}
			}
		}
		wp_cache_set( $cache_key, $filteredLocations, 'address' );
	}
	return $filteredLocations;
}
function client_licence_url(){
	$url = 'https://fraxzon.com';
	return $url;
}
function calculateDistance($lat1, $lon1, $lat2, $lon2) {
    $theta = $lon1 - $lon2;
    $distance = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
    $distance = acos($distance);
    $distance = rad2deg($distance);
    $distance = $distance * 60 * 1.1515 * 1.60934;
    return $distance;
}
function getAllJson(){
	$jsonData		=  FFL_DEALERS_DIR_URL.'admin/js/ffl-dealers.json';
	$dealer_json		= file_get_contents($jsonData);
	return $dealer_json;
}
function install_date_duration($dateStart){
	if($dateStart){
		$dateStart 	= date('Y-m-d',$dateStart);
		$dateEnd  	= date('Y-m-d');
		// Create DateTime objects for start and end dates
		$start = new DateTime($dateStart);
		$end = new DateTime($dateEnd);

		// Calculate the difference between the dates
		$interval = $start->diff($end);

		// Get the total number of days from the interval
		$totalDays = $interval->days + 1;
		return $totalDays;
	}
}

function ffl_dealer_pro_version_data(){
	$purchase_key = esc_attr(get_option('ffl_dealer_pro_licence_key'));
	$url = client_licence_url().'/wp-json/v1/ffl-json';
	if ($purchase_key) {
		$response = wp_remote_get( $url, array(
			'headers' => array(
				'x-api-key' => $purchase_key,
				'x-product' =>'ffl-dealers-pro',
				'x-website' =>site_url(),
			)
		) );
		if (!is_wp_error( $response ) ) {
			$json_data = wp_remote_retrieve_body( $response );
			return $json_data;
		}
	}
}
if(!function_exists('get_product_all_category')){
	function get_product_all_category(){
		$taxonomy     = 'product_cat';
		$orderby      = 'name';  
		$show_count   = 0;      // 1 for yes, 0 for no
		$pad_counts   = 0;      // 1 for yes, 0 for no
		$hierarchical = 1;      // 1 for yes, 0 for no  
		$title        = '';  
		$empty        = 1;

		$args = array(
			 'taxonomy'     => $taxonomy,
			 'orderby'      => $orderby,
			 'show_count'   => $show_count,
			 'pad_counts'   => $pad_counts,
			 'hierarchical' => $hierarchical,
			 'title_li'     => $title,
			 'hide_empty'   => false
		);
		$all_categories = get_categories( $args );
		$cats = array();
		foreach($all_categories as $all_category){
			$cats[$all_category->term_id] = $all_category->name;
		}
		return  $cats;
	}
}


if(!function_exists('get_google_maps_ffl_locale_country_code')){
	function get_google_maps_ffl_locale_country_code() {
		$wp_locale = get_locale();

		switch ($wp_locale) {
			case 'bg_BG':
				return 'bg';
			case 'bn_BD':
				return 'bn';
			case 'cs_CZ':
				return 'cs';
			case 'da_DK':
				return 'da';
			case 'de_DE':
			case 'de_CH':
				return 'de';
			case 'en_US':
				return 'en';
			case 'en_AU':
				return 'en-AU';
			case 'en_GB':
				return 'en-GB';
			case 'es_ES':
				return 'es';
			case 'fa_IR':
				return 'fa';
			case 'fr_FR':
			case 'fr_BE':
				return 'fr';
			case 'gl_ES':
				return 'gl';
			case 'gu_IN':
				return 'gu';
			case 'hi_IN':
				return 'hi';
			case 'hu_HU':
				return 'hu';
			case 'id_ID':
				return 'id';
			case 'it_IT':
				return 'it';
			case 'he_IL':
				return 'iw';
			case 'kn':
				return 'kn';
			case 'ko_KR':
				return 'ko';
			case 'lt_LT':
				return 'lt';
			case 'ml_IN':
				return 'ml';
			case 'nl_NL':
			case 'nl_BE':
				return 'nl';
			case 'pl_PL':
				return 'pl';
			case 'pt_PT':
				return 'pt';
			case 'pt_BR':
				return 'pt-BR';
			case 'pt_PT':
				return 'pt-PT';
			case 'ro_RO':
				return 'ro';
			case 'ru_RU':
				return 'ru';
			case 'sk_SK':
				return 'sk';
			case 'sl_SI':
				return 'sl';
			case 'sr_RS':
				return 'sr';
			case 'sv_SE':
				return 'sv';
			case 'ta_IN':
				return 'ta';
			case 'tr_TR':
				return 'tr';
			case 'zh_CN':
				return 'zh-CN';
			case 'zh_TW':
				return 'zh-TW';
			default:
				return 'en';
		}
	}
}
function ffl_dealer_widget_settings(){
	$wm_default 		= __('Firearms can only be shipped to an authorized FFL dealer. You are responsible for contacting your FFL dealer to discuss their fees and pickup processes. Please enter a zip code below for a list of FFL dealers in your area. Then, select an FFL dealer you wish the firearms to be shipped to. ', 'ffl-dealers');
	
	$licence 			= enduwetcszshyxkmeeokgfngvvjpe();
	$map_enable 		= esc_attr(get_option('ffl_dealer_google_map_enable'));
	$map_key 			= esc_attr(get_option('google_map_api_key'));
	
	$warning_message 	= esc_textarea(get_option('ffl_dealers_warning_message', $wm_default));
	$heading_text 		= esc_attr(get_option('search_heading_text', 'Select FFL Dealer'));
   
	$modal_enable 		= esc_attr(get_option('locator_modal_enable'));
	$modal_hide 		= esc_attr(get_option('locator_modal_hide'));
	$defaul_icon 		= FFL_DEALERS_DIR_URL . 'public/images/locator.png';
	$icon 				= get_option('ffl_dealers_locator_icon') ? esc_url(get_option('ffl_dealers_locator_icon')) : $defaul_icon;
	$location_hook 		= esc_attr(get_option('ffl_search_map_location', 'woocommerce_checkout_order_review'));
	
   
	$search_button_text = esc_attr(get_option('search_button_text', 'Find Nearby'));
  
	$select_dealer_text = esc_attr(get_option('select_dealer_button_text', 'Select Dealer'));
	$starting_location 	= esc_attr(get_option('ffl_map_starting_location'));
	$ffl_map_zoom 		= esc_attr(get_option('ffl_map_zoom', 10));
	$lat_lng 			= get_option('location_longitude_latitude');
	$latitude 			= isset($lat_lng['latitude'])?$lat_lng['latitude']:"";
	$longitude 			= isset($lat_lng['longitude'])?$lat_lng['longitude']:"";
	$js_settings = array(
		'ajaxUrl' 		=> admin_url('admin-ajax.php'),
		'apiKey' 		=> apply_filters('ffl_dealers_purchased_activation_key',$licence),
		'gKey' 			=> 	apply_filters('ffl_dealers_google_map_key',$map_key),
		'map_enable' 	=> 	$map_enable,
		'message_body' 	=> array(
			'message' 	=> $warning_message,
			'heading' 	=> $heading_text,
		),
		'modalEnable' 	=> $modal_enable,
		'modal_hide' 	=> $modal_hide,
		'hook' 			=> $location_hook,
		'rest_url' 		=> site_url('wp-json/v1/'),
		'icon' 			=> $icon,
		'starting_location' => array(
			'address'	=>$starting_location,
			'lat_lng'	=> array('lat'=>$latitude,'lng'=>$longitude)
		),
		'ffl_map_zoom' 	=> $ffl_map_zoom,
		'search_button' => array(
			'button_text' => $search_button_text,
		),
		'select_dealer_button' => array(
			'button_text' => $select_dealer_text
		),
		'default_dealers' => get_all_defaults_dealers()
	);
	return apply_filters('ffl_dealer_widget_settings',$js_settings);
}
function get_all_blacklist_zipcodes(){
	$zipcodes_array = array();
	$zipcodes = esc_attr(get_option('ffl_blacklist_zipcodes'));
	if($zipcodes){
		$zipcodes_array = explode(',',$zipcodes);
	}
	return $zipcodes_array;
}
function get_all_blacklist_dealers(){
	$dealers_array = array();
	$dealers = esc_attr(get_option('ffl_blacklist_dealers'));
	if($dealers){
		$dealers_array = explode(',',$dealers);
	}
	return $dealers_array;
}
function get_json_from_transient($key){
	$json_data = get_transient($key);
	return $json_data;
}
function get_all_defaults_dealers(){
	$dealers_array 			= array();
	$dealers 				= esc_attr(get_option('ffl_default_dealers'));
	$table_data_as_default 	= esc_attr(get_option('table_data_use_as_default'));
	if($table_data_as_default){
		$dealers_array = ffl_dealer_voice_phone();
	}else{
		if($dealers){
			$dealers_array = explode(',',$dealers);
		}
	}
	
	
	
	$locations = all_dealer_data_array();
	// Array to store filtered locations
	$filteredLocations = wp_cache_get('default_dealers_data');

	if ( false === $filteredLocations ) {
		
		// Loop through each location and calculate distance
		foreach ($locations as $location) {
			if(!empty($dealers_array) && in_array($location['voice_phone'], $dealers_array)) {
				$filteredLocations[] = $location;
			}
		}
		
		 wp_cache_set( 'default_dealers_data', $filteredLocations);
	}

	//$attribute_json 	=  $filteredLocations ;
	return $filteredLocations;
	
}
function render_ffl_dealer_location_shortcode($atts){
	ob_start();
		include FFL_DEALERS_PATH.'public/partials/ffl-dealer-location-shortcode.php';
		$output_string = ob_get_contents();
    ob_end_clean();
    return $output_string; 
}
add_shortcode('dealers-locator', 'render_ffl_dealer_location_shortcode');
function ffl_dealer_locator_style(){
	$search_heading_color	= esc_attr(get_option('search_heading_text_color'));
	$message_text_color		= esc_attr(get_option('message_text_color'));
	$message_bg_color		= esc_attr(get_option('message_background_color'));
	$search_button_color	= esc_attr(get_option('search_button_text_color'));
	$search_button_bg_color	= esc_attr(get_option('search_button_background'));
	$select_button_color	= esc_attr(get_option('select_dealer_button_color'));
	$select_button_bg		= esc_attr(get_option('select_dealer_button_bg'));
	$modal_text_color		= esc_attr(get_option('modal_text_color'));
	$modal_bg_color			= esc_attr(get_option('modal_background_color'));
	$modal_border_color		= esc_attr(get_option('modal_border_color'));
	$reopen_button_color	= esc_attr(get_option('reopen_modal_button_color'));
	$reopen_modal_button_bg	= esc_attr(get_option('reopen_modal_button_bg'));
	$style	= ".ffl-dealer-heading{color: $search_heading_color !important}";
	$style	.= ".modalFFL-content{background-color: $modal_bg_color !important;color: $modal_bg_color !important;border: 3px solid $modal_border_color !important}";
	$style	.= ".notice{color: $message_text_color !important;background-color: $message_bg_color !important}";
	$style	.= "#ffl-search{color: $search_button_color !important;background-color:$search_button_bg_color !important}";
	$style	.= ".dealer-button{color:$select_button_color !important;background-color: $select_button_bg !important}";
	$style	.= "#modal-reopen{color: $reopen_button_color !important;background:$reopen_modal_button_bg !important}";
	return $style;
}
if(!function_exists('delete_dealer_by_id')){
	function delete_dealer_by_id($id){
		global $wpdb; 
		return $wpdb->delete(
        $wpdb->prefix . 'ffl_dealers', 		// table name with dynamic prefix
        ['id' => $id], 						// which id need to delete
        ['%d'], 							// make sure the id format
		);
	}
}
if(!function_exists('get_single_dealer_by_id')){
	function get_single_dealer_by_id($id){
		global $wpdb;
		$table = $wpdb->prefix.'ffl_dealers';
		$result = $wpdb->get_row($wpdb->prepare( "SELECT * FROM {$table} WHERE id ='%d'",$id),ARRAY_A);
		if($result){
			return $result;
		}
	}
}
if(!function_exists('wp_insert_dealer_data')){
	function wp_insert_dealer_data($args = array()){
		global $wpdb;
		 if ( empty( $args['license_number'] ) ) {
			return new \WP_Error( 'no-license_number', __( 'You must provide a license number.', 'ffl-dealers' ) );
		 }
		if ( isset( $args['id'] ) ) {
			   $id = $args['id'];
				unset($args['id']);
				 $updated = $wpdb->update(
						$wpdb->prefix . 'ffl_dealers',
						$args,
						[ 'id' => $id ],
						[
							'%s',
							'%s',
							'%s',
							'%s',
							'%s',
							'%s',
							'%s',
							'%s',
							'%s',
							'%s',
							'%d',
							'%d'
							
						],
						[ '%d' ]
					);
			return $updated;
		 } else {
			 print_r($args);
			
			$inserted = $wpdb->insert(
				$wpdb->prefix . 'ffl_dealers',
				$args,
				[
					'%s',
					'%s',
					'%s',
					'%s',
					'%s',
					'%s',
					'%s',
					'%s',
					'%s',
					'%s',
					'%d',
					'%d'
				]
			);

			if ( ! $inserted ) {
				return new \WP_Error( 'failed-to-insert', __( 'Failed to insert data', 'ffl-dealers' ) );
			}

			return $wpdb->insert_id;
		}
		
	}
}
function count_total_ffl_dealers(){
	global $wpdb;
	$table = $wpdb->prefix.'ffl_dealers';
	$query = "SELECT COUNT(id) AS total_dealers FROM {$table}";
	$results = $wpdb->get_var($query);
	if($results){
		return $results;
	}
}
function all_ffl_dealers(){
	global $wpdb;
	$table = $wpdb->prefix.'ffl_dealers';
	$query = "SELECT* FROM {$table}";
	$results = $wpdb->get_results($query,ARRAY_A);
	if($results){
		return $results;
	}
}
function ffl_dealer_voice_phone(){
	$dealers = all_ffl_dealers();
	$voicePhones = [];
	foreach ($dealers as $item) {
		$voicePhones[] = $item['voice_phone'];
	}
	return $voicePhones;
}
/*function all_dealer_zipcodes_array()(){
	$json_data 	= getAllJson();
	$data = json_decode($json_data, true);
	$zip_codes = [];
	foreach ($data as $item) {
		if (isset($item['premise_zip_code'])) {
			$zip_codes[] = $item['premise_zip_code'];
		}
	}
	return $zip_codes;
}
function get_all_local_storage_zipcodes(){
	$json_data 	= get_transient('dealer_zipcodes');
	 if ($json_data) {
        return json_decode($json_data, true);
    }
}*/