<?php

namespace IconPress\Extend\Helpers;

use IconPress__enshrined\svgSanitize\Sanitizer;
use IconPress\Helpers\Option;
use IconPress\Helpers\FileSystem;
use IconPress\Helpers\Utility;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class RestAPI
 *
 * Base class for Rest API requests
 *
 * @package IconPress\Helpers
 */
class RestAPI
{
	/**
	 * Holds the cached instance of the WP File System class used
	 * @var null|\WP_Filesystem_Base
	 */
	private static $_fsCache = null;

	public static function getIconCode( $wpr ){

		if ( $wpr instanceof \WP_REST_Request ) {

			$internal_id = wp_strip_all_tags( $wpr->get_param( 'internal_id' ) );

			// svg path
			$svg = wp_normalize_path( trailingslashit( 'default' ) ) . $internal_id .'.svg';

			if( $svg_content = FileSystem::getContent( $svg ) ) {
				wp_send_json_success( $svg_content );
			}
			else {
				wp_send_json_error( __( "Couldn't get the icon.", 'iconpress') );
			}
		}

		wp_send_json_error( __( 'Sorry, invalid request.', 'iconpress' ) );
	}

	public static function saveIconCode( $wpr ){

		if ( $wpr instanceof \WP_REST_Request ) {

			$overwrite = $wpr->get_param( 'overwrite' );
			$internal_id = wp_strip_all_tags( $wpr->get_param( 'internal_id' ) );

			$svgSanitizer = new Sanitizer();
			$svgSanitizer->removeXMLTag(true);
			$code = $svgSanitizer->sanitize( $wpr->get_param( 'code' ) );

			if( false === $code ){
				wp_send_json_error( __( "The svg code is not valid.", 'iconpress') );
			}


			$saved_collections = get_option( Option::getOptionName( Option::SAVED_COLLECTIONS ), [] );

			if ( !isset( $saved_collections['default'] ) ) {
				wp_send_json_error( __( "Couldn't save because there is no collection saved.", 'iconpress') );
			}

			// Update existing svg
			if( $overwrite ) {
				if( ! FileSystem::writeSvgFile( $internal_id, $code ) ) {
					wp_send_json_error( __( 'SVG wasn\'t saved!', 'iconpress' ) );
				}
			}
			// add new svg
			else {

				$icon_info = [];
				// get icon info
				foreach ($saved_collections['default'] as $k => $v) {
					if( $v['internal_id'] == $internal_id ) {
						$icon_info = $v;
					}
				}

				// update with new internal id
				$icon_info['internal_id'] = $internal_id . uniqid('_');
				$icon_info['local_url'] = str_replace($internal_id, $icon_info['internal_id'], $icon_info['local_url']);
				$icon_info['is_custom'] = true;

				// replace the id attribute
				$code = str_replace($internal_id, $icon_info['internal_id'], $code);

				if( FileSystem::writeSvgFile( $icon_info['internal_id'], $code ) ) {
					array_push($saved_collections['default'], $icon_info);
				}
				else {
					wp_send_json_error( __( 'SVG wasn\'t saved!', 'iconpress' ) );
				}

				// update option
				update_option( Option::getOptionName( Option::SAVED_COLLECTIONS ), $saved_collections );
			}

			// regenerate svg sprite
			FileSystem::generateSvgSprite();

			wp_send_json_success( __( "Saved!", 'iconpress') );
		}
		wp_send_json_error( __( 'Sorry, invalid request.', 'iconpress' ) );
	}

	public static function upload_icon( $wpr ){

		if ( $wpr instanceof \WP_REST_Request ) {

			$count_files = 0;

			if( $file = $wpr->get_file_params() ) {

				if( !empty($file) && isset($file['file']) && is_array($file['file']) && isset($file['file']['name']) ){
					$count_files = count($file['file']['name']);
				}
				else {
					wp_send_json_error( __('File(s) are missing.', 'iconpress') );
				}
			}
			else {
				wp_send_json_error( __('Something went wrong with the uploaded file.', 'iconpress') );
			}

			if ( empty( self::$_fsCache ) ) {
				self::$_fsCache = FileSystem::get();
			}

			if( $count_files !== 0 ) {

				// $svgSanitizer = new Sanitizer();

				$upDir = FileSystem::$uploadsDirPath;
				$iDir = FileSystem::$uploads__IconPressDirPath;
				$cDir = FileSystem::$uploads__IconPressCollectionDirPath;
				$fp = $upDir . $iDir . $cDir;

				$errors = [];

				if( !self::$_fsCache->is_dir( $fp ) ) {
					self::$_fsCache->mkdir( $fp );
				}
				// get saved collections
				$saved_collections = get_option( Option::getOptionName( Option::SAVED_COLLECTIONS ), [] );
				// get user id
				$current_user_id = Utility::$user_id;

				for($i = 0; $i < $count_files; $i++){

					// double check for svg
					if( $file['file']['type'][$i] == 'image/svg+xml' ){

						// get title by filename
						$title = Utility::unslugify( $file['file']['name'][$i] );
						$internal_id = uniqid('upload_');

						// get svg contents
						$svg_icon = self::$_fsCache->get_contents( $file['file']['tmp_name'][$i] );

						// // sanitize svg
						// $svg_icon = $svgSanitizer->sanitize( $svg_icon );

						// cleanups
						if( $svg_object = simplexml_load_string($svg_icon) ){
							$svg_icon = FileSystem::__cleanupClassAttributes( $svg_object );
							$svg_icon = FileSystem::__cleanupSvgFile( $svg_icon, $internal_id );
						}

						if( false === $svg_icon ){
							$errors[] = __( "The SVG code is not valid. Aborting!", 'iconpress');
							continue;
						}

						// upload to iconpress/default/ folder
						if ( ! self::$_fsCache->put_contents( $fp . $internal_id . '.svg', $svg_icon ) ) {
							$errors[] = __( "Couldn't upload to IconPress folder.", 'iconpress');
							continue;
						}

						// Import into WP Media Library
						$uploadml = (int) $wpr->get_param( 'uploadml' );
						if( $uploadml ){
							FileSystem::importWpAttachment( $fp . $internal_id . '.svg' );
						}

						// add icon into DB
						$data = [
							'internal_id' => $internal_id,
							'title' => $title,
							'type' => 'upload',
							'local_url' => $iDir  . $cDir . $internal_id . '.svg'
						];

						// add user id
						$data['user_id'] = $current_user_id;

						// pull collection data
						$saved_collections['default'][] = $data;
					}
				}
			}


			if( !empty($errors) ){
				wp_send_json_error( $errors );
			}

			// update option
			update_option( Option::getOptionName( Option::SAVED_COLLECTIONS ), $saved_collections );

			// Generate the svg sprite
			if ( ! FileSystem::generateSvgSprite() ) {
				wp_send_json_error( __( 'There was an error creating/updating the SVG SPRITE.', 'iconpress' ) );
			}
			// remove unused svg files
			FileSystem::cleanupUnusedSvg();

			wp_send_json_success( $internal_id );

		}

		wp_send_json_error( __( 'Sorry, invalid request.', 'iconpress' ) );
	}
}
