<?php
class HelperFunctions {

function declareGlobalsFn () {
  // Functions declared inside a function have global scope	  
  
  function mycred_return_users_balance() {
      $user_id = get_current_user_id();
      return mycred_get_users_balance( $user_id );
  }
    
  function get_own_nonpremium_requests() {
      $user = wp_get_current_user();
          $data = array(
              'tags'   	=> array ( $user->user_nicename ),
              'category'	=> 'requests',
              'meta_key'	=> 'is_premium',
              'meta_value' => 0,
          );
      
      return get_posts_by_tag_category_postmeta($data);
  } 
   
  function get_own_premium_requests() {
      $user = wp_get_current_user();
          $data = array(
              'tags'   	=> array ( $user->user_nicename ),
              'category'	=> 'requests',
              'meta_key'	=> 'is_premium',
              'meta_value' => 1,
          );
      
      return get_posts_by_tag_category_postmeta($data);
  }
    
  function get_posts_by_tag_category_postmeta($data) {
      $args = array(
          'tax_query' => array(
              'relation' => 'AND',
              array(
                  'taxonomy' => 'post_tag',
                  'field' => 'slug',
                  'terms' => $data['tags'],
                  'include_children' => false
              ),
              array(
                  'taxonomy' => 'category',
                  'field' => 'slug',
                  'terms' => $data['category'],
              ),
          ),
          'meta_query' => array(
             array(
                 'key' => $data['meta_key'],
                 'value' => $data['meta_value'],
                 'compare' => '=',
             )
         )
      );	
      $postslist = get_posts( $args );
      
      return $postslist;
  }
    
  function get_fastsnipeObj() {
      return array(
          1 => array(
              'price' => 2250,
              'day_end' => 7,
              'color' => '#f8dd4d',
          ),
          2 => array(
              'price' => 1800,
              'day_end' => 14,
              'color' => 'hotpink',
          ),
          3 => array(
              'price' => 1100,
              'day_end' => 21,
              'color' => '#fd9f02',
          ),
          4 => array(
              'price' => 500,
              'day_end' => 35,
              'color' => '#87cefa',
          ),
      );
  }
    
  function subtract_fastcoins_by_start_date( $fastsnipeObj, $termintype_switch, $wochentag_start_text = null ) {
      [$bool, $user_balance, $price, $is_premium] = check_premium( $fastsnipeObj, $termintype_switch, $wochentag_start_text );
      // bool 1 - enough coins for booking
      // bool 0 - not enough cons for booking
      // bool null - no premium date

      if ( $bool ) {			
          $user_id = get_current_user_id();
          mycred_subtract( 'fastsnipe', $user_id, $price, 'Forms booking completed' );
      }
      
      return [$bool, $user_balance, $price, $is_premium];
  } 

  function check_premium( $fastsnipeObj, $fswitch, $wochentag_start_text ) {
      $user_id = get_current_user_id();
      $user_balance = mycred_get_users_balance( $user_id );

      if ( $fswitch == 'zeitraum' ) {
          $i = DateDiffFromNow($wochentag_start_text);	
      }
      else if ( $fswitch == 'sofort' ) {
          $i = 0;
      }

      if( $price = get_premium_price($fastsnipeObj, $i) ) {
          $is_premium = 1;
          if ( can_afford($user_balance, $price) ) {
              $bool = 1;
          }
          else {
               $bool = 0;
          }
      }
      else {
          $is_premium = 0;
          $bool = null;
      }

      return array($bool, $user_balance, $price, $is_premium);
  }

  function can_afford($user_balance, $price) {
      $can_afford = 0;
      $diff = $user_balance-$price;
      if( $diff >= 0 ) {
          $can_afford = 1;
      }

      return $can_afford;
  }

  function get_premium_price($fastsnipeObj, $i) {
      $price = 0;
      foreach ($fastsnipeObj as $key => $value) {
          $day_end = $fastsnipeObj[$key]['day_end'] - 2;
          if ($i <= $day_end) {
              $price = $fastsnipeObj[$key]['price'];
              break;
          }
      }
      return $price;
  }
    
  function DateDiffFromNow($d2) {
      $d1 = new DateTime();
      $d2 = new DateTime($d2);
      $dDiff = $d1->diff($d2);
      return $dDiff->format('%r%a');
  }
  
  function user_has_snipes_in_category($category) {
      $user = wp_get_current_user();
      $data = array(
          'tags'   	=> array ( $user->user_nicename ),
          'category'	=> $category,
      );
      $postslist = get_posts_by_tag_and_category($data);
      return count($postslist);
  }
    
  function remove_url_parameter() {		
      ?>
          <script>
          // START JAVASCRIPT		
          document.addEventListener("DOMContentLoaded", function(event) {					
              window.history.replaceState(null, null, window.location.pathname);		
          });
          // END JAVASCRIPT
          </script>
      <?php
  }
    
  function create_post_content($data) {
      dump_to_file('/var/www/lab/newfile.txt', $data, 'clear');	

      // DATE, STATUS & TERMINDETAILS
      if ($data[category] == 'requests') {
          $date = createDate($data[request][DATETIME_FROM], $data[request][DATETIME_TO], $data[category]);
          $status = '<p class="saving">Terminsuche läuft <span>.</span><span>.</span><span>.</span></p>';
          $buttons = '
                          <div id="button-appointment-container">
                              <a data-id="' . $data['request']['REQUEST_ID'] . '" id="button-delete-appointment" class="appointment-control">Löschen & FastCoins zurückerhalten</a>
                          </div>
                      ';
      }
      else if ($data[category] == 'expired') {
          $date = createDate($data[request][DATETIME_FROM], $data[request][DATETIME_TO], $data[category]);
          $status = '<p>Terminsuche abgelaufen</p>';
          $buttons = '
                          <div id="button-appointment-container">
                              <a data-id="' . $data['request']['REQUEST_ID'] . '" id="button-delete-appointment" class="appointment-control">Löschen & FastCoins zurückerhalten</a>
                          </div>
                      ';
      }
      else if ($data[category] == 'appointment') {
          $date = createDate($data[request][DATETIME], null, $data[category]);
          $status = '<p>Termin gefunden & gebucht</p>';
          $buttons = '
                          <div id="button-appointment-container">							
                              <a href="https://service.berlin.de/terminvereinbarung/termin/manage/" target="_blank" class="appointment-control">Termin selbst absagen</a>
                              <a data-id="' . $data['request']['REQUEST_ID'] . '" id="button-delete-appointment" class="appointment-control">Löschen</a>
                          </div>
                      ';

          //TERMINDETAILS PROCESS ID & AUTH KEY		
          $termindetails = 	'<table class="termindetails"><tr>' .
                              '<td class="min">Vorgangsnummer:</td>' .
                              '<td>' . 
                              $data[request]['PROCESS_ID'] .
                              '</td></tr>' . 
                              '<tr><td class="min>Absagecode:</td>' . 
                              '<td>' . 
                              $data[request]['AUTH_KEY'] .
                              '</td></tr>' .
                              '</tr></table>';
      }
      else if ($data['category'] == 'request-failed-logged-out') {
          php_console_log('failed appointment');
          $date = createDate($data[request][DATETIME_FROM], $data[request][DATETIME_TO], $data[category]);
          $status = '<p>Du bist nicht angemeldet :*(<br>Registriere dich jetzt</p>';
      }

      // BUERGERAEMTER LIST		
      $buergeraemter = '<table class="paginated-table"><th></th><tbody>';
      $count_buergeraemter = count($data['request']['BUERGERAEMTER']);
      foreach($data[request]['BUERGERAEMTER'] as $buergeramt) {
          $buergeraemter .= "<tr><td>$buergeramt</td></tr>";
      }
      $buergeraemter = $buergeraemter . '</tbody></table>';

      // DIENSTLEISTUNG
      $dienstleistung = $data[request]['DIENSTLEISTUNG'];
      
      // CHECK IF PREMIUM POST
      $fastsnipeObj = get_fastsnipeObj();
      [$bool, $user_balance, $price, $is_premium] = check_premium( $fastsnipeObj, 'zeitraum', $data['request']['DATETIME_FROM'] );
      
      // RESTRICT ACCESS TO POST BY USER
      $post_content = add_rule_id($data, $post_content, 'beginning');
      
      // CONTENT CONCATENATE
      if ($buttons) {
          $post_content .= $buttons;
      }
      
      $post_content .= 	"<h4 class=\"heading-backend\">Status</h4>
                           <div class=\"status-div\">$status</div>";
      
      if (strcmp('request-failed-logged-out', $data['category']) !== 0) {
          $post_content .= "<h4 class=\"heading-backend\">Preis</h4>
                           <div class=\"preis-div\">$price <img src=\"http://zinomedia.de/terminsnipe/wp-content/uploads/sites/6/2020/03/630865.svg\" alt=\"fastcoin\"></div>";
      }		
      
      $post_content .= 	 "<h4 class=\"heading-backend\">Was?</h4>
                           <div class=\"dienstleistung-div\">$dienstleistung</div>";

      if ($termindetails) {
          $post_content .= 					 
                           "<h4 class=\"heading-backend\">Termindetails</h4>
                           <div class=\"date-div\">$termindetails</div>";
      }	

      $post_content .= 					 
                           "<h4 class=\"heading-backend\">Wann?</h4>
                           <div class=\"date-div\">$date</div>						 
                           <h4 class=\"heading-backend\">Wo?</h4>							 
                           <div class=\"paginated-table-div\">
                               <p>Insgesamt $count_buergeraemter Bürgerämter</p>
                              $buergeraemter
                              <span class=\"prev-table\">« zurück</span><span class=\"next-table\">weiter »</span>
                           </div>";
      
      // RESTRICT ACCESS TO POST BY USER
      $post_content = add_rule_id($data, $post_content, 'ending');		

      return $post_content;
  }
    
  function createDate($dateTimeString_from, $dateTimeString_to, $category) {	
      $monthDayNames = array (
                              'Jan' => 'Januar',
                              'Feb' => 'Februar',
                              'Mar' => 'März',
                              'Apr' => 'April',
                              'May' => 'Mai',
                              'Jun' => 'Juni',
                              'Jul' => 'Juli',
                              'Aug' => 'August',
                              'Sep' => 'September',
                              'Oct' => 'Oktober',
                              'Nov' => 'November',
                              'Dec' => 'Dezember',
                              'Mon' => 'Montag',
                              'Tue' => 'Dienstag',
                              'Wed' => 'Mittwoch',
                              'Thu' => 'Donnerstag',
                              'Fri' => 'Freitag',
                              'Sat' => 'Samstag',
                              'Sun' => 'Sonntag',
      );

      // CREATE  DATE STRING
      $datetime_from = new DateTime($dateTimeString_from);	
      if ($category == 'requests' || $category == 'expired' || $category == 'request-failed-logged-out') {
          $datetime_to = new DateTime($dateTimeString_to);
          if($datetime_from->format('d') == $datetime_to->format('d') && // SAME DAY BOOKINGS
              $datetime_from->format('m') == $datetime_to->format('m') && 
              $datetime_from->format('y') == $datetime_to->format('y')) {
                  $date = $monthDayNames[$datetime_from->format('D')] . ', ' . 
                  $datetime_from->format('d') . '. ' . 
                  $monthDayNames[$datetime_from->format('M')] . ' ' . 
                  $datetime_from->format('Y') . ' von ' . 
                  $datetime_from->format('H') . ':' . 
                  $datetime_from->format('i') . ' Uhr bis ' . 
                  $datetime_to->format('H') . ':' . 
                  $datetime_to->format('i') . ' Uhr';				
              }
          else { # TWO DIFFERENT DATETIME BOOKINGS
              $date = '<table class="dateTable"><tr>' .
                      '<td>Von:</td>' .
                      '<td>' . 
                      $monthDayNames[$datetime_from->format('D')] . ', ' . 
                      $datetime_from->format('d') . '. ' . 
                      $monthDayNames[$datetime_from->format('M')] . ' ' . 
                      $datetime_from->format('Y') . ' ' .
                      $datetime_from->format('H') . ':' . 
                      $datetime_from->format('i') . ' Uhr' .
                      '</td></tr>' . 
                      '<tr><td>Bis:</td>' . 
                      '<td>' . 
                      $monthDayNames[$datetime_to->format('D')] . ', ' . 
                      $datetime_to->format('d') . '. ' . 
                      $monthDayNames[$datetime_to->format('M')] . ' ' . 
                      $datetime_to->format('Y') . ' ' .
                      $datetime_to->format('H') . ':' . 
                      $datetime_to->format('i') . ' Uhr' .
                      '</td></tr>' .
                      '</tr></table>';
          }
      }
      else if ($category == 'appointment') {
          $date = 'pao';
          $date = $monthDayNames[$datetime_from->format('D')] . ', ' . 
                  $datetime_from->format('d') . '. ' . 
                  $monthDayNames[$datetime_from->format('M')] . ' ' . 
                  $datetime_from->format('Y') . ' um ' . 
                  $datetime_from->format('H') . ':' . 
                  $datetime_from->format('i') . ' Uhr';
      }

      return $date;
  }
    
  function add_rule_id($data, $post_content, $switch) {
      if ($data['category'] == 'requests' || $data['category'] == 'expired' || $data['category'] == 'appointment') {
          if ($switch == 'beginning') {
              $rule_id = mpr_get_user_rule_id($data);
              $post_content = '[mepr-show if="rule: ' . $rule_id . '"]';
          }
          else if ($switch == 'ending') {
              $post_content .= '[/mepr-show]';
          }			
      }
      
      return $post_content;
  }
    
  function mpr_get_user_rule_id($data) {
      global $wpdb;
      $user_email = $data[user]->user_email;
      $rule_id = $wpdb->get_var( "SELECT rule_id FROM wp_6_mepr_rule_access_conditions WHERE access_condition = '$user_email'" );
      
      return $rule_id;
  }
  
  function is_child_of( $id ) {
      return ( is_page() && $id === get_post()->post_parent );
  }

  function is_menu_page() {
      $id = 980;
      //return ( is_page() && $id === get_post()->post_parent || page_id() === $id );
      if ( is_page() && $id === get_post()->post_parent || page_id() === $id ) {
          return 1;
      }
      else {
          return 0;
      }
  }
    
  function set_filter_tag($settings) {		
      // CURRENT USER OBJECT
      $user = wp_get_current_user();
      
      // SET RIGHT CATEGORY
      if(page_id() === 975) {			
          $category = 'requests';		
      }
      else if(page_id() === 978) {
          $category = 'expired';	
      }
      else if(page_id() === 965) {
          $category = 'appointment';	
      }

      // CREATE TAG TO DISPLAY RIGHT CONTENT IN CONTENT GRID POSTS MODULE
      $filter_tags = get_user_filter_tags($user);	
      $filter_tag = $filter_tags[$category];
      
      // GET TERM ID BY TAG SLUG AND CHANGE tax_post_post_tag of CONTENT GRID
      $tag = get_term_by('slug', $filter_tag, 'post_tag');
      $settings->tax_post_post_tag = $tag->term_id;
  }
    
  function page_id() {
      global $wp_query;
      return $wp_query->post->ID;
  }
    
  function php_console_log($data) {		
      $output = $data;
      if (is_array($output)) {
          $output = implode(',', $output);
      }
      echo "<script>console.log( '" . $output . "' );</script>";
  }
    
  function current_url() {
      return (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
  }
    
  function redirect($url, $statusCode = 303) {
     header('Location: ' . $url, true, $statusCode);
     die();
  }
    
  function connect_to_server($server) {
      if ($server == 'zinomedia') {
          return	new wpdb('terminsnipe','dIHB6JLk0CBBx1p7','terminsnipe','localhost');
      }
  }
    
  function dump_to_file($file, $data, $method = '') {
      if ($method == 'clear') {
          $f = @fopen($file, "r+");
          if ($f !== false) {
              ftruncate($f, 0);
              fclose($f);
          }
          
          $timestamp = "\n[" . date('m/d/Y h:i:sa', time()) . "]\n";
          file_put_contents($file, $timestamp, FILE_APPEND | LOCK_EX);
      }

      if (is_array($data) || is_object($data)) {
          $data = print_r($data, true);
      }
      
      file_put_contents($file, $data.PHP_EOL , FILE_APPEND | LOCK_EX);		
  }
    
  function sort_aoa_by_value($array, $value) {
      $arr = array();
      foreach ($array as $key => $item) {
         $arr[$item[$value]][$key] = $item;
      }
      ksort($arr, SORT_NUMERIC);
      return $arr;
  }
    
  function json_request($url, $data = array(), $method = 'POST', $header = '') {
      $options = array(
        'http' => array(
          'method'  => $method,
          'content' => json_encode( $data ),
          'header'=>  $header
          )
      );
      $context  = stream_context_create( $options );
      $result = file_get_contents( $url, false, $context );
      //$response = json_decode( $result );
      
      return $result;
  }
    
  function mbpr_restapi_delete_rule_by_title($data) {
      $rule = get_page_by_title( $data[post_title], OBJECT, $data[post_type] );	
      if ($rule) {
          $url = 'http://zinomedia.de/terminsnipe/wp-json/mp/v1/rules/' . $rule->ID;
          $response = json_request(	$url,
                                      array(),
                                      'DELETE',
                                      "Content-Type: application/json\r\nAccept: application/json\r\nAuthorization: sKjdz2pUHx"
                                  );
          return $response;
      }	
  }
    
  function mbpr_restapi_add_rule($data) {
      global $wpdb;

      $data_request = array(	'rule_type'   			=> $data[rule_type],
                              'unauth_excerpt_type' 	=> $data[unauth_excerpt_type],
                              'rule_content'    		=> $data[rule_content],
                           );	
      $response = json_request(	'http://zinomedia.de/terminsnipe/wp-json/mp/v1/rules',
                                  $data_request,
                                  'POST',
                                  "Content-Type: application/json\r\nAccept: application/json\r\nAuthorization: sKjdz2pUHx"
                              );
      $response_decoded = json_decode($response);
      
      // RENAME POST BECAUSE API SETS NO TITLE		
      $wpdb->update( 
          'wp_6_posts', 
          array( 
              'post_title' => $data[post_title],
          ), 
          array( 'ID' => $response_decoded->id )
      );

      // FIX: MANUALLY ADD CORRECT RULE CONDITIONS
      $wpdb->insert( 
          'wp_6_mepr_rule_access_conditions', 
          array( 
              'rule_id' 			=> $response_decoded->id, 
              'access_type' 		=> $data[access_type],
              'access_operator' 	=> $data[access_operator],
              'access_condition' 	=> $data[access_condition]
          )
      );

      return $response;
  }
    
  function get_posts_by_tag_and_category($data) {
      $args = array(
          'tax_query' => array(
              'relation' => 'AND',
              array(
                  'taxonomy' => 'post_tag',
                  'field' => 'slug',
                  'terms' => $data[tags],
                  'include_children' => false
              ),
              array(
                  'taxonomy' => 'category',
                  'field' => 'slug',
                  'terms' => $data[category],
              ),
          )
      );	
      $postslist = get_posts( $args );
      
      return $postslist;
  }	
    
  function get_posts_by_tag($data) {
      $args = array(
          'post_status' => $data[post_status],
          'tax_query' => array(
              'relation' => 'AND',
              array(
                  'taxonomy' => 'post_tag',
                  'field' => 'slug',
                  'terms' => $data[tags],
                  'include_children' => false
              )
          )
      );	
      $postslist = get_posts( $args );
      
      return $postslist;
  }
    
  function delete_posts_by_tag_and_category($data) {
      $postslist = get_posts_by_tag_and_category($data);
      foreach ($postslist as $post) {
          wp_delete_post( $post->ID, true );
      }
  }

  function delete_posts_by_tag($data) {
      // Rework to use get_posts_by_tag if possible
      $args = array(
          'post_status' => 'any',
          'tax_query' => array(
              array(					
                  'taxonomy' => 'post_tag',
                  'field' => 'slug',
                  'terms' => $data[tags],
                  'include_children' => true
              ),
          )
      );	
      $postslist = get_posts( $args );

      foreach ($postslist as $post) {
          wp_delete_post( $post->ID, true );
      }
  }
    
  function delete_tag_by_slug($slug) {
      $term = get_term_by('slug', $slug, 'post_tag');
      wp_delete_term($term->term_id, 'post_tag');
  }
    
  function get_user_filter_tags($user) {
      $filter_tag = array();
      $filter_tag[requests] = $user->user_nicename . '-r';
      $filter_tag[expired] = $user->user_nicename . '-e';
      $filter_tag[appointment] = $user->user_nicename . '-a';
      return $filter_tag;
  }	  
}
}

$ob = new HelperFunctions();
$ob->declareGlobalsFn();