<?php

namespace IGD_PRO;

defined( 'ABSPATH' ) || exit;

use IGD\Account;
use IGD\Authorization;
use IGD\Shortcode;

class Ajax extends \IGD\Ajax {

	private static $instance;

	/**
	 *  constructor.
	 */
	public function __construct() {

		parent::__construct();

		// Update User Folders
		add_action( 'wp_ajax_igd_update_user_folders', [ $this, 'update_user_folders' ] );

		// Get access token
		add_action( 'wp_ajax_igd_get_access_token', [ $this, 'get_access_token' ] );

		// save specific folders
		add_action( 'wp_ajax_igd_save_specific_folders', [ $this, 'save_specific_folders' ] );

		// remove specific folders
		add_action( 'wp_ajax_igd_remove_specific_folders', [ $this, 'remove_specific_folders' ] );

		// Module Password Protected
		add_action( 'wp_ajax_igd_check_module_password', [ $this, 'handle_password_protected' ] );
		add_action( 'wp_ajax_nopriv_igd_check_module_password', [ $this, 'handle_password_protected' ] );

		// Module login
		add_action( 'wp_ajax_igd_handle_module_login', [ $this, 'handle_module_login' ] );
		add_action( 'wp_ajax_nopriv_igd_handle_module_login', [ $this, 'handle_module_login' ] );

	}

	public function get_access_token() {

		$this->check_nonce();

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'You do not have permission to access this page' );
		}

		$account_id      = ! empty( $_POST['id'] ) ? sanitize_text_field( $_POST['id'] ) : '';
		$account = Account::instance()->get_accounts( $account_id );

		$authorization       = new Authorization( $account_id );
		$access_token_string = $authorization->get_access_token();
		$access_token_obj    = json_decode( $access_token_string, true );

		$access_token = $access_token_obj['access_token'];

		wp_send_json_success( $access_token );

	}

	public function handle_module_login() {

		// Verify AJAX nonce
		$this->check_nonce( true );

		// Sanitize and extract credentials
		$username = isset( $_POST['username'] ) ? sanitize_user( $_POST['username'] ) : '';
		$password = isset( $_POST['password'] ) ? $_POST['password'] : '';
		$remember = ! empty( $_POST['remember'] );

		// Validate required fields
		if ( empty( $username ) || empty( $password ) ) {
			wp_send_json_error( [ 'message' => __( 'Username and password are required.', 'integrate-google-drive-premium' ) ] );
		}

		// Attempt login
		$user = wp_signon( [
			'user_login'    => $username,
			'user_password' => $password,
			'remember'      => $remember,
		], is_ssl() );

		if ( is_wp_error( $user ) ) {
			error_log( 'IGD Login Failed: ' . $user->get_error_message() );

			wp_send_json_error( [
				'message' => $user->get_error_message(),
			] );
		}

		// Set session cookies and user context
		wp_set_current_user( $user->ID );
		wp_set_auth_cookie( $user->ID, $remember );

		wp_send_json_success();

	}

	public function handle_password_protected() {

		// Check nonce
		$this->check_nonce( true );

		$shortcode_id = ! empty( $_POST['shortcodeId'] ) ? sanitize_text_field( $_POST['shortcodeId'] ) : '';
		$password     = ! empty( $_POST['password'] ) ? sanitize_text_field( $_POST['password'] ) : '';
		$type         = ! empty( $_POST['type'] ) ? sanitize_text_field( $_POST['type'] ) : 'module';

		if ( 'table' == $type ) {
			$shortcode_data = Shortcode_Table::get_table_data( $shortcode_id );
		} else {
			$shortcode_data = Shortcode::get_shortcode_data( $shortcode_id );
		}

		if ( empty( $shortcode_data ) ) {
			wp_send_json_error( 'Invalid shortcode' );
		}

		$shortcode_password = $shortcode_data['password'] ?? '';

		if ( $password != $shortcode_password ) {
			wp_send_json_error( 'Invalid password' );
		}

		// Set module check cookie
		Restrictions::instance()->set_module_password( $shortcode_id );

		if ( 'table' == $type ) {
			$shortcode_content = Shortcode_Table::instance()->render_table( [], $shortcode_data );
		} else {
			$shortcode_content = Shortcode::instance()->render_shortcode( [], $shortcode_data );
		}

		wp_send_json_success( $shortcode_content );

	}

	public function update_user_folders() {

		// Check nonce
		$this->check_nonce();

		// Check performance
		if ( ! igd_user_can_access( 'shortcode_builder' ) ) {
			wp_send_json_error( __( 'You do not have permission to access this page', 'integrate-google-drive-premium' ) );
		}

		$user_id = ! empty( $_POST['id'] ) ? intval( $_POST['id'] ) : 0;
		$folders = ! empty( $_POST['folders'] ) ? igd_sanitize_array( $_POST['folders'] ) : [];

		update_user_meta( $user_id, 'igd_folders', $folders );

		wp_send_json_success();
	}

	public function remove_specific_folders() {

		$this->check_nonce();

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'You do not have permission to access this page' );
		}

		$account_id = ! empty( $_POST['account_id'] ) ? sanitize_text_field( $_POST['account_id'] ) : '';
		$folder_id  = ! empty( $_POST['id'] ) ? sanitize_text_field( $_POST['id'] ) : [];

		if ( empty( $account_id ) ) {
			wp_send_json_error( 'Invalid account id' );
		}

		$accounts = Account::instance()->get_accounts();

		$specific_folders = $accounts[ $account_id ]['specific_folders'];

		$specific_folders = array_filter( $specific_folders, function ( $folder ) use ( $folder_id ) {
			return $folder['id'] != $folder_id;
		} );

		$accounts[ $account_id ]['specific_folders'] = array_values( $specific_folders );
		update_option( 'igd_accounts', $accounts );

		wp_send_json_success();

	}

	public function save_specific_folders() {

		$this->check_nonce();

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'You do not have permission to access this page' );
		}

		$account_id = ! empty( $_POST['accountId'] ) ? sanitize_text_field( $_POST['accountId'] ) : '';
		$folders    = ! empty( $_POST['folders'] ) ? igd_sanitize_array( $_POST['folders'] ) : [];

		if ( empty( $account_id ) ) {
			wp_send_json_error( 'Invalid account id' );
		}

		$accounts = Account::instance()->get_accounts();

		$previous_folders = $accounts[ $account_id ]['specific_folders'] ?? [];

		$merged_folder    = array_merge( $previous_folders, $folders );
		$specific_folders = array_column( $merged_folder, null, 'id' );

		$accounts[ $account_id ]['specific_folders'] = array_values( $specific_folders );

		update_option( 'igd_accounts', $accounts );

		wp_send_json_success();
	}


	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

}

Ajax::instance();