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

class DSProofwp_Review_Request_Service
{
	private DSProofwp_Review_Request_Repository $repo;

	public function __construct(DSProofwp_Review_Request_Repository $repo)
	{
		$this->repo = $repo;
	}

	/**
	 * 1. Order Completed → Schedule First Email
	 */
	public function handle_order_completed(WC_Order $order): void
	{
		$settings = $this->repo->get_settings();
		if (empty($settings['first_request_enabled'])) {
			return;
		}

		$order_id = $order->get_id();
		$email = $order->get_billing_email();
		$delay_days = (int) ($settings['first_request_delay_days'] ?? 0);
		$scheduled_at = date('Y-m-d H:i:s', strtotime("+{$delay_days} days"));

		// Get all existing requests for this order
		$existing_requests = $this->repo->get_requests_by_order($order_id);

		$match = null;
		foreach ($existing_requests as $req) {
			if ($req['type'] === 'first') {
				$match = $req;
				break;
			}
		}

		$token = wp_generate_password(32, false);

		$data = [
			'order_id'       => $order_id,
			'token'          => $token,
			'customer_email' => $email,
			'customer_name'  => $order->get_billing_first_name(),
			'type'           => 'first',
			'scheduled_at'   => $scheduled_at,
			'status'         => 'scheduled',
			'reminder_count' => 0
		];

		if ($match) {
			// Update ONLY if status is 'scheduled'
			if ($match['status'] === 'scheduled') {
				if (!empty($match['token'])) {
					$data['token'] = $match['token'];
				}
				$this->repo->update_request($match['id'], $data);
			}
		} else {
			$this->repo->create_request($data);
		}
	}

	/**
	 * Get existing token for an order or create a new token on demand.
	 */
	public function get_or_create_order_token(WC_Order $order): string
	{
		$order_id = $order->get_id();
		$existing_requests = $this->repo->get_requests_by_order($order_id);

		foreach ($existing_requests as $req) {
			if (!empty($req['token'])) {
				return (string) $req['token'];
			}
		}

		// If no token exists, generate one and save a request
		$token = wp_generate_password(32, false);
		$email = $order->get_billing_email();
		$settings = $this->repo->get_settings();
		$delay_days = (int) ($settings['first_request_delay_days'] ?? 0);
		$scheduled_at = date('Y-m-d H:i:s', strtotime("+{$delay_days} days"));

		$this->repo->create_request([
			'order_id'       => $order_id,
			'token'          => $token,
			'customer_email' => $email,
			'customer_name'  => $order->get_billing_first_name() ?: $order->get_billing_full_name(),
			'type'           => 'first',
			'scheduled_at'   => $scheduled_at,
			'status'         => 'scheduled',
			'reminder_count' => 0,
		]);

		return $token;
	}

	/**
	 * Check if all products in the order have already been reviewed by the customer.
	 */
	public function is_order_fully_reviewed(WC_Order $order): bool
	{
		$items = $order->get_items();
		if (empty($items)) {
			return false;
		}

		$customer_email = $order->get_billing_email();
		$user_id = $order->get_customer_id();

		global $wpdb;
		$comments_table = $wpdb->comments;

		foreach ($items as $item) {
			$product = $item->get_product();
			if (!$product) {
				continue;
			}
			$product_id = $product->get_id();

			$has_review = false;
			if ($user_id > 0) {
				$has_review = (bool) $wpdb->get_var($wpdb->prepare(
					"SELECT comment_ID FROM {$comments_table} 
					 WHERE comment_post_ID = %d AND (user_id = %d OR comment_author_email = %s) AND comment_type = 'review' LIMIT 1",
					$product_id,
					$user_id,
					$customer_email
				));
			} else {
				$has_review = (bool) $wpdb->get_var($wpdb->prepare(
					"SELECT comment_ID FROM {$comments_table} 
					 WHERE comment_post_ID = %d AND comment_author_email = %s AND comment_type = 'review' LIMIT 1",
					$product_id,
					$customer_email
				));
			}

			// If at least one product has not been reviewed, the order is not fully reviewed
			if (!$has_review) {
				return false;
			}
		}

		return true;
	}

	/**
	 * 2. Review Submitted → Cancel All Scheduled Reminders
	 */
	public function handle_review_submitted(int $product_id, string $email): void
	{
		global $wpdb;
		$requests_table = $this->repo->get_requests_table_name();
		$order_id = (int) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT order_id 
				 FROM {$requests_table}
				 WHERE customer_email = %s 
				   AND status IN ('sent', 'scheduled')
				 ORDER BY id DESC
				 LIMIT 1",
				$email
			)
		);

		if ($order_id > 0) {
			$this->repo->cancel_all_requests_by_order($order_id);
		} 
		// else {
		// 	$this->repo->cancel_followup_requests($product_id, $email);
		// }
	}

	/**
	 * 3. Order Cancelled or Refunded → Cancel All Scheduled Reminders
	 */
	public function handle_order_cancelled_or_refunded(int $order_id): void
	{
		$this->repo->cancel_all_requests_by_order($order_id);
	}

	/**
	 * 3. Cron Processor
	 */
	public function process_queue(): void
	{
		$due_requests = $this->repo->get_due_requests();

		foreach ($due_requests as $request) {
			try {
				$template = $this->repo->get_template_by_type($request['type']);

				if (empty($template)) {
					continue;
				}

				$this->send_email($request, $template);

				$this->repo->mark_as_sent((int) $request['id']);

				do_action('dsproofwp_review_request_sent', $request, $this->repo);

				// Schedule followup after first email (to be handled by Pro)
				if ($request['type'] === 'first') {
					do_action('dsproofwp_after_first_review_request_sent', $request, $this->repo);
				}

			} catch (Exception $e) {
				$this->repo->mark_as_failed($request['id']);
			}
		}
	}

	/**
	 * Email Sender
	 */
	private function send_email(array $request, array $template): void
	{
		$to = $request['customer_email'];

		list($subject, $body) = $this->mailTemplate($request, $template);

		$headers = array('Content-Type: text/html; charset=UTF-8');

		$result = dsproofwp_send_mail_verified(
			$to,
			$subject,
			$body,
			$headers
		);

		if (is_wp_error($result)) {
			error_log('[DSProofwp] Email send failed: ' . $result->get_error_message());
			return;
		}
	}

	/**
	 * Mail Template Processor
	 */
	public function mailTemplate(array $request, array $template): array
	{
		$customer_name = $request['customer_name'] ?? 'Customer';
		$order_number  = '';
		$items_html    = '';
		$order         = null;

		if (!empty($request['order_id']) && function_exists('wc_get_order')) {
			$order = wc_get_order($request['order_id']);
			if ($order) {
				$order_number = $order->get_order_number();
			}
		}

		$site_name = get_bloginfo('name');
		$logo_id  = get_theme_mod('custom_logo');
		$logo_url = $logo_id ? wp_get_attachment_image_url($logo_id, 'full') : '';
		$button_label = !empty($template['button_text']) ? $template['button_text'] : 'Leave a Review';

		// Construct aggregated review page URL
		$review_url = '';
		if (!empty($request['token'])) {
			$review_url = home_url('/proofwp-review/' . $request['token']);
		} else {
			$review_url = home_url('/');
		}

		

		// Replace placeholders in the raw content
		$replacements = [
			'[customer_name]' => $customer_name,
			'[order_number]'  => $order_number,
			'[site_name]'     => $site_name,
		];

		$raw_subject = strtr($template['subject'] ?? '', $replacements);
		$raw_body    = strtr($template['body'] ?? '', $replacements);

		$button_html = '
        <div style="text-align: center; margin-top: 25px;">
            <a href="' . esc_url($review_url) . '" 
               style="background-color: #7f54b3; color: #ffffff; padding: 12px 25px; text-decoration: none; border-radius: 5px; font-weight: bold; display: inline-block;">
                ' . esc_html($button_label) . '
            </a>
        </div>';

		// Standard HTML Email Wrapper
		$html_message = '
		<html>
		<head>
			<style>
				body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; margin: 0; padding: 0; }
				.container { width: 100%; max-width: 600px; margin: 20px auto; border: 1px solid #eee; }
				.header { background: #f8f8f8; padding: 20px; text-align: center; border-bottom: 3px solid #7f54b3; }
				.header img { max-width: 150px; height: auto; }
				.content { padding: 30px; background: #ffffff; }
				.footer { background: #f8f8f8; padding: 20px; text-align: center; font-size: 12px; color: #777; }
			</style>
		</head>
		<body>
			<div class="container">
				<div class="header">
					' . ($logo_url ? '<img src="' . esc_url($logo_url) . '" alt="' . esc_attr($site_name) . '">' : '<h1>' . esc_html($site_name) . '</h1>') . '
				</div>
				<div class="content">
					' . wpautop($raw_body) . '
					' . $items_html . '
					' . $button_html . '
				</div>
				<div class="footer">
					<p>&copy; ' . date('Y') . ' ' . esc_html($site_name) . '. All rights reserved.</p>
				</div>
			</div>
		</body>
		</html>';

		return [$raw_subject, $html_message];
	}
}
