<?php

namespace CommerceBird\API;

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

use WP_REST_Response;
use WP_REST_Server;
use WP_REST_Controller;
use CMBIRD_API_Handler_Zoho;
/**
 * REST API controller for CommerceBird custom endpoints.
 *
 * Handles product SKUs, purchase order automation settings, and Zoho CRM status.
 */
class CMBird_APIs extends WP_REST_Controller {

	/**
	 * REST API namespace prefix.
	 *
	 * @var string
	 */
	protected $prefix = 'wc/v3';
	/**
	 * REST API base route.
	 *
	 * @var string
	 */
	protected $rest_base = 'cmbird';
	/**
	 * An empty response array used for initializing REST responses.
	 *
	 * @var array
	 */
	protected $empty_response = array();

	/**
	 * Register REST API routes.
	 *
	 * Registers the following endpoints:
	 * - /wc/v3/cmbird/products-skus: GET products with SKUs.
	 * - /wc/v3/cmbird/purchase-order-automation: POST and GET purchase order automation settings.
	 * - /wc/v3/cmbird/zohocrm-status: GET Zoho CRM status.
	 *
	 * @since 2.0.0
	 */
	public function __construct() {
		register_rest_route(
			$this->prefix,
			'/' . $this->rest_base . '/products-skus/',
			array(
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => array( $this, 'cmbird_get_all_product_with_skus' ),
				'permission_callback' => array( $this, 'permission_check' ),
			)
		);
		// register route for setting purchase order automation settings.
		register_rest_route(
			$this->prefix,
			'/' . $this->rest_base . '/purchase-order-automation/',
			array(
				'methods'             => WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'cmbird_set_purchase_order_automation_settings' ),
				'permission_callback' => array( $this, 'permission_check' ),
			)
		);
		// register route for getting purchase order automation settings.
		register_rest_route(
			$this->prefix,
			'/' . $this->rest_base . '/purchase-order-automation/',
			array(
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => array( $this, 'cmbird_get_purchase_order_automation_settings' ),
				'permission_callback' => array( $this, 'permission_check' ),
			)
		);

		register_rest_route(
			$this->prefix,
			'/' . $this->rest_base . '/zohocrm-status',
			array(
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => array( $this, 'get_zcrm_token' ),
				'permission_callback' => array( $this, 'permission_check' ),
			)
		);
	}

	/**
	 * Check if a given request has access to get items.
	 */
	public function permission_check() {
		return current_user_can( 'manage_woocommerce' );
	}

	/**
	 * Status API of get_zcrm_token
	 *
	 * @return WP_REST_Response|\WP_Error
	 */
	public function get_zcrm_token(): WP_REST_RESPONSE {
		$rest_response = new WP_REST_Response();
		$rest_response->set_data( $this->empty_response );
		$rest_response->set_status( 400 );
		$zoho_crm_url             = get_option( 'cmbird_zoho_crm_url' );
		$get_url                  = $zoho_crm_url . 'crm/v7/org';
		$execute_curl_call_handle = new CMBIRD_API_Handler_Zoho();
		$json                     = $execute_curl_call_handle->execute_curl_call_get( $get_url );
		if ( isset( $json->org ) && is_array( $json->org ) ) {
			$rest_response->set_data(
				array(
					'status' => 'success',
					'org'    => $json->org[0],
				)
			);
			$rest_response->set_status( 200 );
		} else {
			$rest_response->set_data( 'connection is not yet setup' );
			$rest_response->set_status( 400 );
		}
		return rest_ensure_response( $rest_response );
	}


	public function cmbird_get_all_product_with_skus(): WP_REST_RESPONSE {
		$rest_response = new WP_REST_Response();
		$rest_response->set_data( $this->empty_response );
		$rest_response->set_status( 200 );

		global $wpdb;

		// Try to get from cache first.
		$cache_key = 'cmbird_product_skus_list';
		$results   = wp_cache_get( $cache_key, 'commercebird' );

		if ( false === $results ) {
			// Query to fetch product IDs and SKUs directly from the database.
			$results = $wpdb->get_results(
				"
				SELECT p.ID as product_id, pm.meta_value as sku, p.post_type as product_type
        FROM {$wpdb->posts} p
        LEFT JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id AND pm.meta_key = '_sku'
        WHERE p.post_type IN ('product', 'product_variation') "
			);
			wp_cache_set( $cache_key, $results, 'commercebird', 5 * MINUTE_IN_SECONDS );
		}       $rest_response->set_data( $results );

		return rest_ensure_response( $rest_response );
	}

	/**
	 * Set purchase order automation settings.
	 *
	 * This endpoint expects a JSON payload in the following format:
	 *
	 * {
	 *   "settings": {
	 *     "enable_automation": bool,        // Whether to enable automation for creating purchase orders.
	 *     "cron_interval": string,          // WordPress cron interval (e.g., 'hourly', 'twicedaily', 'daily').
	 *     "product_stock_status": array,    // Array of stock statuses to monitor (e.g., 'low_stock', 'out_of_stock').
	 *     "send_to_vendor": bool            // Whether to send purchase orders to vendors automatically.
	 *   }
	 * }
	 *
	 * @param WP_REST_Request $request The REST API request object.
	 * @return WP_REST_Response A REST response indicating success or failure.
	 */
	public function cmbird_set_purchase_order_automation_settings( $request ) {
		$rest_response = new WP_REST_Response();
		$rest_response->set_data( $this->empty_response );
		$rest_response->set_status( 200 );

		if ( ! isset( $request['settings'] ) ) {
			return rest_ensure_response(
				array(
					'status'  => false,
					'message' => 'Settings not found',
				)
			);
		}

		$settings = $request->get_param( 'settings' );

		if ( ! empty( $settings ) ) {
			update_option( 'cmbird_po_automation_settings', $settings, false );

			// Handle cron job scheduling or clearing.
			if ( isset( $settings['enable_automation'] ) && true === $settings['enable_automation'] ) {
				$interval = $settings['cron_interval'] ?? 'daily';

				// Clear existing to prevent duplicates.
				wp_clear_scheduled_hook( 'cmbird_purchase_order_auto' );

				if ( ! wp_next_scheduled( 'cmbird_purchase_order_auto' ) ) {
					wp_schedule_event( time(), $interval, 'cmbird_purchase_order_auto' );
				}
			} else {
				// Disable automation: clear cron.
				wp_clear_scheduled_hook( 'cmbird_purchase_order_auto' );
			}

			return rest_ensure_response(
				array(
					'status'  => true,
					'message' => 'Settings updated successfully',
				)
			);
		}

		return rest_ensure_response(
			array(
				'status'  => false,
				'message' => 'Settings not found',
			)
		);
	}

	/**
	 * Get purchase order automation settings
	 *
	 * @param WP_REST_Request $request The REST API request object.
	 * @return WP_REST_Response A REST response containing the settings or an error message.
	 */
	public function cmbird_get_purchase_order_automation_settings( $request ) {
		$rest_response = new WP_REST_Response();
		$rest_response->set_data( $this->empty_response );
		$rest_response->set_status( 200 );

		$settings = get_option( 'cmbird_po_automation_settings' );

		if ( ! empty( $settings ) ) {
			return rest_ensure_response(
				array(
					'status' => true,
					'data'   => $settings,
				)
			);
		}

		return rest_ensure_response(
			array(
				'status'  => false,
				'message' => 'Settings not found',
			)
		);
	}
}
