<?php 

if(!function_exists('save_block_to_theme')) {
	
	/*
		commented temporarily as it is not used.
		Uncomment this if we change our mind in the future
	*/
	/*
	function save_block_to_theme() {
		if(defined("FLO_ENVIROMENT") && FLO_ENVIROMENT === "DEV") {
			$file_name = $_POST["fileName"];
			$file_content = $_POST["fileContent"];
      $block_data = $_POST["blockData"];
      $res = flexSaveBlockFile($file_name, $file_content, $block_data);
			wp_die(json_encode($res));
		} else {
			wp_die(json_encode(['status' => 'Not Allowed']));
		}
	}
	*/
	//add_action('wp_ajax_save_block_to_theme', 'save_block_to_theme');
  
  if(!function_exists('flexSaveBlockFile')) {
		function flexSaveBlockFile($file_name, $file_content, $block_data) {
			global $wp_filesystem;
			$flex_blocks_root = get_template_directory() . '/theme-files/flex-blocks/';
      $flex_blocks_dir = $flex_blocks_root . '/blocks-list/';

			if(!$wp_filesystem->is_dir($flex_blocks_root)) {
				$wp_filesystem->mkdir($flex_blocks_root);
        $wp_filesystem->mkdir($flex_blocks_dir);
			}
      
      $blocks_config_file = $flex_blocks_root . '/flex-blocks-config.json';
      if (!file_exists($blocks_config_file)) {
				// file does not exist, create new one
        $jsondata = json_encode([$block_data], JSON_PRETTY_PRINT);
        $fh = fopen($blocks_config_file, 'a');
        fwrite($fh, $jsondata);
        fclose($fh);
        $message["config_file"] = ["status" => "Config file not found, created"];
      } else {
        // Get data from existing json file
        $jsondata = file_get_contents($blocks_config_file);
        $arr_data = json_decode($jsondata, true);
				
				$block_index = $block_data["index"];
				$key = array_search($block_index, array_column($arr_data, 'index'));
				
				if($key === false) {
					// if entry is not present, append it
	        array_push($arr_data, $block_data);	
				} else {
					// if entry is already present, update it with the current block data
					$arr_data[$key] = $block_data;
				}
        
        // Convert updated array to JSON
        $jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);

        // write json data back to file
        if(file_put_contents($blocks_config_file, $jsondata)) {
          $message["config_file"] = ["status" => "Config file edited successfully"];
        } else {
          $message["config_file"] = ["status" => "Error editing config file"];
        }
      }

			if($wp_filesystem->is_dir($flex_blocks_root)) {
				$file_path = $flex_blocks_dir . $file_name . ".json";
				$file_data = urldecode($file_content);
				
				// single quotes are encountered ONLY inside texts, and these do not need to be escaped, as this breaks the JSON file
				// to fix that, we do a naive replace of escaped single quotes to non-escaped single quotes: (\' -> ')
				$file_data = str_replace("\'", "'", $file_data);
				
        $fileCallback = $wp_filesystem->put_contents(
					$file_path,
					$file_data,
					FS_CHMOD_FILE
				);
        
        $message["flex_block"] = ["status" => "Success"];
			} else {
        $message["flex_block"] = ["status" => "Could not create folder"];
      }
      
			return $message;
			
		}
	}
}

?>