<?php
declare(strict_types=1);
defined('ABSPATH') || exit;

class DSProofwp_Review_Request_Hooks
{
	private DSProofwp_Review_Request_Service $service;

	public function __construct(DSProofwp_Review_Request_Service $service)
	{
		$this->service = $service;
	}

	public function register(): void
	{
		/**
		 * WooCommerce Order Completed
		 */
		add_action('woocommerce_order_status_completed', function ($order_id) {
			$order = wc_get_order($order_id);

			if ($order) {
				$this->service->handle_order_completed($order);
			}
		});

		/**
		 * WooCommerce Order Cancelled or Refunded
		 */
		add_action('woocommerce_order_status_changed', function ($order_id, $old_status, $new_status) {
			if (in_array($new_status, ['cancelled', 'refunded'], true)) {
				$this->service->handle_order_cancelled_or_refunded((int) $order_id);
			}
		}, 10, 3);

		/**
		 * Review Submitted
		 */
		add_action('comment_post', function ($comment_id) {

			$comment = get_comment($comment_id);

			if (!$comment || $comment->comment_type !== 'review') {
				return;
			}

			$this->service->handle_review_submitted(
				(int) $comment->comment_post_ID,
				$comment->comment_author_email
			);
		});

		/**
		 * Cron Job
		 */
		add_action('dsproofwp_review_request_cron', function () {
			$this->service->process_queue();
		});

        // Ensure cron is scheduled
        if (!wp_next_scheduled('dsproofwp_review_request_cron')) {
            wp_schedule_event(time(), 'hourly', 'dsproofwp_review_request_cron');
        }

		/**
		 * WooCommerce My Account Orders Table Action Button
		 */
		add_filter('woocommerce_my_account_my_orders_actions', [$this, 'add_my_account_order_review_action'], 10, 2);

		/**
		 * Single Order Details Screen (My Account -> View Order)
		 */
		add_action('woocommerce_order_details_after_order_table', [$this, 'render_single_order_review_button'], 20);

		/**
		 * Render Modal Container in Footer on Account Pages
		 */
		add_action('wp_footer', [$this, 'render_modal_container']);
	}

	/**
	 * Add "Write your review" action button to Completed orders in the My Account -> Orders list.
	 *
	 * @param array $actions
	 * @param WC_Order $order
	 * @return array
	 */
	public function add_my_account_order_review_action(array $actions, WC_Order $order): array
	{
		if (!$order->has_status('completed')) {
			return $actions;
		}

		$items = $order->get_items();
		if (empty($items)) {
			return $actions;
		}

		$current_user_id = get_current_user_id();
		$user_id = $order->get_customer_id() ?: $current_user_id;
		$current_user = $current_user_id ? wp_get_current_user() : null;
		$customer_email = $order->get_billing_email() ?: ($current_user ? $current_user->user_email : '');

		global $wpdb;
		$repo = new DSProofwp_Review_Repository($wpdb);

		// Find the first unreviewed product in the order
		$unreviewed_product_id = 0;
		foreach ($items as $item) {
			$product_id = $item->get_product_id();
			if ($product_id <= 0) {
				$product = $item->get_product();
				$product_id = $product ? $product->get_id() : 0;
			}
			if ($product_id <= 0) {
				continue;
			}

			if (!$repo->has_user_reviewed($product_id, $user_id, (string) $customer_email)) {
				$unreviewed_product_id = $product_id;
				break;
			}
		}

		// If all products in the order have already been reviewed, do not show the button
		if ($unreviewed_product_id <= 0) {
			return $actions;
		}

		$actions['proofwp-review'] = [
			'url'  => '#write-review?product_id=' . (int) $unreviewed_product_id,
			'name' => __('Write your review', 'proofwp'),
		];

		return $actions;
	}

	/**
	 * Render review button on the Single Order Details view.
	 *
	 * @param WC_Order $order
	 */
	public function render_single_order_review_button(WC_Order $order): void
	{
		if (!$order->has_status('completed')) {
			return;
		}

		$items = $order->get_items();
		if (empty($items)) {
			return;
		}

		$current_user_id = get_current_user_id();
		$user_id = $order->get_customer_id() ?: $current_user_id;
		$current_user = $current_user_id ? wp_get_current_user() : null;
		$customer_email = $order->get_billing_email() ?: ($current_user ? $current_user->user_email : '');

		global $wpdb;
		$repo = new DSProofwp_Review_Repository($wpdb);

		$unreviewed_buttons = [];
		foreach ($items as $item) {
			$product_id = $item->get_product_id();
			if ($product_id <= 0) {
				$product = $item->get_product();
				$product_id = $product ? $product->get_id() : 0;
			}
			if ($product_id <= 0) {
				continue;
			}

			if ($repo->has_user_reviewed($product_id, $user_id, (string) $customer_email)) {
				continue;
			}

			$product = $item->get_product();
			$product_name = $product ? $product->get_name() : $item->get_name();

			$unreviewed_buttons[] = '<a href="#write-review?product_id=' . esc_attr((string) $product_id) . '" class="button woocommerce-button proofwp-review" data-product-id="' . esc_attr((string) $product_id) . '">' . sprintf(esc_html__('Write review for %s', 'proofwp'), esc_html($product_name)) . '</a>';
		}

		if (!empty($unreviewed_buttons)) {
			echo '<div class="dsproofwp-single-order-review-wrap" style="margin: 20px 0; display: flex; gap: 10px; flex-wrap: wrap;">';
			echo implode('', $unreviewed_buttons);
			echo '</div>';
		}
	}

	/**
	 * Output the review popup modal container in the footer on account pages.
	 */
	public function render_modal_container(): void
	{
		if (!function_exists('is_account_page') || !is_account_page()) {
			return;
		}

		echo DSProofwp_Plugin::maybe_render_frontend_config();
		echo '<div id="dsproofwp-order-review-root"></div>';
	}
}
