<?php

class Intense_Icon extends Intense_Shortcode {

  function __construct() {
    parent::__construct();

    global $intense_visions_options;

    $this->title = __( 'Icon', 'intense' );
    $this->description = __( 'Quickly add icons to your WordPress site using the icon shortcode. There are thousands of icons to choose from by default or add your own. Easily find the icon you are looking for using the shortcode dialogs.', 'intense' );
    $this->category = __( 'Elements', 'intense' );
    $this->show_preview = true;
  }

  function shortcode( $atts, $content = null ) {
    global $intense_visions_options;
    extract( shortcode_atts( $this->get_shortcode_defaults( null, $atts ), $atts ) );

    intense_add_script( 'intense.icon' );

    $size -= 1;
    $output = "";    

    $id = ( !empty ( $id ) ) ? ' id="' . $id . '"' : '';

    if ( !empty( $rotate ) ) {
      $rotate = " icon-rotate-" . $rotate;
    }
    if ( !empty( $flip ) ) {
      $flip = " icon-flip-" . $flip;
    }

    if ( $extra_class != '' ) {
      $class = ( !empty ( $class ) ) ? $class . ' ' . $extra_class : $extra_class;
    }

    $color_style = "";
    $stack_color_style = "";

    $color = intense_get_plugin_color( $color );

    if ( !empty( $color ) ) {
      $color_style = "fill: {$color};";
    }

    if ( !empty( $stack_type ) ) {
      $stack_color = intense_get_plugin_color( $stack_color );

      if ( !empty( $stack_color ) ) {
        $stack_color_style = "fill: ${stack_color};";        
      }

      $svg_icon_path = $this->get_svg_path( $stack_source, $stack_type );

      if ( !file_exists( $svg_icon_path ) ) {
        $stack_source = 'font-awesome';
        $stack_type = 'ban';
      }

      $stack_key = str_replace( ' ', '_', $stack_source . '-' . $stack_type );      

      if ( !isset( $GLOBALS['IntensePluginInlineSVG'][ $stack_key ] ) ) {
        $svg = $this->get_svg( $stack_source, $stack_type );

        $GLOBALS['IntensePluginInlineSVG'][ $stack_key ] = $svg;
      }
    }

    $icon_path = $this->get_svg_path( $source, $type );

    if ( empty( $icon_path ) ) {
      $source = 'font-awesome';
      $type = 'remove-sign';
    }

    $key = str_replace( ' ', '_', $source . '-' . $type );

    if ( !isset( $GLOBALS['IntensePluginInlineSVG'][ $key ] ) ) {
      $svg = $this->get_svg( $source, $type );

      $GLOBALS['IntensePluginInlineSVG'][ $key ] = $svg;
    }

    $dimensions = '';
    $stack_dimensions = '';

    if ( is_numeric( $width ) ) $width .= 'px';
    if ( is_numeric( $height ) ) $height .= 'px';

    if ( !empty( $width ) && !empty( $height ) ) {      
      $dimensions = ' width:' . $width . ';height:' . $height . ';';
      $stack_dimensions = ' width:' . $width * 2 . ';height:' . $height * 2 . ';';
    } else if ( !empty( $width ) ) {
      $dimensions = ' width:' . $width . ';height:' . $width . ';';
      $stack_dimensions = ' width:' . $width * 2 . ';height:' . $width * 2 . ';';
    } else if ( !empty( $height ) ) {
      $dimensions = ' width:' . $height . ';height:' . $height . ';';
      $stack_dimensions = ' width:' . $height * 2 . ';height:' . $height * 2 . ';';
    } 

    $style = $color_style . $dimensions;
    $stack_style = $stack_color_style . $stack_dimensions;
    $hover_title = '';

    if ( !empty( $title ) ) {
      $hover_title = ' title="' . $title . '"';
    }

    $output .= 
    '<i' . $id . $hover_title . ' class="intense icon icon-' . $size . 'x' . $rotate . $flip . ( !empty( $class ) ? ' ' . $class : '' ) . ( $spin ? " icon-spin" : "" ) . ( isset( $stack_key ) ? ' icon-stack' : '' ) . '"' . ( isset( $stack_key ) ? ' style="'.$stack_dimensions.'"' : ' style="'.$dimensions.'"' ) . '>' .
      '<svg>' . 
        ( isset( $stack_key ) ? '<use xlink:href="#' . esc_attr( $stack_key ) . '" class="stack-base' . ( !empty( $stack_color_style ) ? ' filled' : '' ) . '"' . ( !empty( $stack_style ) ? ' style="' . $stack_style . '"'  : '' ) . '></use>' : '' ) .
        '<use xlink:href="#' . esc_attr( $key ) . '" class="' . ( isset( $stack_key ) ? ' stack-child' : '' ) . ( !empty( $color_style ) ? ' filled' : '' ) . '"' . ( !empty( $style ) ? ' style="' . $style . '"' : '' )  . $dimensions .  '>' . 
        '</use>' .
      '</svg>' . 
    '</i>';

    return $output;
  }

  function get_svg_path( $source, $type ) {
    $uploads = wp_upload_dir();
    $intense_uploads_dir = trailingslashit( $uploads['basedir'] . '/intense-cache/icons' );

    if ( !is_dir( $intense_uploads_dir ) ) {
      Intense_Icon::get_icon_sources();
    }

    if ( file_exists( $intense_uploads_dir . '/child-theme/' . $source . '/' . $type . '.svg' ) ) {      
      return $intense_uploads_dir . '/child-theme/'  . $source . '/' . $type . '.svg';
    } else if ( file_exists( $intense_uploads_dir . '/theme/' . $source . '/' . $type . '.svg' ) ) {
      return $intense_uploads_dir . '/theme/' . $source . '/' . $type . '.svg';
    } else if ( file_exists( $intense_uploads_dir . '/plugin/' . $source . '/' . $type . '.svg' ) ) {
      return $intense_uploads_dir . '/plugin/' . $source . '/' . $type . '.svg';
    }

    return null;
  }

  function get_svg_url( $source, $type ) {
    $uploads = wp_upload_dir();
    $intense_uploads_dir = trailingslashit( $uploads['basedir'] . '/intense-cache/icons' );
    $intense_uploads_url = $uploads['baseurl'] . '/intense-cache/icons';

    if ( !is_dir( $intense_uploads_url ) ) {
      Intense_Icon::get_icon_sources();
    }

    if ( file_exists( $intense_uploads_dir . '/child-theme/' . $source . '/' . $type . '.svg' ) ) {      
      return $intense_uploads_url . '/child-theme/'  . $source . '/' . $type . '.svg';
    } else if ( file_exists( $intense_uploads_dir . '/theme/' . $source . '/' . $type . '.svg' ) ) {
      return $intense_uploads_url . '/theme/' . $source . '/' . $type . '.svg';
    } else if ( file_exists( $intense_uploads_dir . '/plugin/' . $source . '/' . $type . '.svg' ) ) {
      return $intense_uploads_url . '/plugin/' . $source . '/' . $type . '.svg';
    }

    return null;
  }  

  function get_svg( $source, $type, $tag = 'symbol' ) {
    //  This is used if we want to build the colors, height, and width into the returned svg code
    //  function get_svg( $source, $type, $tag = 'symbol', $height = '', $width = '', $fill = '' ) {
    $key = str_replace( ' ', '_', $source . '-' . $type );
    $path = $this->get_svg_path( $source, $type );
    $svg = '';
    //$size = '';

    if ( file_exists( $path ) ) {
      $full_svg = file_get_contents( $path );
      
      $viewbox = '';
      $svg_start_index = stripos( $full_svg, '<svg' );
      $end_svg_start_index = strripos( $full_svg, '</svg>' );
      $svg_open_tag_end = $end_svg_start_index;

      $found_svg_start = false;
      $found_svg_end = false;

      if ( $svg_start_index > -1 && $end_svg_start_index > -1 ) {
        for ( $i = $svg_start_index; $i < $end_svg_start_index; $i++ ) {
          $character = $full_svg[ $i ];

          if ( $found_svg_start ) {
            $svg .= $character;
          }

          if ( !$found_svg_start && $character == '>' ) {
            $found_svg_start = true;
            $svg_open_tag_end = $i;
          }
        }

        $viewbox_start = stripos( $full_svg, 'viewbox', $svg_start_index );

        if ( $viewbox_start ) {
          $found_viewbox_start = false;

          for ( $i=$viewbox_start; $i < $svg_open_tag_end; $i++ ) {
            $character = $full_svg[ $i ];

            if ( !$found_viewbox_start && ( $character == '"' || $character == "'" ) ) {
              $found_viewbox_start = true;
            } else if ( $found_viewbox_start && ( $character == '"' || $character == "'" ) ) {
                break;
            } else if ( $found_viewbox_start && ( $character != '"' && $character != "'" ) ) {
              $viewbox .= $character;
            }
          }
        }

        // if ( $height != '' ) {
        //   $size = 'height="' . $height . '" ';
        // }

        // if ( $width != '' ) {
        //   $size .= 'width="' . $width . '" ';
        // }

        // if ( $fill != '' ) {
        //   $fill = 'fill="' . $fill . '"';
        // }

        $svg = '<'.$tag.' id="' . esc_attr( $key ) . '"' . ( $viewbox != '' ? ' viewBox="' . $viewbox . '"' : ' viewBox="0 0 32 32"' ) . '>' . $svg .  '</'.$tag.'>';
        //$svg = '<'.$tag.' id="' . esc_attr( $key ) . '"' . $size . $fill . ( $viewbox != '' ? ' viewBox="' . $viewbox . '"' : ' viewBox="0 0 32 32"' ) . '>' . $svg .  '</'.$tag.'>';
      }

      unset( $full_svg );
    }

    return $svg;
  }

  public static function get_icon_sources() {
    $packs = array();

    if ( file_exists( INTENSE_PLUGIN_FOLDER . '/icons/' ) ) {
      $sources = Intense_Icon::get_source_folders( 'plugin', INTENSE_PLUGIN_FOLDER . '/icons/' );      
      $packs = array_merge( $packs, $sources );
    }

    if ( file_exists( get_template_directory() . '/intense_icons/' ) ) {
      $sources = Intense_Icon::get_source_folders( 'theme', get_template_directory() . '/intense_icons/' );
      $packs = array_merge( $packs, $sources );
    }

    if ( file_exists( get_stylesheet_directory() . '/intense_icons/' ) ) {
      $sources = Intense_Icon::get_source_folders( 'child-theme', get_stylesheet_directory() . '/intense_icons/' );
      $packs = array_merge( $packs, $sources );
    }

    ksort( $packs );

    return $packs;
  }

  public static function get_source_folders( $key, $path ) {
    $results = scandir( $path );
    $directories = array();

    $uploads = wp_upload_dir();
    $intense_uploads_dir = trailingslashit( $uploads['basedir'] . '/intense-cache/' );

    if ( !is_dir( $intense_uploads_dir ) ) {
      mkdir( $intense_uploads_dir, 0777, true );
    }

    if ( !is_dir( $intense_uploads_dir . 'icons/' ) ) {
      mkdir( $intense_uploads_dir . 'icons/', 0777, true );
    }

    if ( !is_dir( $intense_uploads_dir . 'icons/' . $key ) ) {
      mkdir( $intense_uploads_dir . 'icons/' . $key, 0777, true );
    }

    //unzip icon files
    foreach ( $results as $result ) {
      if ( $result === '.' or $result === '..' ) continue;

      if ( substr( $result, -strlen( ".zip" ) ) == ".zip" ) {

        if ( !is_dir( $intense_uploads_dir . 'icons/' . $key . '/' . str_replace( '.zip', '', $result ) . '/') ) {
          require_once(ABSPATH .'/wp-admin/includes/file.php'); //the cheat

          WP_Filesystem();
          $unzipfile = unzip_file( $path . $result, $intense_uploads_dir . 'icons/' . $key . '/' );

          if ( is_wp_error( $unzipfile ) ) {
            error_log( $unzipfile->get_error_message() );
          // } else {
          //   unlink( $path . $result );
          }
        }
      } else if ( is_dir( $path . $result ) ) {
        $dir_files = scandir( $path . $result );

        if ( !is_dir( $intense_uploads_dir . 'icons/' . $key . '/' . $result . '/') ) {
          mkdir( $intense_uploads_dir . 'icons/' . $key . '/' . $result . '/', 0777, true );

          foreach ($dir_files as $file) {
            if ( $file === '.' or $file === '..' ) continue;          

            copy( $path . $result . '/' . $file, $intense_uploads_dir . 'icons/' . $key . '/' . $result . '/' . $file);
          }        
        }         
      }
    }

    $path = $intense_uploads_dir . 'icons/' . $key . '/';

    $results = scandir( $path );

    foreach ( $results as $result ) {
        if ( $result === '.' or $result === '..' ) continue;        

        $title = ucwords( str_replace( '-', ' ', $result ) );
        $license = 'custom';
        $license_url = '';
        $author = '';
        $website = '';
        $source = '';
        $name = $result;

        if ( is_dir( $path . $result ) ) {
          $pack_info = null;

          if ( file_exists( $path  . $result . '/pack.json' ) ) {
            try {
              $pack_info = json_decode( file_get_contents( $path  . $result . '/pack.json' ), true );  
              $name = isset( $pack_info['name'] ) ? $pack_info['name'] : '';
              $title = isset( $pack_info['title'] ) ? $pack_info['title'] : '';
              $license = isset( $pack_info['license']['type'] ) ? $pack_info['license']['type'] : '';
              $license_url = isset( $pack_info['license']['url'] ) ? $pack_info['license']['url'] : '';
              $author = isset( $pack_info['author'] ) ? $pack_info['author'] : '';
              $website = isset( $pack_info['website'] ) ? $pack_info['website'] : '';
              $source = isset( $pack_info['source'] ) ? $pack_info['source'] : '';
            } catch (Exception $e) {
             $pack_info = null;
            }            
          }

          $directories[ $name ] = array( 
              'name' => $name,
              'title' => $title,
              'author' => $author,
              'license' => $license,
              'license_url' => $license_url,
              'website' => $website,
              'source' => $source,
              'path' => $path  . $result,
              'count' => Intense_Icon::get_folder_count( $path . '/' . $result)
            );
        }
    }

    return $directories;
  }

  public static function get_source_icons( $source ) {
    $icon_files = array();
    $icons = array();

    $uploads = wp_upload_dir();
    $intense_uploads_dir = trailingslashit( $uploads['basedir'] . '/intense-cache/icons' );

    if ( !is_dir( $intense_uploads_dir ) ) {
      Intense_Icon::get_icon_sources();
    }

    if ( file_exists( $intense_uploads_dir . '/child-theme/' . $source . '/' ) ) {
      $icon_files = scandir( $intense_uploads_dir . '/child-theme/' . $source . '/' );
    } else if ( file_exists( $intense_uploads_dir . '/theme/' . $source . '/' ) ) {
      $icon_files = scandir( $intense_uploads_dir . '/theme/' . $source . '/' );
    } else if ( file_exists( $intense_uploads_dir . '/plugin/' . $source . '/' ) ) {
      $icon_files = scandir( $intense_uploads_dir . '/plugin/' . $source . '/' );
    } else { 
      get_icon_sources();
    }

    foreach ( $icon_files as $key => $icon ) {
      if ( $icon != '.' && $icon != '..' && substr( $icon, -strlen( ".svg" ) ) == ".svg" ) {
        $icons[] = str_replace( '.svg', '', $icon );
      }
    }

    return $icons;
  }

  public static function get_folder_count( $path ) {
    $files = scandir( $path );
    $count = 0;
 
    foreach ($files as $key => $file) {
      if ( $file != '.' && $file != '..' && substr( $file, -strlen( ".svg" ) ) == ".svg" ) {
        $count++; 
      }        
    }

    return $count;
  }
}

add_shortcode( 'intense_list_icons', 'intense_list_icons_shortcode' );
function intense_list_icons_shortcode( $atts = null, $content = null ) {
  extract( shortcode_atts( array(
        'source' => null,
        'color' => null,
      ), $atts ) );

  if ( empty( $source ) ) $source = 'font-awesome';  

  $uploads = wp_upload_dir();
  $intense_uploads_dir = trailingslashit( $uploads['basedir'] . '/intense-cache/icons' );

  if ( !is_dir( $intense_uploads_dir ) ) {
    Intense_Icon::get_icon_sources();
  }

  if ( file_exists( $intense_uploads_dir . '/child-theme/' . $source . '/' ) ) {
    $icon_files = scandir( $intense_uploads_dir . '/child-theme/' . $source . '/' );
  } else if ( file_exists( $intense_uploads_dir . '/theme/' . $source . '/' ) ) {
    $icon_files = scandir( $intense_uploads_dir . '/theme/' . $source . '/' );
  } else if ( file_exists( $intense_uploads_dir . '/plugin/' . $source . '/' ) ) {
    $icon_files = scandir( $intense_uploads_dir . '/plugin/' . $source . '/' );
  }

  $icon_files = array_flip( $icon_files );
  $output = '';
  $count = 0;

  foreach ( $icon_files as $key => &$value ) {
    if ( $key != '.' && $key != '..' && substr( $key, -strlen( ".svg" ) ) == ".svg" ) {
      $type = str_replace( '.svg', '', $key );
      $output .= intense_run_shortcode( 'intense_icon', array( 
        'source' => $source, 
        'type' => $type,
        'size' => '3',
        'color' => $color
      ) );
      $output .= '&nbsp;';
      $count++;
    }
  }

   // $sources = Intense_Icon::get_icon_sources();
   // echo '<pre>'; print_r( $sources ); echo '</pre>';

  $output = '<h2>'.$source.' (' . $count . ')</h2>' . $output;

  return $output;
}
