<?php

namespace CarDealerPress\Includes\Database;

use CarDealerPress\includes\functions\Logger;
use CarDealerPress\Includes\Helpers\Option;

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

class Update_Delete {
	use Logger;

	public static $admin_options;
	public static $theme_options;

	private static $wpdb;
	private static $blog;

	public function __construct() {
		global $wpdb;
		self::$wpdb          = $wpdb;
		self::$theme_options = Option::get_cdp_theme_options();
		self::$admin_options = Option::get_cdp_admin_options();
		self::$blog          = get_current_blog_id();
	}

	public function remove_company_id_from_table( $args ) {
		$where        = array(
			'blog_id'   => self::$blog,
			'dealer_id' => $args['dealer_id'],
		);
		$where_format = array( '%d', '%d' );
		// @codingStandardsIgnoreStart
		self::$wpdb->delete( $args['table'] , $where, $where_format );
		// @codingStandardsIgnoreEnd
	}

	public function remove_inventory_import_duplicates($args) {
		$dealer_id = $args['dealer_id'];
		$company_id = $args['company_id'];
		// Removes Possible Duplicates.
		$sql = 'DELETE FROM ' . CDP_INVENTORY_IMPORT_TABLE . ' WHERE id in ( SELECT max_id from ( SELECT max(id) as max_id FROM ' . CDP_INVENTORY_IMPORT_TABLE . ' WHERE vms_id IN ( SELECT vms_id FROM (SELECT vms_id, count(*) AS duplicates FROM ' . CDP_INVENTORY_IMPORT_TABLE . ' WHERE company_id = ' . $company_id . ' AND blog_id = ' . self::$blog . ' AND dealer_id = ' . $dealer_id . ' GROUP BY vms_id ) AS z where z.duplicates > 1 ) GROUP BY vms_id ) AS a )';
		// @codingStandardsIgnoreStart
		self::$wpdb->query( $sql );
		// @codingStandardsIgnoreEnd
	}

	public function update_companies_table_with_last_modified($args) {
		$dealer_id = $args['dealer_id'];

		$update_values = array();
		if (isset($args['inventory_api_last_modified'])) {
			$update_values['inventory_api_last_modified'] = $args['inventory_api_last_modified'];
		}

		if (isset($args['inventory_last_checked'])) { //Last Checked API
			$update_values['inventory_last_checked'] = $args['inventory_last_checked'];
		}

		if (isset($args['inventory_last_updated'])) { //Site Last Updated
			$update_values['inventory_last_updated'] = $args['inventory_last_updated'];
		}

		$update_format = array_fill(0, count($update_values), '%s'); // Dynamically generate format placeholders

		$where_values = [
			'blog_id'   => self::$blog,
			'dealer_id' => $dealer_id
		];

		$where_format = ['%d', '%d'];

		// @codingStandardsIgnoreStart
		self::$wpdb->update(CDP_COMPANIES, $update_values, $where_values, $update_format, $where_format);
		// @codingStandardsIgnoreEnd

	}

	public function remove_dealer_id_from_cdp_tables( $dealer_id ) {
		$this->remove_dealer_id_from_cdp_data_table( $dealer_id );
		$this->remove_dealer_id_from_cdp_companies_table( $dealer_id );
		$this->remove_dealer_id_from_table(
			array(
				'table'     => CDP_INVENTORY_TABLE,
				'dealer_id' => $dealer_id,
			)
		);
		$this->remove_dealer_id_from_table(
			array(
				'table'     => CDP_INVENTORY_IMPORT_TABLE,
				'dealer_id' => $dealer_id,
			)
		);
	}

	public function remove_dealer_id_from_cdp_data_table( $dealer_id ) {
		// Remove Data from CDP Data.
		$this->append_log( array( 'message' => 'CDP Message: Removing dealer ' . $dealer_id . ' from CDP Data Table' ) );
		$where        = array(
			'blog_id'   => self::$blog,
			'data_key'  => 'dealer',
			'dealer_id' => $dealer_id,
		);
		$where_format = array( '%d', '%s', '%d' );
		// @codingStandardsIgnoreStart
		self::$wpdb->delete( CDP_DATA, $where, $where_format );
		// @codingStandardsIgnoreEnd
		$where        = array(
			'blog_id'  => self::$blog,
			'data_key' => 'disclaimer',
		);
		$where_format = array( '%d', '%s' );
		// @codingStandardsIgnoreStart
		self::$wpdb->delete( CDP_DATA, $where, $where_format );
		// @codingStandardsIgnoreEnd
	}

	public function remove_dealer_id_from_cdp_companies_table( $dealer_id ) {
		$this->append_log( array( 'message' => 'CDP Message: Removing dealer ' . $dealer_id . ' from CDP Companies Table' ) );
		// check for automall dealer
		$automall_check = false;
		$company = ( new Requests() )->cdp_db_init( 'company' );
		$company_db        = isset($company) ? $company[0] : array();
		$dealers        = empty( $company_db['automalls'] ) ? array() : $company_db['automalls'];
		if ( count( $dealers ) > 1 ) {
			$automall_check = true;
		}
		if ( $automall_check ) {
			$where        = array(
				'blog_id'   => self::$blog,
				'company_id' => $dealer_id,
			);
		} else {
			$where = array(
				'blog_id'   => self::$blog,
				'dealer_id' => $dealer_id,
			);
		}
		$where_format = array( '%d', '%s', '%d' );
		// @codingStandardsIgnoreStart
		self::$wpdb->delete( CDP_COMPANIES, $where, $where_format );
		// @codingStandardsIgnoreEnd
	}

	public function remove_dealer_id_from_table( $args ) {
		$this->append_log( array( 'message' => 'CDP Message: Removing dealer ' . $args['dealer_id'] . ' from Table ' . $args['table'] . ' for blog ' . self::$blog ) );
		$where        = array(
			'blog_id'   => self::$blog,
			'dealer_id' => $args['dealer_id'],
		);
		$where_format = array( '%d', '%d' );
		// @codingStandardsIgnoreStart
		self::$wpdb->delete( $args['table'] , $where, $where_format );
		// @codingStandardsIgnoreEnd
	}

	public function reset_tables( $dealer_id ) {
		$this->append_log( array( 'message' => 'CDP Message: Dealer Id has been changed or a reset has been triggered, truncating all data tables from blog site:' . self::$blog ) );
		$this->remove_dealer_id_from_cdp_data_table( $dealer_id );
		$this->remove_dealer_id_from_cdp_companies_table( $dealer_id );
		// @codingStandardsIgnoreStart
		self::$wpdb->query( 'TRUNCATE '. CDP_INVENTORY_TABLE );
		self::$wpdb->query( 'TRUNCATE ' . CDP_INVENTORY_IMPORT_TABLE );
		// @codingStandardsIgnoreEnd
	}

	public function remove_all_cdp_tables() {
		global $wpdb;
		// Remove Data from CDP Data.
			$tables = array(
				$wpdb->prefix .'cdp_data',
				$wpdb->prefix .'cdp_companies',
				$wpdb->prefix .'cdp_inventory',
				$wpdb->prefix .'cdp_inventory_import',
			);
			foreach ( $tables as $table ) {
				// @codingStandardsIgnoreStart
				$query                = self::$wpdb->query( "DROP TABLE IF EXISTS $table" );
				error_log('CDP Message: Removing table: ' . $table .', result: ' . $query );
				// @codingStandardsIgnoreEnd
			}
	}

}
