<?php

namespace CarDealerPress\Includes\Database;

use CarDealerPress\includes\functions\Logger;
use CarDealerPress\includes\helpers\helpers as helpers;
use CarDealerPress\Includes\Helpers\Option;
use CarDealerPress\Includes\Helpers\Remote_Requests;

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

class Company_Handler {
	use Logger;

	private static $blog_id;
	private Requests $db_requests;
	private $admin_options;

	public function __construct() {
		self::$blog_id = get_current_blog_id();
		$this->set_option_variables();
	}

	public function set_option_variables() {
		$this->admin_options = Option::get_cdp_admin_options();
		$this->db_requests   = new Requests();
	}
	public function init_company_handler( $args = array() ) {
		$company_id   = $args['company_id'] ?? helpers::company_id();
		$purge        = $args['purge'] ?? false;
			if ( ! get_transient( 'cdp_company_processing_' . self::$blog_id ) ) {
					set_transient( 'cdp_company_processing_' . self::$blog_id, 'Running', 60 );
				if ( $company_id ) {
					// need to check if dealer exists in companies table
					// need to pass the company id on second call, to get a result.
					$db_check_dealer = $this->db_requests->cdp_company_dealer_request( $company_id, $company_id );
					switch (true) {
						case ($db_check_dealer):
							if (!empty($db_check_dealer[0]['automalls']) ) { // check for automalls
								$pre_check_automalls = $db_check_dealer[0]['automalls'];

								$this->check_api_and_update_company( array('company_id' => $company_id, 'dealer' => $db_check_dealer[0] ) );

								$post_db_check_dealer = $this->db_requests->cdp_company_dealer_request( $company_id, $company_id);
								$post_check_automalls = $post_db_check_dealer[0]['automalls'] ?? array();
								$fullDiff = array_merge( array_diff( $pre_check_automalls, $post_check_automalls ), array_diff( $post_check_automalls, $pre_check_automalls ) );
								// if the id is found in current then it needs to be removed, if it isn't found it needs to be added.
								if ( ! empty( $fullDiff ) ) {
									foreach ( $fullDiff as $index => $automall_id ) {
										if ( ! empty( $result ) ) {
											$this->append_log( array( 'message' => 'CDP Message: Dealer ' . $automall_id . ' missing from company | Adding to company table' ) );
											$this->check_api_and_update_company( array( 'company_id' => $company_id, 'automall_id' => $automall_id ) );
											// populate inventory tables with new dealer
											( new Inventory_Handler() )->init_inventory_handler( $automall_id, $purge );
										} else {
											$this->append_log( array( 'message' => 'CDP Message: Dealer ' . $automall_id . ' being removed from companies as no longer found in Automall' ) );
											( new Update_Delete() )->remove_dealer_id_from_cdp_tables( $automall_id );
										}
									}
								} else { // no changes to automall, need to account for initial call, and normal updates
									foreach ( $post_check_automalls as $index => $automall_id ) {
										$result = $this->db_requests->cdp_company_dealer_request( $automall_id );
										if ( empty( $result ) ) { // initial time will be empty
											$this->check_api_and_update_company( array( 'company_id' => $company_id, 'automall_id' => $automall_id ) );
											// populate inventory tables with new dealer
											( new Inventory_Handler() )->init_inventory_handler( $automall_id, $purge );
										} else {
											$this->append_log( array( 'message' => 'CDP Message: Checking Dealer automall dealer: ' . $automall_id .' for company updates.') );
											$this->check_api_and_update_company( array( 'company_id' => $company_id, 'automall_id' => $automall_id, 'dealer' => $result[0] ) );
										}
									}
								}
							}
						break;
						case (empty($db_check_dealer)): // no dealer in companies table
							$this->append_log( array( 'message' => 'CDP Message: Initial Populating companies table ' . $company_id ) );
							$this->check_api_and_update_company( array('company_id' => $company_id) );  // validate company and populate company table
							// re-run to check for automalls
							delete_transient( 'cdp_company_processing_' . self::$blog_id );
							$this->init_company_handler(array('company_id' => $company_id));
							break;
					}
				}
				delete_transient( 'cdp_company_processing_' . self::$blog_id );
			}

	}

	public function check_for_company_update() { //in Main
		$this->append_log( array( 'message' => 'CDP Message: Company Handler Check for Company Update' ) );
		if ( false === ( get_transient( 'cdp_check_for_company_update_' . self::$blog_id ) ) ) {
			set_transient( 'cdp_check_for_company_update_' . self::$blog_id, 'Running', 60 );
			$companies = $this->db_requests->cdp_company_request();
			if ( $companies ) {
				$this->append_log( array( 'message' => 'CDP Message: debug Company Handler Check for Company Update DB companies ' . json_encode( $companies ) ) );
				foreach ( $companies as $key => $dealer ) {
					$this->check_api_and_update_company( array('dealer' => $dealer) );
				}
			}
			delete_transient( 'cdp_check_for_company_update_' . self::$blog_id );
		}
	}

	public function check_api_and_update_company($args){
		$company_id = $args['company_id'] ?? helpers::company_id();
		$db_last_updated = $args['dealer']['last_updated'] ?? null;
		$automall_id = $args['automall_id'] ?? null;
		$company_or_dealer_id = $automall_id ?? $company_id;

		$response      = Remote_Requests::check_for_valid_company_id( $company_or_dealer_id );
		$response_code = $response['status_code'];
		if ( 200 === $response_code ) {
			$response_data = isset( $response['body'] ) ? json_decode( wp_kses_data( $response['body'] ) ) : array();
			// Update Company entry if new or update needed.
			if (!$db_last_updated){
				$this->append_log( array( 'message' => 'CDP Message: Company or Dealer ID ' . $company_or_dealer_id . ' inserted first time' ) );
				( new Inserts() )->populate_companies_table(
					array(
						'data'       => $response_data,
						'type'       => 'insert',
						'company_id' => $company_id,
					)
				);
				return;
			}
			$date_check = strtotime( $response_data->updated ) > intval( $db_last_updated );
			if ( $date_check ) {
				$this->append_log( array( 'message' => 'CDP Message: Company Company/Dealer ID ' . $company_or_dealer_id . ' automatically updated' ) );
				( new Inserts() )->populate_companies_table(
					array(
						'data'       => $response_data,
						'type'       => 'update',
						'company_id' => $company_id,
					)
				);
			}
		} else {
			$this->append_log( array( 'message' => 'CDP Message: Whoops something went wrong: ' . $company_or_dealer_id  ) );
		}
	}
}
