<?php

namespace Bookingor\Backend\Controller\Category;

use Bookingor\Backend\Controller\Subcategory\SubcategoryControl;

class CategoryControl
{

	private static $bookingorDb;
	/**
	 * Stores the table name for categories in the database.
	 *
	 * @var string
	 */
	public static $category_table;
	/**
	 * Stores the default image path.
	 *
	 * @var string
	 */
	public static $default_img;
	/**
	 * Stores the view icon path.
	 *
	 * @var string
	 */
	public static $view_icon;
	public static $dp_prefix = "bookingor_";
	/**
	 * Deletes a category from the database.
	 *
	 * This function checks if the category is already in use by any booked appointments.
	 * If it is not in use, it deletes the category from the database.
	 * If it is in use, it returns an error message.
	 *
	 * @throws None
	 * @return void
	 */
	public function bp_delete_category()
	{
		global $wpdb;
		self::$bookingorDb = $wpdb;
		$category = $wpdb->prefix . self::$dp_prefix . 'categories';
		$booked = $wpdb->prefix . self::$dp_prefix . 'booked_appointment';

		if (sanitize_text_field(wp_unslash(isset($_REQUEST["id"])))) {
			if (isset($_POST['nonce'])) {
				if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'bookingor_ajax_nonce')) {
					$response = [
						'status' => htmlspecialchars('error'),
						'message' => htmlspecialchars('Nonce verification failed.')
					];
				}
			}
			if (isset($_REQUEST['action'])) {
				if (isset($_POST['nonce'])) {
					if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'bookingor_ajax_nonce')) {
						$response = [
							'status' => htmlspecialchars('error'),
							'message' => htmlspecialchars('Nonce verification failed.')
						];
					}
				}
			}
			$id = stripslashes(filter_var(wp_unslash($_REQUEST["id"]), FILTER_SANITIZE_NUMBER_INT));
			$get_category_in_booking = self::$bookingorDb->get_results(
				$wpdb->prepare(
					"SELECT book_id, customer_get_id, duration_service, start_time, end_time, picked_date_end, picked_date, service_get_price,  discount_get_price,  paid_amount, payment_method, customer_time_zone, token_code, appoint_status, category_get_id, service_get_id, staff_get_id, location_get_id, updated_at, created_at FROM {$wpdb->prefix}bookingor_booked_appointment  WHERE category_get_id = %d",
					$id
				)
			);
			if (empty($get_category_in_booking)) {
				self::$bookingorDb->delete($category, array(
					'category_id' => $id
				));
				$response = [
					'status' => 'success',
					'message' => 'Category Deleted successfully.'
				];
				echo wp_json_encode($response);
				exit;
			} else {
				$response = [
					'status' => 'error',
					'message' => 'Category is already in use.'
				];
				echo wp_json_encode($response);
				exit;
			}
		}
	}
	/**
	 * Updates a category in the database.
	 *
	 * This function checks if the 'action' parameter is set in the $_REQUEST array.
	 * If it is, it updates the parent category in the database.
	 *
	 * @throws None
	 * @return void
	 */
	public function bp_update_category()
	{
		global $wpdb;
		self::$bookingorDb = $wpdb;
		$category = $wpdb->prefix . self::$dp_prefix . 'categories';
		// Check if the 'action' parameter is set in the $_REQUEST array
		if (isset($_REQUEST['action'])) {


			if (isset($_POST['nonce'])) {
				if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'bookingor_ajax_nonce')) {
					$response = [
						'status' => htmlspecialchars('error'),
						'message' => htmlspecialchars('Nonce verification failed.')
					];
					echo wp_json_encode($response);
				}
			}
			if (!current_user_can('manage_options')) {
				$response = [
					'status' => htmlspecialchars('error'),
					'message' => htmlspecialchars('You do not have permission.')
				];
				echo wp_json_encode($response);
				die();
			}

			//Update Parent Category
			self::$bookingorDb->update(
				$category,
				array(
					'category_name' => sanitize_text_field(wp_unslash($_POST['tcn_category_name'] ?? '')),
					'icon' => sanitize_text_field(wp_unslash($_POST['tcn_category_icon_id_update'] ?? '')),
					'status' => sanitize_text_field(wp_unslash($_POST['tcn_category_status'] ?? '')),
				),
				array('category_id' => sanitize_text_field(wp_unslash($_POST['category_id'] ?? '')))
			);
			// Return the success message as a JSON-encoded response
			$response = [
				'status' => 'success',
				'message' => "Category Updated successfully"
			];
			echo wp_json_encode($response);
			exit;
		}
	}
	/**
	 * Adds a category to the database.
	 *
	 * This function checks if the 'action' parameter is set in the $_REQUEST array.
	 * If it is, it inserts a new category into the database with the provided category name, icon, and status.
	 * If the 'bookingor-subcategory-addon/bookingor-subcategory-addon.php' plugin is active, it also adds a subcategory to the database.
	 *
	 * @throws None
	 * @return void
	 */
	public function bp_add_category()
	{
		global $wpdb;
		self::$bookingorDb = $wpdb;
		$subcategory = $wpdb->prefix . self::$dp_prefix . 'subcategory';
		$category = $wpdb->prefix . self::$dp_prefix . 'categories';
		if (isset($_REQUEST['action'])) {


			if (isset($_POST['nonce'])) {
				if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'bookingor_ajax_nonce')) {
					$response = [
						'status' => htmlspecialchars('error'),
						'message' => htmlspecialchars('Nonce verification failed.')
					];
					echo wp_json_encode($response);
				}
			}
			if (!current_user_can('manage_options')) {
				$response = [
					'status' => htmlspecialchars('error'),
					'message' => htmlspecialchars('You do not have permission.')
				];
				echo wp_json_encode($response);
				die();
			}

			$category_name   = sanitize_text_field(wp_unslash($_POST['tcn_category_name'] ?? ''));
			$category_icon   = sanitize_text_field(wp_unslash($_POST['tcn_category_icon_id'] ?? ''));
			$category_status = sanitize_text_field(wp_unslash($_POST['tcn_category_status'] ?? ''));
			update_option("bookingor_settings_category_active", "on");
			self::$bookingorDb->insert(
				$category,
				array(
					'category_name' => $category_name,
					'icon' => $category_icon,
					'status' => $category_status,
				),
				array(
					'%s',
					'%s',
					'%s',
					'%s'
				)
			);
			$id = $wpdb->insert_id;
			if (class_exists('Bookingor\Backend\Controller\Subcategory\SubcategoryControl')) {
				$subcategoryHandler =  SubcategoryControl::bp_add_subcategory();
				$subcategoryHandler->bp_add_subcategory();
			}
			$response = [
				'status' => 'success',
				'message' => 'Category Added successfully.'
			];
			echo wp_json_encode($response);
			exit;
		}
	}
	/**
	 * Retrieves the category view data.
	 *
	 * This function checks if the bookingor-subcategory-addon plugin is active.
	 * If active, it retrieves the category data with subcategories.
	 * Otherwise, it retrieves the category data without subcategories.
	 *
	 * @global wpdb $wpdb WordPress database object.
	 * @return array Category view data.
	 */
	public static function bp_category_view()
	{
		self::$view_icon = plugin_dir_url(dirname(dirname(__FILE__))) . 'assets/images/cate-serv.jpg';
		self::$default_img = plugin_dir_url(dirname(dirname(__FILE__))) . 'assets/images/cate-serv-1.jpg';
		global $wpdb;
		self::$bookingorDb = $wpdb;
		$category     = $wpdb->prefix . self::$dp_prefix . 'categories';
		$subcategory     = $wpdb->prefix . self::$dp_prefix . 'subcategory';

		if (class_exists('Bookingor\Backend\Controller\Subcategory\SubcategoryControl')) {
			return self::$category_table = SubcategoryControl::bp_category_and_subcategory_view();
		} else {
			return self::$category_table = self::$bookingorDb->get_results(
				$wpdb->prepare(
					"SELECT c.category_id, c.category_name, c.icon, c.status
					 FROM %1\$s AS c
					 GROUP BY c.category_id",
					$category
				)
			);
		}
	}
	/**
	 * Retrieves a specific category based on the provided category ID.
	 *
	 * This function checks if the 'category_id' parameter is set in the $_REQUEST array.
	 * If it is, it retrieves the category data from the database and returns it in JSON format.
	 * If the 'action' parameter is set, it also retrieves the category name, icon, and status.
	 *
	 * @global wpdb $wpdb WordPress database object.
	 * @param int $category_id The ID of the category to retrieve.
	 * @throws None
	 * @return array Category data.
	 */
	public function bp_get_category()
	{
		$response  = new \stdclass();
		$response->success = false;
		global $wpdb;
		self::$bookingorDb = $wpdb;
		$subcategory = $wpdb->prefix . self::$dp_prefix . 'subcategory';
		$category = $wpdb->prefix . self::$dp_prefix . 'categories';
		$category_id = isset($_REQUEST['category_id']) ? intval($_REQUEST['category_id']) : 0;


		if (isset($_POST['nonce'])) {
			if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'bookingor_ajax_nonce')) {
				$response = [
					'status' => htmlspecialchars('error'),
					'message' => htmlspecialchars('Nonce verification failed.')
				];
				echo wp_json_encode($response);
			}
		}
		if (class_exists('Bookingor\Backend\Controller\Subcategory\SubcategoryControl')) {
			$subcategoryHandler =  SubcategoryControl::bp_get_category_and_subcategory();
			$subcategoryHandler->bp_get_category_and_subcategory();
		} else {
			$response = self::$bookingorDb->get_results(
				$wpdb->prepare(
					"SELECT category_id, category_name, icon, status FROM %1\$s WHERE category_id = %2\$s",
					$category,
					$category_id
				)
			);
		}
		echo wp_json_encode($response);
		die;
	}
}
