<?php
/**
 * Product Synchronization Manager Class
 *
 * @package ShopExplorer\Modules
 * @since 1.0.0
 */

namespace SHOPEXPLORER\Modules;

use SHOPEXPLORER\Models\ProductDataModel;
use SHOPEXPLORER\Database\DatabaseManager;
use SHOPEXPLORER\Exceptions\SyncException;
use SHOPEXPLORER\Auth\AuthenticationManager;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Product Synchronization Manager class
 *
 * Handles product synchronization operations
 *
 * @since 1.0.0
 */
class SHOPEX_ProductSyncManager {

	/**
	 * Database manager instance
	 *
	 * @var DatabaseManager
	 */
	private $database_manager;

	/**
	 * Authentication manager instance
	 *
	 * @var AuthenticationManager
	 */
	private $auth_manager;

	/**
	 * Product manager instance
	 *
	 * @var ProductManager
	 */
	private $product_manager;

	/**
	 * Real-time sync enabled
	 *
	 * @var bool
	 */
	private $real_time_sync = true;

	/**
	 * Constructor
	 */
	public function __construct() {
		$this->database_manager = new DatabaseManager();
		$this->auth_manager = new AuthenticationManager();
		$this->product_manager = new ProductManager();
		$this->init_hooks();
	}

	/**
	 * Initialize WordPress hooks for real-time sync
	 */
	private function init_hooks() {
		if ( $this->real_time_sync ) {
			// Hook into WooCommerce product events
			add_action( 'woocommerce_update_product', [ $this, 'on_product_update' ], 20, 1 );
			add_action( 'woocommerce_new_product', [ $this, 'on_product_create' ], 20, 1 );
			add_action( 'woocommerce_delete_product', [ $this, 'on_product_delete' ], 20, 1 );

			// Hook into stock changes
			add_action( 'woocommerce_product_set_stock', [ $this, 'on_stock_change' ], 20, 1 );
			add_action( 'woocommerce_variation_set_stock', [ $this, 'on_stock_change' ], 20, 1 );

			// Hook into price changes
			add_action( 'woocommerce_product_object_updated_props', [ $this, 'on_product_props_update' ], 20, 2 );
		}
	}

	/**
	 * Sync products to database (No longer available)
	 *
	 * @param array  $product_ids Array of product IDs to sync
	 * @param string $direction Sync direction
	 * @param array  $options Sync options
	 * @return array
	 */
	public function sync_products( $product_ids = [], $direction = 'to_database', $options = [] ) {
		// External sync functionality has been removed
		return [
			'success' => false,
			'message' => __( 'External sync functionality is no longer available.', 'shop-explorer' ),
		];
	}

	/**
	 * Handle product creation event
	 *
	 * @param int $product_id Product ID
	 */
	public function on_product_create( $product_id ) {
		if ( ! $this->real_time_sync ) {
			return;
		}

		try {
			// Store product data in database
			$product = $this->product_manager->get_product( $product_id );
			if ( $product ) {
				$this->database_manager->store_product( $product );
			}
		} catch ( \Exception $e ) {
			error_log( 'Product sync error on create: ' . $e->getMessage() );
		}
	}

	/**
	 * Handle product update event
	 *
	 * @param int $product_id Product ID
	 */
	public function on_product_update( $product_id ) {
		if ( ! $this->real_time_sync ) {
			return;
		}

		try {
			// Update product data in database
			$product = $this->product_manager->get_product( $product_id );
			if ( $product ) {
				$this->database_manager->update_product( $product );
			}
		} catch ( \Exception $e ) {
			error_log( 'Product sync error on update: ' . $e->getMessage() );
		}
	}

	/**
	 * Handle product deletion event
	 *
	 * @param int $product_id Product ID
	 */
	public function on_product_delete( $product_id ) {
		if ( ! $this->real_time_sync ) {
			return;
		}

		try {
			// Mark product as deleted in database
			$this->database_manager->mark_product_deleted( $product_id );
		} catch ( \Exception $e ) {
			error_log( 'Product sync error on delete: ' . $e->getMessage() );
		}
	}

	/**
	 * Handle stock change event
	 *
	 * @param \WC_Product $product WooCommerce product
	 */
	public function on_stock_change( $product ) {
		if ( ! $this->real_time_sync || ! $product instanceof \WC_Product ) {
			return;
		}

		try {
			$product_id = $product->get_id();
			$stock_quantity = $product->get_stock_quantity();

			// Update stock in database
			$this->database_manager->update_product_stock( $product_id, $stock_quantity );
		} catch ( \Exception $e ) {
			error_log( 'Product stock sync error: ' . $e->getMessage() );
		}
	}

	/**
	 * Handle product properties update
	 *
	 * @param \WC_Product $product WooCommerce product
	 * @param array       $updated_props Updated properties
	 */
	public function on_product_props_update( $product, $updated_props ) {
		if ( ! $this->real_time_sync || ! $product instanceof \WC_Product ) {
			return;
		}

		// Check if price-related properties were updated
		$price_props = [ 'regular_price', 'sale_price', 'price' ];
		$price_updated = array_intersect( $price_props, $updated_props );

		if ( ! empty( $price_updated ) ) {
			$this->on_product_update( $product->get_id() );
		}
	}

	/**
	 * Get field settings (No longer available)
	 *
	 * @return array
	 */
	public function get_field_settings() {
		// External sync field settings are no longer available
		return [
			'success' => false,
			'message' => __( 'External sync field settings are no longer available.', 'shop-explorer' ),
		];
	}

	/**
	 * Update field settings (No longer available)
	 *
	 * @param array $field_settings Field settings
	 * @return array
	 */
	public function update_field_settings( $field_settings ) {
		// External sync field settings are no longer available
		return [
			'success' => false,
			'message' => __( 'External sync field settings are no longer available.', 'shop-explorer' ),
		];
	}

	/**
	 * Sync all products (No longer available)
	 *
	 * @param string $spreadsheet_id Spreadsheet ID
	 * @param string $sheet_name Sheet name
	 * @return array
	 */
	public function sync_all_products( $spreadsheet_id, $sheet_name ) {
		// External sync functionality has been removed
		return [
			'success' => false,
			'message' => __( 'External sync functionality is no longer available.', 'shop-explorer' ),
		];
	}

	/**
	 * Sync single product (No longer available)
	 *
	 * @param int    $product_id Product ID
	 * @param string $spreadsheet_id Spreadsheet ID
	 * @param string $sheet_name Sheet name
	 * @return array
	 */
	public function sync_single_product( $product_id, $spreadsheet_id, $sheet_name ) {
		// External sync functionality has been removed
		return [
			'success' => false,
			'message' => __( 'External sync functionality is no longer available.', 'shop-explorer' ),
		];
	}

	/**
	 * Enable or disable real-time sync
	 *
	 * @param bool $enabled Whether to enable real-time sync
	 */
	public function set_real_time_sync( $enabled ) {
		$this->real_time_sync = (bool) $enabled;
		update_option( 'shopex_real_time_sync', $this->real_time_sync );
	}

	/**
	 * Get real-time sync status
	 *
	 * @return bool
	 */
	public function is_real_time_sync_enabled() {
		return $this->real_time_sync;
	}

	/**
	 * Get product sync statistics
	 *
	 * @return array
	 */
	public function get_sync_statistics() {
		try {
			return [
				'total_products' => $this->database_manager->get_product_count(),
				'synced_today' => $this->database_manager->get_products_synced_today(),
				'last_sync' => get_option( 'shopex_last_product_sync', null ),
				'real_time_enabled' => $this->real_time_sync,
			];
		} catch ( \Exception $e ) {
			return [
				'error' => $e->getMessage(),
			];
		}
	}

	/**
	 * Bulk update products in database
	 *
	 * @param array $updates Array of product updates
	 * @return array
	 */
	public function bulk_update_products( $updates ) {
		try {
			$updated_count = 0;
			$errors = [];

			foreach ( $updates as $product_id => $update_data ) {
				try {
					$success = $this->database_manager->update_product_data( $product_id, $update_data );
					if ( $success ) {
						$updated_count++;
					}
				} catch ( \Exception $e ) {
					$errors[] = "Product {$product_id}: " . $e->getMessage();
				}
			}

			return [
				'success' => true,
				'updated_count' => $updated_count,
				'total_count' => count( $updates ),
				'errors' => $errors,
			];

		} catch ( \Exception $e ) {
			return [
				'success' => false,
				'message' => $e->getMessage(),
			];
		}
	}
}