<?php

namespace Unlockafe_addons\Admin;

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

class Admin {

	/**
	 *
	 * $instance property for instance
	 */
	private static $instance = null;
	public function __construct() {
		add_action( 'init', [ $this, 'init' ] );
		add_filter( 'plugin_action_links_' . UNLOCKAFE_ADDONS_BASE, [ $this, 'unlockafe_action_links' ] );
		add_action( 'rest_api_init', [ $this, 'register_google_sheet_rest_routes' ] );
		add_action( 'admin_post_unlockafe_save_header_footer', [ $this, 'handle_header_footer_form' ] );

	}

	/**
	 *
	 * @return self
	 * @since  1.0.0
	 */
	public static function getInstance() {
		if ( ! isset( self::$instance ) ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	public function init() {
		// admin page
		add_action( 'admin_menu', [ $this, 'menu' ] );
	}

	/**
	 * Admin menu options
	 * 
	 * @return void
	 */
	public function menu() {
		add_menu_page(
			esc_html__( 'Unlock Addons', 'unlock-addons-for-elementor' ),
			esc_html__( 'Unlock Addons', 'unlock-addons-for-elementor' ),
			'manage_options',
			'unlock-addons',
			[ $this, 'dashboard' ],
			UNLOCKAFE_ASSETS . 'images/unlock-dash-logo.svg',
			'58.1'
		);

		// All elements menager page
		add_submenu_page(
			'unlock-addons',
			__( 'Elements', 'unlock-addons-for-elementor' ),
			__( 'Elements', 'unlock-addons-for-elementor' ),
			'manage_options',
			'unlock-addons-elements',
			[ $this, 'dashboard' ],
		);

		// all pluigns list from wpreqlizer
		add_submenu_page(
			'unlock-addons',
			__( 'Integrations', 'unlock-addons-for-elementor' ),
			__( 'Integrations', 'unlock-addons-for-elementor' ),
			'manage_options',
			'unlock-addons-integrations',
			[ $this, 'dashboard' ],
		);

		// The React version of Email Records has been removed because it had errors
		// We now use the native WordPress version at 'unlockafe-email-records' instead

		// Support page
		add_submenu_page(
			'unlock-addons',
			__( 'Support', 'unlock-addons-for-elementor' ),
			__( 'Support', 'unlock-addons-for-elementor' ),
			'manage_options',
			'unlock-addons-support',
			[ $this, 'dashboard' ],
		);

		// Popup Statistics page
		add_submenu_page(
			'unlock-addons',
			__( 'Popup Statistics', 'unlock-addons-for-elementor' ),
			__( 'Popup Statistics', 'unlock-addons-for-elementor' ),
			'manage_options',
			'unlockafe-popup-dashboard',
			[ $this, 'dashboard' ],
		);

		// Promotions page
		add_submenu_page(
			'unlock-addons',
			__( 'Go premium', 'unlock-addons-for-elementor' ),
			__( 'Go premium', 'unlock-addons-for-elementor' ),
			'manage_options',
			'unlock-addons-go-premium',
			[ $this, 'dashboard' ],
		);
		add_submenu_page(
			'unlock-addons',
			__( 'Header & Footer', 'unlock-addons-for-elementor' ),
			__( 'Header & Footer', 'unlock-addons-for-elementor' ),
			'manage_options',
			'unlockafe-header-footer',
			[ $this, 'header_footer_settings_page' ],
		);
	}

	/**
	 * Admin Dashboard View
	 * @return void
	 */
	public function dashboard() {
		// dashboard output
		include_once UNLOCKAFE_INCLUDE_PATH . 'Admin/views/main.dashboard.php';
	}

	public function header_footer_settings_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$headers = get_posts( [
			'post_type'      => 'wpr-header',
			'post_status'    => 'publish',
			'posts_per_page' => -1,
			'orderby'        => 'title',
			'order'          => 'ASC',
		] );

		$footers = get_posts( [
			'post_type'      => 'wpr-footer',
			'post_status'    => 'publish',
			'posts_per_page' => -1,
			'orderby'        => 'title',
			'order'          => 'ASC',
		] );

		$selected_header = get_option( 'unlockafe_default_header', '' );
		$selected_footer = get_option( 'unlockafe_default_footer', '' );

		include UNLOCKAFE_INCLUDE_PATH . 'Admin/views/header-footer-settings.php';
	}

	function unlockafe_action_links( $actions ) {
		$links   = array(
			'<a href="' . admin_url( 'admin.php?page=unlock-addons' ) . '">' . __( 'Settings', 'unlock-addons-for-elementor' ) . '</a>',
			'<a href="' . admin_url( 'admin.php?page=unlock-addons-go-premium' ) . '" style="color:#c60055; font-weight: bold;">' . __( 'Get Premium', 'unlock-addons-for-elementor' ) . '</a>',
		);
		$actions = array_merge( $actions, $links );
		return $actions;
	}

	public function register_google_sheet_rest_routes() {
		register_rest_route( 'unlock-addons/v1', '/google-sheets/settings', [
			[
				'methods'  => 'GET',
				'callback' => [ $this, 'get_google_sheet_settings' ],
				'permission_callback' => [ $this, 'get_permissions_check' ],
			],
			[
				'methods'  => 'POST',
				'callback' => [ $this, 'save_google_sheet_settings' ],
				'permission_callback' => [ $this, 'get_permissions_check' ],
			],
		] );

		// Register Google Maps REST API routes
		register_rest_route( 'unlock-addons/v1', '/google-maps/settings', [
			[
				'methods'  => 'GET',
				'callback' => [ $this, 'get_google_maps_settings' ],
				'permission_callback' => [ $this, 'get_permissions_check' ],
			],
			[
				'methods'  => 'POST',
				'callback' => [ $this, 'save_google_maps_settings' ],
				'permission_callback' => [ $this, 'get_permissions_check' ],
			],
		] );
	}

public function get_google_sheet_settings() {
		$settings = get_option('unlockafe_google_sheets_settings', ['api_key' => '']);
		$api_key = !empty($settings['api_key']) ? $settings['api_key'] : '';
		return new \WP_REST_Response(['api_key' => $api_key], 200);
	}

	public function save_google_sheet_settings($request) {
		$api_key = sanitize_text_field($request->get_param('api_key'));
		$settings = ['api_key' => $api_key];
		update_option('unlockafe_google_sheets_settings', $settings);
		return new \WP_REST_Response(['message' => 'Settings saved successfully.'], 200);
	}

	public function get_permissions_check() {
		return current_user_can( 'manage_options' );
	}

	public function get_google_maps_settings() {
		$api_key = get_option('unlockafe_google_map_api_key', '');
		return new \WP_REST_Response(['api_key' => $api_key], 200);
	}

	public function save_google_maps_settings($request) {
		$api_key = sanitize_text_field($request->get_param('api_key'));
		update_option('unlockafe_google_map_api_key', $api_key);
		return new \WP_REST_Response(['message' => 'Settings saved successfully.'], 200);
	}

	public function handle_header_footer_form() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( __( 'Unauthorized action.', 'unlock-addons-for-elementor' ) );
		}

		check_admin_referer( 'unlockafe_header_footer_save', 'unlockafe_header_footer_nonce' );

		$header_id = isset( $_POST['unlockafe_default_header'] ) ? absint( $_POST['unlockafe_default_header'] ) : 0;
		$footer_id = isset( $_POST['unlockafe_default_footer'] ) ? absint( $_POST['unlockafe_default_footer'] ) : 0;

		update_option( 'unlockafe_default_header', $header_id );
		update_option( 'unlockafe_default_footer', $footer_id );

		wp_safe_redirect(
			add_query_arg(
				[
					'page'   => 'unlockafe-header-footer',
					'status' => 'saved',
				],
				admin_url( 'admin.php' )
			)
		);
		exit;
	}
}