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

namespace SHOPEXPLORER\Modules;

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

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

/**
 * Order Synchronization Manager class
 *
 * Handles order synchronization operations
 *
 * @since 1.0.0
 */
class SHOPEX_OrderSyncManager {

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

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

	/**
	 * Order manager instance
	 *
	 * @var OrderManager
	 */
	private $order_manager;

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

	/**
	 * Initialize WordPress hooks for real-time sync
	 */
	private function init_hooks() {
		// Hook into WooCommerce order events
		add_action( 'woocommerce_new_order', [ $this, 'on_order_create' ], 20, 1 );
		add_action( 'woocommerce_update_order', [ $this, 'on_order_update' ], 20, 1 );
		add_action( 'woocommerce_order_status_changed', [ $this, 'on_order_status_change' ], 20, 3 );
		add_action( 'woocommerce_delete_order', [ $this, 'on_order_delete' ], 20, 1 );
	}

	/**
	 * Sync orders (No longer available)
	 *
	 * @param array  $order_ids Array of order IDs to sync
	 * @param string $direction Sync direction
	 * @param array  $options Sync options
	 * @return array
	 */
	public function sync_orders( $order_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 order creation event
	 *
	 * @param int $order_id Order ID
	 */
	public function on_order_create( $order_id ) {
		try {
			// Store order data in database
			$order = $this->order_manager->get_order( $order_id );
			if ( $order ) {
				$this->database_manager->store_order( $order );
			}
		} catch ( \Exception $e ) {
			error_log( 'Order sync error on create: ' . $e->getMessage() );
		}
	}

	/**
	 * Handle order update event
	 *
	 * @param int $order_id Order ID
	 */
	public function on_order_update( $order_id ) {
		try {
			// Update order data in database
			$order = $this->order_manager->get_order( $order_id );
			if ( $order ) {
				$this->database_manager->update_order( $order );
			}
		} catch ( \Exception $e ) {
			error_log( 'Order sync error on update: ' . $e->getMessage() );
		}
	}

	/**
	 * Handle order status change event
	 *
	 * @param int    $order_id Order ID
	 * @param string $old_status Old status
	 * @param string $new_status New status
	 */
	public function on_order_status_change( $order_id, $old_status, $new_status ) {
		try {
			// Update order status in database
			$this->database_manager->update_order_status( $order_id, $new_status );
		} catch ( \Exception $e ) {
			error_log( 'Order status sync error: ' . $e->getMessage() );
		}
	}

	/**
	 * Handle order deletion event
	 *
	 * @param int $order_id Order ID
	 */
	public function on_order_delete( $order_id ) {
		try {
			// Mark order as deleted in database
			$this->database_manager->mark_order_deleted( $order_id );
		} catch ( \Exception $e ) {
			error_log( 'Order sync error on delete: ' . $e->getMessage() );
		}
	}

	/**
	 * 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 orders (No longer available)
	 *
	 * @param string $spreadsheet_id Spreadsheet ID
	 * @param string $sheet_name Sheet name
	 * @return array
	 */
	public function sync_all_orders( $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 order (No longer available)
	 *
	 * @param int    $order_id Order ID
	 * @param string $spreadsheet_id Spreadsheet ID
	 * @param string $sheet_name Sheet name
	 * @return array
	 */
	public function sync_single_order( $order_id, $spreadsheet_id, $sheet_name ) {
		// External sync functionality has been removed
		return [
			'success' => false,
			'message' => __( 'External sync functionality is no longer available.', 'shop-explorer' ),
		];
	}

	/**
	 * Validate order data for sync
	 *
	 * @param OrderDataModel $order Order data model
	 * @return array Validation errors
	 */
	public function validate_order_for_sync( $order ) {
		$errors = [];

		// Basic validation
		$validation_result = $order->validate();
		if ( $validation_result !== true ) {
			$errors = array_merge( $errors, $validation_result );
		}

		// Sync-specific validation
		if ( empty( $order->order_number ) ) {
			$errors[] = 'Order number is required for synchronization';
		}

		if ( empty( $order->customer_email ) || ! is_email( $order->customer_email ) ) {
			$errors[] = 'Valid customer email is required for synchronization';
		}

		return $errors;
	}

	/**
	 * Get order sync statistics
	 *
	 * @return array
	 */
	public function get_sync_statistics() {
		try {
			return [
				'total_orders' => $this->database_manager->get_order_count(),
				'synced_today' => $this->database_manager->get_orders_synced_today(),
				'last_sync' => get_option( 'shopex_last_order_sync', null ),
				'pending_orders' => $this->database_manager->get_pending_orders_count(),
			];
		} catch ( \Exception $e ) {
			return [
				'error' => $e->getMessage(),
			];
		}
	}

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

			foreach ( $updates as $order_id => $update_data ) {
				try {
					$success = $this->database_manager->update_order_data( $order_id, $update_data );
					if ( $success ) {
						$updated_count++;
					}
				} catch ( \Exception $e ) {
					$errors[] = "Order {$order_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(),
			];
		}
	}

	/**
	 * Get orders by status
	 *
	 * @param string $status Order status
	 * @param array  $args Additional arguments
	 * @return array
	 */
	public function get_orders_by_status( $status, $args = [] ) {
		try {
			return $this->database_manager->get_orders_by_status( $status, $args );
		} catch ( \Exception $e ) {
			return [
				'success' => false,
				'message' => $e->getMessage(),
			];
		}
	}

	/**
	 * Format address for display
	 *
	 * @param array $address Address array
	 * @return string
	 */
	private function format_address( $address ) {
		if ( empty( $address ) ) {
			return '';
		}

		$parts = array_filter( [
			$address['address_1'] ?? '',
			$address['city'] ?? '',
			$address['state'] ?? '',
			$address['postcode'] ?? '',
			$address['country'] ?? '',
		] );

		return implode( ', ', $parts );
	}

	/**
	 * Format items summary
	 *
	 * @param array $items Items array
	 * @return string
	 */
	private function format_items_summary( $items ) {
		if ( empty( $items ) ) {
			return '';
		}

		$summary = [];
		foreach ( $items as $item ) {
			$summary[] = sprintf(
				/* translators: %s: is the product id */
				'%s (x%d)',
				$item['name'] ?? 'Unknown',
				$item['quantity'] ?? 1
			);
		}

		return implode( '; ', $summary );
	}
}