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

class DSProofwp_Review_Request_Controller
{
	private const ROUTE_NAMESPACE = 'dsproofwp/v1';

	private DSProofwp_Review_Request_Repository $repo;

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

	public function register_routes(): void
	{
		register_rest_route(self::ROUTE_NAMESPACE, '/review-request-settings', [
			[
				'methods' => WP_REST_Server::READABLE,
				'callback' => [$this, 'get_settings'],
				'permission_callback' => [$this, 'manage_permission'],
			],
			[
				'methods' => WP_REST_Server::EDITABLE,
				'callback' => [$this, 'update_settings'],
				'permission_callback' => [$this, 'manage_permission'],
			],
		]);

		register_rest_route(self::ROUTE_NAMESPACE, '/email-templates', [
			[
				'methods' => WP_REST_Server::READABLE,
				'callback' => [$this, 'get_templates'],
				'permission_callback' => [$this, 'manage_permission'],
			],
		]);

		register_rest_route(self::ROUTE_NAMESPACE, '/email-templates/(?P<type>first|followup)', [
			[
				'methods' => WP_REST_Server::EDITABLE,
				'callback' => [$this, 'update_template'],
				'permission_callback' => [$this, 'manage_permission'],
			],
		]);

		register_rest_route(self::ROUTE_NAMESPACE, '/review-requests', [
			[
				'methods' => WP_REST_Server::READABLE,
				'callback' => [$this, 'get_requests'],
				'permission_callback' => [$this, 'manage_permission'],
			],
		]);

		register_rest_route(self::ROUTE_NAMESPACE, '/review-requests/(?P<id>\d+)/cancel', [
			[
				'methods' => WP_REST_Server::EDITABLE,
				'callback' => [$this, 'cancel_request'],
				'permission_callback' => [$this, 'manage_permission'],
			],
		]);

		register_rest_route(self::ROUTE_NAMESPACE, '/review-requests/(?P<id>\d+)/delete', [
			[
				'methods' => WP_REST_Server::EDITABLE,
				'callback' => [$this, 'delete_request'],
				'permission_callback' => [$this, 'manage_permission'],
			],
		]);

		register_rest_route(self::ROUTE_NAMESPACE, '/test-email', [
			[
				'methods' => WP_REST_Server::CREATABLE,
				'callback' => [$this, 'send_test_email'],
				'permission_callback' => [$this, 'manage_permission'],
			],
		]);
	}

	public function manage_permission(): bool
	{
		return current_user_can('manage_options');
	}

	/**
	 * SETTINGS
	 */
	public function get_settings()
	{
		return rest_ensure_response($this->repo->get_settings());
	}

	public function update_settings(WP_REST_Request $request)
	{
		$this->repo->upsert_settings($request->get_params());

		return rest_ensure_response(['success' => true]);
	}

	/**
	 * TEMPLATES
	 */
	public function get_templates()
	{
		return rest_ensure_response($this->repo->get_templates());
	}

	public function update_template(WP_REST_Request $request)
	{
		$type = $request->get_param('type');

		$this->repo->upsert_template($type, $request->get_params());

		return rest_ensure_response(['success' => true]);
	}

	/**
	 * REQUESTS
	 */
	public function get_requests(WP_REST_Request $request)
	{
		$data = $this->repo->list_requests([
			'status'     => $request->get_param('status'),
			'email_type' => $request->get_param('email_type'),
			'page'       => $request->get_param('page'),
			'sort'       => $request->get_param('sort'),
		]);

		return rest_ensure_response($data);
	}

	public function cancel_request(WP_REST_Request $request)
	{
		$id = (int) $request->get_param('id');

		$success = $this->repo->cancel_request($id);

		if (! $success) {
			return new WP_Error(
				'cancel_failed',
				'Unable to cancel request',
				['status' => 500]
			);
		}

		return rest_ensure_response([
			'success' => true,
			'id' => $id,
		]);
	}

	public function delete_request(WP_REST_Request $request)
	{
		$id = (int) $request->get_param('id');

		$success = $this->repo->delete_request($id);

		if (! $success) {
			return new WP_Error(
				'delete_failed',
				'Unable to delete request',
				['status' => 500]
			);
		}

		return rest_ensure_response([
			'success' => true,
			'id' => $id,
		]);
	}

	public function send_test_email(WP_REST_Request $request)
	{
		$email = $request->get_param('email');
		$type  = $request->get_param('type') ?? 'first';

		if (empty($email) || !is_email($email)) {
			return new WP_Error('dsproofwp_invalid_email', 'Invalid email', ['status' => 400]);
		}

		$template = $this->repo->get_template_by_type($type);

		if (!$template) {
			return new WP_Error('dsproofwp_template_not_found', 'Template not found', ['status' => 404]);
		}

		$mock_request = [
			'customer_name'  => 'Test Customer',
			'customer_email' => $email,
			'order_id'       => 0,
		];

		$service = new DSProofwp_Review_Request_Service($this->repo);
		list($subject, $body) = $service->mailTemplate($mock_request, $template);

		$result = dsproofwp_send_mail_verified(
			$email,
			$subject,
			$body,
			['Content-Type: text/html; charset=UTF-8']
		);

		if (is_wp_error($result)) {
			return new WP_Error('smtp_not_configured', 'No SMTP configuration detected. Please configure an SMTP plugin (e.g. WP Mail SMTP).', ['status' => 500]);
		}

		return rest_ensure_response(['success' => true]);
	}
}
