<?php
function wosmpl_leaflet_activate() {
    wp_enqueue_script('leaflet-js', plugin_dir_url( dirname( __FILE__ ) ) . 'public/js/leaflet.js', array( 'jquery' ), '1.3.4', false);
    wp_enqueue_script('markercluster-js', plugin_dir_url( dirname( __FILE__ ) ) . 'public/js/leaflet.markercluster-src.js', array( 'jquery' ), '1.3.4', false);
    wp_enqueue_style( 'leaflet-css', plugin_dir_url ( dirname( __FILE__ ) ) . 'public/css/leaflet.css');
    wp_enqueue_style( 'marker-cluster-css', plugin_dir_url ( dirname( __FILE__ ) ) . 'public/css/MarkerCluster.css');
    wp_enqueue_style( 'marker-cluster-default-css', plugin_dir_url ( dirname( __FILE__ ) ) . 'public/css/MarkerCluster.Default.css');

}

function wosmpl_pages_with_shortcode($shortcode, $args = array()) {
    if(!shortcode_exists($shortcode)) {
        // shortcode was not registered (yet?)
        return null;
    }

    // replace get_pages with get_posts
    // if you want to search in posts
    $pages = get_pages($args);
    $list = array();

    foreach($pages as $page) {
        if(has_shortcode($page->post_content, $shortcode)) {
            $list[] = $page;
        }
    }

    return $list;
}

function wosmpl_get_cat_marker_icon($cat_id){
    //get_option is caching result
    $cat_icon_path = get_option('wosmpl_cat_icon_path');
    $cat_icon_name_prefix = get_option('wosmpl_cat_icon_name_prefix');
    return  $cat_icon_path . $cat_icon_name_prefix . $cat_id . '.png';
}
function wosmpl_get_categories_with_nb()
{
    $geo_cats = get_option('wosmpl_geo_cats', []);
    $contents = wosmpl_get_geolocalized_contents();

    array_walk($geo_cats, function (&$cat) { $cat['nb'] = 0; });

    foreach ($contents as $c) {
      if ($c->type == 'wosmpl_partners') {
        for($i=0;$i < count($geo_cats);$i++) {
          if ($geo_cats[$i]['id'] == $c->cat) {
            $geo_cats[$i]['nb']++;
            break;
          }
        }
      }
    }

    return $geo_cats;
}

function wosmpl_get_array_by_category($contents) {
    $result = [];
    $tmp_result = [];
    $geo_cats = get_option('wosmpl_geo_cats', []);
    $named_cats = [];
    foreach ($geo_cats as $gc) {
        $named_cats[$gc['id']] = $gc['name'];
    }
    foreach ($contents as $c) {
        if ($c->cat > 0) {
            if (!isset($tmp_result[$c->cat])) {
                $tmp_result[$c->cat] = [];
            }
            $tmp_result[$c->cat][] = $c;
        }

    }
    //sort by contents size
    usort($tmp_result,function($a,$b) {
        if (count($a) == count($b)) {
            return 0;
        }
        return (count($a) > count($b)) ? -1 : 1;

    });
    // Set result with cat name keys
    foreach ($tmp_result as $contents) {
        $fc = $contents[0];
        $result[$named_cats[$fc->cat]] = ['id'=>$fc->cat,
                                          'contents'=>$contents];
    }
    //var_dump($result);
    return $result;
}

function wosmpl_get_map_url(){
    $options = get_option( 'wosmpl_options' );
    $map_url = '';
    if (isset($options['wosmpl_main_map_page_id'])) {
        $p_id = $options['wosmpl_main_map_page_id'];
        if ($p_id > 0) {
            $map_url = get_permalink($p_id);
        }
    }
    return $map_url;
}
function wosmpl_get_categories_ul($ul_class='sub-menu wosmpl-cat',$with_map_link=FALSE) {
    $map_url = wosmpl_get_map_url();
    $cats = wosmpl_get_categories_with_nb();
    $o = '';
    if (count($cats) > 0) {
        $o = '<ul class="'.$ul_class.'">';

        foreach ($cats as $cat) {
            if ($cat['nb'] > 0) {
                $img_url = wosmpl_get_cat_marker_icon($cat['id']);
                $li_open = '<li>';
                $img_width = '50';
                if ($ul_class =='sub-menu') {
                    $li_open = '<li class="menu-item">';
                    $img_width = '35';
                }
                $o .= $li_open;
                $o .= '<img src="'.$img_url.'" width="'.$img_width.'" /> ';
                $o .= '<span>('.$cat['nb'].')</span>';
                if ($map_url != '') {
                    $o .= ' <a href="'.$map_url.'?code_categorie='.$cat['id'].'" >'.$cat['name'].'</a>';
                }

                $o .= '</li>';
            }

        }
        $o .= '</ul>';
        if ($map_url != '' && $with_map_link === TRUE) {
            $o .= '<a href="'.$map_url.'">Carte partenaire</a>';
        }



    }
    return $o;
}

/*
* Get loc geocat correspondance
* Will not more be needed in future version (dynamically retrieve cat data from kohinos)
*/

function get_local_geocat_id_correspondance ($kohinos_rubrique_slug) {
   $id = 21;
   switch ($kohinos_rubrique_slug) {
   	  case 'produit-de-lagriculture-et-elevage':
	  $id = 17;
	  break;
   	  case 'sports-et-loisirs':
	  $id = 15;
	  break;
   	  case 'commerce-alimentaire':
	  $id = 2;
	  break;
   	  case 'restaurant-bar-traiteur':
	  $id = 1;
	  break;
   	  case 'commerces-divers':
	  $id = 8;
	  break;
   	  case 'metiers-dart-creations':
	  $id = 3;
	  break;
   	  case 'habillement-mode-accessoires':
	  $id = 4;
	  break;
   	  case 'papeterie-librairie-presse-edition':
	  $id = 6;
	  break;
   	  case 'marches-amap':
	  $id = 22;
	  break;
   	  case 'web-multimedia-communication-imprimerie':
	  $id = 14;
	  break;
   	  case 'sorties-culturelles':
	  $id = 9;
	  break;
   	  case 'informatique-electronique':
	  $id = 10;
	  break;
   	  case 'decoration-ameublement-bricolage-jardin':
	  $id = 7;
	  break;
   	  case 'artisanat-constructions-reparations':
	  $id = 12;
	  break;
   	  case 'transports-livraisons':
	  $id = 13;
	  break;
   	  case 'divers':
	  $id = 21;
	  break;
   	  case 'hygiene-beaute':
	  $id = 5;
	  break;
   	  case 'sante-bien-etre':
	  $id = 11;
	  break;
   	  case 'immobilier':
	  $id = 19;
	  break;
   	  case 'services-a-la-personne':
	  $id = 20;
	  break;
   	  case 'formation-education':
	  $id = 16;
	  break;

   }
   return $id;
}

/**
* Programmaticaly insert (or update if kohinos_id found) a "partenaire" content
* Missing equivalents : wosmpl_partner_specialty, wosmpl_partner_challenge
*/

function wosmpl_insert_or_update_partner ($data) {
  require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/queries.php';
  $pid = wosmpl_get_page_matching_kohinos_id($data['id']) ??
         wosmpl_get_page_matching_kohinos_raison($data['raison']);

  // Default values
  $args = [
    'post_content' => $data['description'],
    'post_title' => $data['raison'],
    'post_type' => 'wosmpl_partners',
    'post_status' => 'publish',
    'meta_input' => [
      'wosmpl_kid' => $data['id'],
    ],
  ];

  $defaultMetaAtCreation = [
    'wosmpl_geo_cat' => '',
    'wosmpl_presta_type' => '',
    'wosmpl_partner_challenge' => '',
    'wosmpl_partner_specialty' => '',
    'wosmpl_partner_email_visible' => '',
    'wosmpl_partner_open_hours' => '',
    'wosmpl_partner_phone_visible' => '',
    'wosmpl_partner_website_visible' => '',
    'wosmpl_partner_pict' => '',
  ];

  if (isset($data['horaires'])) {
    $args['meta_input']['wosmpl_partner_open_hours'] = $data['horaires'];
  }

  if (isset($data['web'])) {
    $args['meta_input']['wosmpl_partner_website'] = $data['web'];
    $args['meta_input']['wosmpl_partner_website_visible'] = 'yes';
  }
  if (!empty($data['contacts'])) {
     //let's retrieve the last one (TODO : manage multi contacts for a single partner)
     $cdata = array_pop($data['contacts']);
     $tel = $cdata['tel'];
     $email = $cdata['email'];
     $visible_tel = $visible_email = 'no';

     if ($cdata['enabled'] == TRUE) {
       $visible_tel = $visible_email = 'yes';
     }

     $args['meta_input']['wosmpl_partner_phone'] = $tel;
     $args['meta_input']['wosmpl_partner_email'] = $email;
     $args['meta_input']['wosmpl_partner_phone_visible'] = $visible_tel;
     $args['meta_input']['wosmpl_partner_email_visible'] = $visible_email;
  }
  if (!empty($data['geolocs'])) {
     //let's retrieve the last one (TODO : manage multi location for a single partner)
     $gdata = array_pop($data['geolocs']);
     $args['meta_input']['wosmpl_latlon'] = $gdata['geoloc']['lat'] . ',' . $gdata['geoloc']['lon'];
     $args['meta_input']['wosmpl_post_addr'] = $gdata['geoloc']['adresse'] . ' ' . $gdata['geoloc']['cpostal'] . ' ' . $gdata['geoloc']['ville'];
  }
  if (!empty($data['rubriques'])) {
     //let's retrieve the last one (TODO : manage multi rubriques for a single partner)
     $rub = array_pop($data['rubriques']);
     $args['meta_input']['wosmpl_geo_cat'] = get_local_geocat_id_correspondance ($rub['slug']);
  }
  if (!empty($data['metier'])) {
     $args['meta_input']['wosmpl_presta_type'] = $data['metier'];
     $args['meta_input']['wosmpl_partner_specialty'] = $data['metier'];
  }

  /**
   * @author Mathieu Poisbeau (contact@freepius.net)
   * @date   2020-11-16
   *
   * Retrieve and upload the media from Kohinos
   */
  if ($media = $data['media']['src'] ?? null) {
    // To have access to the wosmpl_upload_file() and wosmpl_remove_files() functions
    require_once plugin_dir_path( dirname( __FILE__ ) ) . 'admin/image.php';

    // First, we remove the last files if there are
    wosmpl_remove_files($pid);

    // Then, we upload the new Kohinos file using Curl
    $mediaUrl = get_option( 'wosmpl_options' )['wosmpl_kohinos_url'].$media;

    $respCurl = (new Wp_Http_Curl())->request($mediaUrl, [
      '_redirection' => true,
      'decompress' => false,
      'filename' => '',
      'stream' => false,
      'user-agent' => get_bloginfo('name'),
    ]);

    if (! is_wp_error($respCurl)) {
      $args['meta_input']['wosmpl_partner_pict'] = wosmpl_upload_file($respCurl['body'], false)['file_url'];
    }
  }

  if (is_numeric($pid)) {
     $args['ID'] = $pid;
     $post_id = wp_update_post($args);
     if ($post_id) {
       foreach ($args['meta_input'] as $key => $val) {
         update_post_meta($post_id, $key, $val);
       }
     }
  } else {
    $args['meta_input'] += $defaultMetaAtCreation;
    $post_id = wp_insert_post($args);
  }

  if ($post_id) {
    // it worked :)
    $pid = $post_id;
  }

  return $pid;
}

/**
 * Retrieve one, several or all partners from kohinos
 *
 * @param WP_REST_Request $request
 *
 * @return array
 */
function retrieve_partners_from_kohinos( WP_REST_Request $request)
{
  $options = get_option( 'wosmpl_options' );
  $kohinos_server = $options['wosmpl_kohinos_url'];

  $args = [
    'headers' => [
      'API-AUTH-TOKEN' => $options['wosmpl_kohinos_api_key'],
      'accept' => 'application/json',
    ],
    // @fixby Mathieu Poisbeau (contact@freepius.net) 2020-11-16
    // The following args avoid warnings in debug mode
    // because the wp-includes/class-wp-http-curl.php needs them
    '_redirection' => true,
    'decompress' => false,
    'filename' => '',
    'stream' => false,
    'user-agent' => get_bloginfo('name') .'-apicall',
  ];

  $curl = new Wp_Http_Curl();
  $ids = \explode(',', $request['ids'] ?? '');
  $responses = [];

  // Retrieve the partners from Kohinos
  foreach ($ids as $id) {
    $respCurl = $curl->request("$kohinos_server/api/prestataires/$id", $args);

    if (! is_wp_error($respCurl)) {
      $response = json_decode($respCurl['body'], true);

      // Case of one Partner API request
      if ('' !== $id) {
        $responses[] = $response;
      }
      // Case of all Partners API request => not necessary to request again.
      else {
        $responses = $response;
        break;
      }
    }
  }

  // Insert or update partners in Wordpress
  foreach ($responses as &$p) {
    // @fixme: why don't select the very first 'prestataire'?
    // Question and comment by Mathieu Poisbeau (contact@freepius.net): 2020-11-16
    //if ($p['id'] > 1) {
    $p['pid'] = wosmpl_insert_or_update_partner($p);
    //}
  }

  return [\array_keys($responses[0]), $responses];
}
