<?php


function vq_enqueue_theme_resources() {
	$templateUri  = get_template_directory_uri();
	$assetsFolder = "$templateUri/assets";
	wp_enqueue_style( 'vq_customStyle', "$assetsFolder/css/custom.css", array(), '1.0.0', 'all' );
	wp_enqueue_script( 'vq_jquery', "https://code.jquery.com/jquery-3.3.1.min.js", array(), '1.0.0' );
	wp_enqueue_script( 'vq_indexJs', "$assetsFolder/js/index.js", array( 'vq_jquery' ), '1.0.0');
}

function vq_enqueue_custom_admin_style() {
	$templateUri  = get_template_directory_uri();
	$assetsFolder = "$templateUri/assets";
	wp_enqueue_style( 'vq_adminStyle', "$assetsFolder/css/admin.css", array(), '1.0.0', 'all' );
	wp_enqueue_script( 'vq_adminJquery', "https://code.jquery.com/jquery-3.3.1.min.js", array(), '1.0.0' );
	wp_enqueue_style( 'vq_adminBootstrap', "$assetsFolder/css/bootstrap-grid.css", '1.0.0', 'all' );
	wp_enqueue_script( 'vq_adminJs', "$assetsFolder/js/admin.js", array('vq_adminJquery'), '1.0.0' );
}

function vq_register_theme_supports() {
	add_theme_support( 'menus' );
	add_theme_support( 'custom-background' );
	add_theme_support( 'post-thumbnails' );
	add_theme_support( 'custom-logo' );

	register_nav_menu( 'primary', 'Primary Menu' );
	register_nav_menu( 'secondary', 'Secondary Menu' );
}


// Register Settings sin the Customizer API
function vq_theme_customize_register( $wp_customize ) {

	// Footer settings
	$wp_customize->add_section( 'vq_footer_section', array(
		'title'    => __( 'Footer Settings' ),
		'priority' => 30
	) );
	$wp_customize->add_setting( 'vq-copyright-text', array() );
	$wp_customize->add_control( new WP_Customize_Control(
			$wp_customize,
			'vq_about_us_title_text',
			array(
				'label'    => __( 'About Us Title' ),
				'section'  => 'vq_footer_section',
				'settings' => 'vq-about-us-title-text',
				'priority' => 1
			)
		)
	);

	$wp_customize->add_setting( 'vq-about-company-text', array() );
	$wp_customize->add_control( new WP_Customize_Control(
			$wp_customize,
			'vq_about_company_text',
			array(
				'type'     => 'textarea',
				'label'    => __( 'About' ),
				'section'  => 'vq_footer_section',
				'settings' => 'vq-about-company-text',
				'priority' => 2
			)
		)
	);

	$wp_customize->add_setting( 'vq-about-us-title-text', array() );
	$wp_customize->add_control( new WP_Customize_Control(
			$wp_customize,
			'vq_copyright_text',
			array(
				'type'     => 'textarea',
				'label'    => __( 'Copyright' ),
				'section'  => 'vq_footer_section',
				'settings' => 'vq-copyright-text',
				'priority' => 3
			)
		)
	);


	// Sidebar Sections
	$wp_customize->add_section( 'vq_sidebar_section', array(
		'title'    => __( 'Sidebar' ),
		'priority' => 40
	) );

	$wp_customize->add_setting( 'vq-speed-test-heading', array() );
	$wp_customize->add_control( new WP_Customize_Control(
			$wp_customize,
			'vq_speed_test_heading',
			array(
				'label'    => __( 'Speed Test' ),
				'section'  => 'vq_sidebar_section',
				'settings' => 'vq-speed-test-heading',
				'priority' => 1
			)
		)
	);

	$wp_customize->add_setting( 'vq-recent-posts-heading', array() );
	$wp_customize->add_control( new WP_Customize_Control(
			$wp_customize,
			'vq_recent_posts_heading',
			array(
				'label'    => __( 'Recent Posts' ),
				'section'  => 'vq_sidebar_section',
				'settings' => 'vq-recent-posts-heading',
				'priority' => 2
			)
		)
	);

	$wp_customize->add_setting( 'vq-top-reviews-heading', array() );
	$wp_customize->add_control( new WP_Customize_Control(
			$wp_customize,
			'vq_top_reviews_heading',
			array(
				'label'    => __( 'Top New Reviews' ),
				'section'  => 'vq_sidebar_section',
				'settings' => 'vq-top-reviews-heading',
				'priority' => 3
			)
		)
	);

	$wp_customize->add_setting( 'vq-top-hosting-heading', array() );
	$wp_customize->add_control( new WP_Customize_Control(
			$wp_customize,
			'vq_top_hosting_heading',
			array(
				'label'    => __( 'Top Hosting' ),
				'section'  => 'vq_sidebar_section',
				'settings' => 'vq-top-hosting-heading',
				'priority' => 4
			)
		)
	);

	$wp_customize->add_setting( 'vq-newsletter-heading', array() );
	$wp_customize->add_control( new WP_Customize_Control(
			$wp_customize,
			'vq_newsletter_heading',
			array(
				'label'    => __( 'Newsletter' ),
				'section'  => 'vq_sidebar_section',
				'settings' => 'vq-newsletter-heading',
				'priority' => 5
			)
		)
	);

}

// Include Admin
$templateDirectory = get_template_directory();
require_once( "$templateDirectory/admin/functions.php" );



function generateRandomString($length = 10) {
	$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
	$charactersLength = strlen($characters);
	$randomString = '';
	for ($i = 0; $i < $length; $i++) {
		$randomString .= $characters[rand(0, $charactersLength - 1)];
	}
	return $randomString;
}

function vq_get_hosting_speed() {

	try {
		$servers = json_decode(get_option('vq_hosting_server_locations'));
		if (!isset($servers) || count($servers) === 0) {
			print_r(['error' => 'No servers found.']);
		}

		$requestBatch = generateRandomString(10);

		$allResults = [];
		global $wpdb;
		$speed_table_name = $wpdb->prefix . "speed_results";
		for($i = 0; $i < count($servers); $i++) {
			$domain = $_POST['domain'];
			$curl   = curl_init();
			curl_setopt( $curl, CURLOPT_URL, $servers[$i]->domain );
			curl_setopt( $curl, CURLOPT_POST, 1 );
			curl_setopt( $curl, CURLOPT_POSTFIELDS, json_encode( [ 'url' => $domain ] ) );
			curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
			curl_setopt( $curl, CURLINFO_HEADER_OUT, true );
			curl_setopt( $curl, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json' ] );

			$server_output = curl_exec( $curl );
			curl_close ($curl);

			$result = json_decode($server_output, true);

			if ($result['status'] === 'success') {
				// Save id DB HERE.
				$data = $result['data']['data'];
				$pageTimings = $data['browserScripts'][0]['timings']['pageTimings'];

				$timestamp = $result['data']['dir'];
				$videoPath = $data['files']['video'][0];
				$screenshotPath = $data['files']['screenshot'][0];

				$serverResponseTime = $pageTimings['serverResponseTime'];
				$pageLoadTime = $pageTimings['pageLoadTime'];

				$newData = [
					"server_location" => $servers[$i]->location,
					"server_name" => $servers[$i]->domain,
					"hosting_name" => '-',
					"domain_addr" => $domain,
					"timestamp" => $timestamp,
					"video" => $videoPath,
					"screen_shot" => $screenshotPath,
					"server_response_time" => $serverResponseTime,
					"page_load_time" => $pageLoadTime,
					"batch_id" => $requestBatch
				];

				$newData['domain_ip'] = gethostbyname($domain);
				$wpdb->insert($speed_table_name, $newData);

				//	$cmd = "whois {$newData['ip']}";
				// echo shell_exec('whois 64.233.160.0');


				$newData['id'] = $wpdb->insert_id;
				$newData['imgPath'] = "{$servers[$i]->domain}/{$domain}/$timestamp/$screenshotPath";
				$newData['videoPath'] = "{$servers[$i]->domain}/{$domain}/$timestamp/$videoPath";

				array_push($allResults, $newData);
			} else {
				print_r(['error' => 'Could not retrieve data from all servers.']);
			}
		}


		$oldResutls = $wpdb->get_results("SELECT server_response_time, page_load_time FROM $speed_table_name");

		echo json_encode(['oldData' => $oldResutls, 'newData' => $allResults]);
		exit;
	} catch(Exception $exception) {
		print_r(['error' => 'Something went wrong in the server']);
	}

}

function vq_add_review_subscribers() {

	global $wpdb;

	$newSubscripber = [
		'name' => $_POST['name'],
		'email' => $_POST['email']
	];

	$subscriber_table = $wpdb->prefix . "review_subscribers";
	$wpdb->insert($subscriber_table, $newSubscripber);

	print_r($wpdb->insert_id);
	exit;
}

function vq_get_saved_speed_results() {
	$batchId = $_POST['batchId'];

	global $wpdb;
	$speed_table_name = $wpdb->prefix . "speed_results";

	$oldResutls = $wpdb->get_results("SELECT server_response_time, page_load_time FROM $speed_table_name WHERE batch_id != '$batchId'");
	$newResutls = $wpdb->get_results("SELECT * FROM $speed_table_name WHERE batch_id = '$batchId'");

	echo json_encode(['oldData' => $oldResutls, 'newData' => $newResutls]);
	exit;
}


// Actions
add_action( 'customize_register', 'vq_theme_customize_register' );
add_action( 'wp_enqueue_scripts', 'vq_enqueue_theme_resources' );
add_action( 'init', 'vq_register_theme_supports' );
add_action( 'init', 'vq_add_theme_default_pages' );
add_action( 'wp_ajax_nopriv_get_speed_results', 'vq_get_hosting_speed' );
add_action( 'wp_ajax_get_speed_results', 'vq_get_hosting_speed' );

add_action( 'wp_ajax_nopriv_get_saved_speed_results', 'vq_get_saved_speed_results' );
add_action( 'wp_ajax_get_saved_speed_results', 'vq_get_saved_speed_results' );


add_action( 'wp_ajax_nopriv_add_review_subscribers', 'vq_add_review_subscribers' );
add_action( 'wp_ajax_add_review_subscribers', 'vq_add_review_subscribers' );

add_action( 'admin_enqueue_scripts', 'vq_enqueue_custom_admin_style' );
