<?php

namespace CarDealerPress\includes\helpers;

use CarDealerPress\Includes\Database\Inventory_Handler;
use CarDealerPress\Includes\Database\Requests;
use CarDealerPress\includes\functions\Logger;
use CarDealerPress\includes\helpers\helpers as helpers;

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

class Multi_Request {
	use Logger;

	private static $wpdb;
	private $curl_url;
	public $company_id;
	private $dealer_id;
	private $current_inventory_version = '5.9.2203.00';
	private $current_company_version   = '6.0.2209.00';
	private $retry_limit               = 5;
	private $retry                     = 0;
	private static $blog               = 1;
	private $admin_options;
	private $theme_options;
	private $inventory_handler;
	/**
	 * @var int
	 */
	private $job_start_time;
	/**
	 * @var string
	 */
	private $api_call;

	public function __construct() {
		global $wpdb;
		self::$wpdb = $wpdb;
		self::$blog = get_current_blog_id();
		$this->set_option_variables();
		$this->inventory_handler = new Inventory_Handler();


	}

	public function set_option_variables() {
		$this->job_start_time = time();
		$this->admin_options  = Option::get_cdp_admin_options();
		$this->theme_options  = Option::get_cdp_theme_options();
		$this->company_id     = helpers::company_id();
		$nonce_check = isset( $_REQUEST['nonce'] ) && wp_verify_nonce( sanitize_key( $_REQUEST['nonce'] ), 'cdp-nonce' );
		if ( isset( $_POST['cdp_Admin_post_action'] ) && 'dealerChange' === $_POST['cdp_Admin_post_action']  && $nonce_check ) {
			$safe = helpers::sanitize_get( $_POST );
			if ( isset( $safe['cdp_Admin_post_previous_id'] ) && ! empty( $safe['cdp_Admin_post_new_value'] ) ) {
				$this->company_id = wp_unslash($safe['cdp_Admin_post_new_value']);
			}
		}

		$this->api_call = isset( $this->admin_options['admin']['help']['host'] ) ? urldecode( $this->admin_options['admin']['help']['host'] ) : '';
		if ( $this->company_id ) {
			$this->disclaimer_check();
		}
	}



	public function disclaimer_check() {

		$query   = 'Select * from ' . CDP_DATA . ' where blog_id = "' . self::$blog . '" and data_key = "disclaimer" ';
		// @codingStandardsIgnoreStart
		$results = self::$wpdb->get_results( self::$wpdb->prepare( $query, ARRAY_A ));
		// @codingStandardsIgnoreEnd
		if ( empty( $results ) ) {
			$api_params    = '/' . $this->company_id . '/inventory/vehicles.json?per_page=1';
			$response      = Remote_Requests::http_get_file( $api_params );
			$response_code = $response['status_code'];
			if ( 200 === $response_code ) {
				$response_data = isset( $response['body'] ) ? json_decode( wp_kses_data( $response['body'] ) ) : array();
				if ( ! empty( $response_data[0]->disclaimer ) ) {
					$table  = CDP_DATA;
					$data   = array(
						'blog_id'    => self::$blog,
						'data_key'   => 'disclaimer',
						'data_value' => $response_data[0]->disclaimer,
					);
					$format = array( '%d', '%s', '%s' );
					// @codingStandardsIgnoreStart
					self::$wpdb->insert( $table, $data, $format );
					// @codingStandardsIgnoreEnd
				}
			}
		}
	}

	public function manual_dealer_check( $manual_id ) {

		$results = array();
		if ( $manual_id ) {
			$query       = 'Select * from %s where blog_id = %d and data_key = "dealer" and dealer_id = %d';
			$query_params = array( CDP_DATA, self::$blog, $manual_id );
			// @codingStandardsIgnoreStart
			$query_prepare                = self::$wpdb->prepare( $query, $query_params );
			$data_dealer = self::$wpdb->get_results( $query_prepare, ARRAY_A );
			// @codingStandardsIgnoreEnd
			if ( empty( $data_dealer ) ) {
				$api_params    = '/api/companies/' . $manual_id;
				$response      = Remote_Requests::http_get_file( $api_params );
				$response_code = $response['status_code'];
				if ( 200 === $response_code ) {
					$results['found'] = 'Company ID added to company. Will import momentarily.';
				} else {
					$results['error'] = 'Company ID not found. Please enter a different ID.';
				}
			} else {
				$results['error'] = 'Company ID already manually added. Please enter a different ID.';
			}
		} else {
			$results['error'] = 'Company ID not found. Please enter a different ID.';
		}

		return $results;
	}

	public function run_inventory_if_inventory_table_empty( $dealer ) {
		// Run Inventory if Inventory Table is Empty for Dealer Inventory
		$query_prepare        = 'select count(*) Inv_Total from ' . CDP_INVENTORY_TABLE . ' where blog_id = %d and dealer_id = %d';
		$query_params_prepare = array( self::$blog, $dealer['dealer_id'] );
		// @codingStandardsIgnoreStart
		$query                = self::$wpdb->prepare( $query_prepare, $query_params_prepare );
		$vehicle_count        = self::$wpdb->get_results( $query, ARRAY_A );
		// @codingStandardsIgnoreEnd
		if ( 0 === $vehicle_count[0]['Inv_Total'] ) {
			$this->append_log( array( 'message' => 'CDP Message: Vehicle Count 0 | Dealer - ' . $dealer['dealer_id'] ) );
			$this->inventory_handler->init_inventory_handler( $dealer['dealer_id'] );
		}
	}

}
