<?php
/**
 * Directory module
 * 
 * Provides basics methods called from public templates
 * These methods can be overriden. Discover logic and examples on :
 * @url http://dev.linea21.com/projects/linea21/wiki/Override
 * @url http://dev.linea21.com/projects/linea21/wiki/Personnalisation_de_l%27interface_publique
 * 
 * @package linea21\modules\yellowpages
 * @author $Author$ - linea21 <info@linea21.com>
 * @version $Id$ 
 * @access public
 * @license http://opensource.org/licenses/gpl-3.0.html
 */

include_once(override('../yellowpages/'.SQL.'.inc.php'));

/**
 * DisplayUrlAddYellowpages()
 * @return
 * affichage d'ajout d'un organisation
 **/
if(!function_exists('DisplayUrlAddYellowpages')) {

  function DisplayUrlAddYellowpages() {

    $link_table= array('rub'=> $GLOBALS['links'][U_L]['directory-add']['linkvalue']);
    $content='<a class="button buttonmargin" href="'.HrefMaker($link_table).'" title="'._t('yp','add_public').'"><i class="fa fa-plus" aria-hidden="true"></i> '._t('yp','add_public').'</a>'.PHP_EOL;
    echo $content;
  }
}

/**
 * DisplayListYellowPages()
 * affichage de l'annuaire
 * @param $debut
 * @param unknown $limite
 * @param integer $filter
 * @param integer $search
 * @return
 **/
if(!function_exists('DisplayListYellowPages')) {

  function DisplayListYellowPages($debut, $limite = SELECT_LIMIT, $filter= -1, $search= -1){

  	if($filter == 'LEVEL') {
  		$levels = getLevelChildren($GLOBALS['sql_object']->DBSelect(SQL_getLevelsList()), $search);
  		$search = array_extract($levels, 'level_id', true, 'children');
  	}

    $result_yp = $GLOBALS['sql_object'] -> DBSelect(SQL_get_Display_ypList($debut, $limite, $filter, $search));
    $result_nb_yp = $GLOBALS['sql_object'] -> DBSelect(SQL_get_Display_CountypList($filter, $search));

    $bdd_nb_yp=$result_nb_yp[0]['num_rows'];


    $sep = ' <span class="separator">/</span> ';
    
    if ($filter==-1) $table_link=array('rub' => $GLOBALS['links'][U_L]['directory']['linkvalue']);
    else $table_link=array('rub' => $GLOBALS['links'][U_L]['directory']['linkvalue'],'id' => $search, 'filter' => $filter);

    $bdd_nb_yp_display = $bdd_nb_yp;

    if($bdd_nb_yp!=0) DisplayAlphaBeta($filter,$search);

    $content = '';
    
    $content .= get_linkin_page($table_link, $bdd_nb_yp, $debut);
    //$content .='<hr />'.PHP_EOL;
    $content .= '<div class="grid-3 has-gutter-xl">'.PHP_EOL;
    if($result_yp!=0)
    {

      for($i=0; $i<count($result_yp); $i++) {
      	
      	$levels = $GLOBALS['sql_object']->DBSelect(SQL_getLevelsList());
      	$level = getLevelParent($levels, $result_yp[$i]['level_id'], 0);
      	
        $link_table= array('rub'=> $GLOBALS['links'][U_L]['directory-detail']['linkvalue'],'id'=>$result_yp[$i]['yellowp_id'], 'name'=>$result_yp[$i]['yellowp_name']);
        if(is_array($level)) {
        	$link_level = array('rub' => $GLOBALS['links'][U_L]['directory']['linkvalue'], 'filter' => $GLOBALS['filters'][U_L]['level']['linkvalue'], 'id' => $level['id'], 'name' => $level['name']);
        }
        $yp_name=formatText($result_yp[$i]['yellowp_name'], '2HTML');
        $yp_activity=formatText(cutText($result_yp[$i]['yellowp_activity'],150), '2HTML');
        $yp_level=formatText($result_yp[$i]['level_name'], '2HTML');
        $content .= '<div class="directory-entry">'.PHP_EOL;
        $content.='<h2>'.PHP_EOL;
        $content.='<a href="'.HrefMaker($link_table).'" title="'.formatText($yp_name, '2ATT').'">'.$yp_name.'</a>'.PHP_EOL;
        $content.='</h2>'.PHP_EOL;
        $content.='<p> '.mb_ucfirst(_t('yp','activity')).' : '.$yp_activity.'</p>'.PHP_EOL;
				
        if(is_array($level)) $content .=  '<p class="filter_info"> ' . $level['label'] . ' : <a href="' . HrefMaker($link_level) . '" title="' . $GLOBALS['filters'][U_L]['level']['desc'] . ' : ' . formatText($level['name'], '2ATT') . '" class="filter_info_theme">' . $level['name'] . '</a></p>' . PHP_EOL;
        $content .= '</div>' . PHP_EOL;


        //$content.='<hr />'.PHP_EOL;
      }
      $content .= '</div>' . PHP_EOL;
    }
    else
    {
      $content.='<p class="info"> '._t('yp','noresult').'</p>';
    }

    $content .= get_linkin_page($table_link, $bdd_nb_yp, $debut);

    echo $content;

  }

}

/**
 * DisplayAlphaBeta()
 * affichage de la liste alphabétique
 * @param $filter
 * @param $filter_id
 * @return
 **/
if(!function_exists('DisplayAlphaBeta')) {

  function DisplayAlphaBeta($filter,$filter_id){

    $result_alphabetical = $GLOBALS['sql_object'] -> DBSelect(SQL_get_req_alphabetical());

    $content='<div id="directory-alpha" class="pagination">'.PHP_EOL;
    $content.=_t('divers','trialpha').' :';
    for($i=0; $i<count($result_alphabetical); $i++)  {
      $link_aff_classic= HrefMaker(array('rub'=>$GLOBALS['links'][U_L]['directory']['linkvalue'], 'filter'=>"alpha", 'id'=>$result_alphabetical[$i]['first_letter']));
      if ($i==0) $separator="";
      else $separator="-";
      if ($filter ==  'alpha' && $result_alphabetical[$i]['first_letter']==strtoupper($filter_id))
      $content.=$separator.' <span>'.$result_alphabetical[$i]['first_letter'].'</span> '.PHP_EOL;
      else $content.=$separator.' <a href="'.$link_aff_classic.'" title="'.$result_alphabetical[$i]['first_letter'].'" >'.$result_alphabetical[$i]['first_letter'].'</a> '.PHP_EOL;
    }
    $content.='</div>'.PHP_EOL;
    echo  $content;
  }

}

/**
 * DisplayOneYellowPages()
 * affichage d'une organisation
 * @param $yp_id
 * @return
 **/
if(!function_exists('DisplayOneYellowPages')) {

  function DisplayOneYellowPages($yp_id){

    $data= $GLOBALS['sql_object'] -> DBSelect(SQL_getdetyp($yp_id, array('P')));

    if($data == 0) error_redirect();
    
    $levels = $GLOBALS['sql_object']->DBSelect(SQL_getLevelsList());
    $level = getLevelParent($levels, $data[0]['level_id'], 0);

    if (count($data) != 1) exit;
    else {
      $content= '';
      if(is_array($level)) {
      	$link_level = array('rub' => $GLOBALS['links'][U_L]['directory']['linkvalue'], 'filter' => $GLOBALS['filters'][U_L]['level']['linkvalue'], 'id' => $level['id'], 'name' => $level['name']);
      }
      $link_self= array('rub'=> $GLOBALS['links'][U_L]['directory']['linkvalue'],'id'=> $yp_id);

      $yp_name=formatText($data[0]['yellowp_name'], '2HTML');
      $yp_activity=formatText(cutText($data[0]['yellowp_activity'],150), '2HTML');
      $yp_level=formatText($data[0]['level_name'], '2HTML');
      $yp_street=formatText($data[0]['yellowp_street'], '2HTML');
      $yp_postal_code=formatText($data[0]['yellowp_postal_code'], '2HTML');
      $yp_city=formatText($data[0]['yellowp_city'], '2HTML');
      $yp_phone=formatText($data[0]['yellowp_phone'], '2HTML');
      $yp_fax=formatText($data[0]['yellowp_fax'], '2HTML');
      $yp_email=formatText($data[0]['yellowp_email'], '2HTML');
      $yp_website=formatText($data[0]['yellowp_website'], '2HTML');
      $yp_lat=$data[0]['yellowp_latitude'];
      $yp_long=$data[0]['yellowp_longitude'];

      $content.='<h1>'.$yp_name.'</h1>'.PHP_EOL;
      $content.='<p class="published_by">'.PHP_EOL;
      $content.= formatted_permalink($link_self);
      $content.='</p>'.PHP_EOL;
      $content.='<dl id="det_yp"><dt> '.mb_ucfirst(_t('yp','adresse')).' : </dt><dd>'.$yp_street.' '.$yp_postal_code.' '.$yp_city.'</dd>'.PHP_EOL;
      $content.='<dt> '.mb_ucfirst(_t('yp','phone')).' : </dt><dd>'.empty_nc($yp_phone).'</dd>'.PHP_EOL;
      $content.='<dt> '.mb_ucfirst(_t('yp','fax')).': </dt><dd>'.empty_nc($yp_fax).'</dd>'.PHP_EOL;
      $content.='<dt> '.mb_ucfirst(_t('yp','email')).' : </dt><dd><a href="mailto:'.$yp_email.'" title="'.formatText($yp_email, '2ATT').'">'.$yp_email.'</a></dd>'.PHP_EOL;
      if ($data[0]['yellowp_website']<>"") $content.='<dt> '.mb_ucfirst(_t('yp','website')) 	.' : </dt><dd><a href="'.$data[0]['yellowp_website'].'" title="'.formatText($yp_website, '2ATT').'">'.$yp_website.'</a></dd>'.PHP_EOL;
      else $content.='<dt> '.mb_ucfirst(_t('yp','website')).' : </dt><dd>'.empty_nc($yp_website).'</dd>'.PHP_EOL;
      $content.='<dt> '.mb_ucfirst(_t('yp','activity')).' : </dt><dd>'.$yp_activity.'</dd>'.PHP_EOL;
      if ($yp_level != 0) {
        $content.='<dt> '.mb_ucfirst($level['label']).' : </dt><dd><a href="'.HrefMaker($link_level).'" title="'.formatText($level['name'], '2ATT').'">'.$level['name'].'</a>'.PHP_EOL;
      }

      $content.='</dl>'.PHP_EOL;

    }

    echo $content;

    if(defined('MAP_ENGINE') && MAP_ENGINE == 'leaflet') {
    	echo generateLMap('map', $data, 16) ;
    } else {
    	echo generateGMap('map', $data, 16) ;
    }

  }

}

/**
 * generateMap()
 * generate a Map with Gmaps
 * @return
 **/
if(!function_exists('generateLMap')) {

	function generateLMap($id, $data, $zoom) {

		$lat     = $data[0]['yellowp_latitude'];
		$long    = $data[0]['yellowp_longitude'];
		$name    = formatText($data[0]['yellowp_name'], '2HTML');
		$address = formatText($data[0]['yellowp_street'], '2HTML').'<br />'.formatText($data[0]['yellowp_postal_code'], '2HTML'). ' - '.formatText($data[0]['yellowp_city'], '2HTML');

		if($lat==0 || $long==0) return false;

		if(defined('MAP_TILELAYER')) $tile_layer = MAP_TILELAYER;
		else $tile_layer = "http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png";
		$map  ='<div id="'.$id.'" class="map"></div>';
		$map .= '<script type="text/javascript">
		$(document).ready(function() {

				var map = L.map("map").setView(['.($lat+0.0012).', '.($long-0.004).'], '.$zoom.');
				
				L.tileLayer("'.$tile_layer.'", {
					maxZoom: 18,
					attribution: "Map data &copy; <a href=\"http://openstreetmap.org\">OpenStreetMap</a> contributors, <a href=\"http://creativecommons.org/licenses/by-sa/2.0/\">CC-BY-SA</a>"
				}).addTo(map);


		L.marker(['.($lat).', '.($long).']).addTo(map)
			.bindPopup("<b>'.$name.'<\/b><br />'.$address.'").openPopup();

	});
	</script>';

		return $map;
	}

}

/**
 * generateMap()
 * generate a Map with Gmaps
 * @return
 **/
if(!function_exists('generateGMap')) {

  function generateGMap($id, $data, $zoom) {

    $lat     = $data[0]['yellowp_latitude'];
    $long    = $data[0]['yellowp_longitude'];
    $name    = formatText($data[0]['yellowp_name'], '2HTML');
    $address = formatText($data[0]['yellowp_street'], '2HTML').'<br />'.formatText($data[0]['yellowp_postal_code'], '2HTML'). ' - '.formatText($data[0]['yellowp_city'], '2HTML');

    if($lat==0 || $long==0) return false;

    footerAddJS('http://maps.googleapis.com/maps/api/js?v=3&sensor=false');

    $map  ='<div id="'.$id.'" class="map"></div>';
    $map .= '<script type="text/javascript">
         $(document).ready(function() {
          var markerPosition = new google.maps.LatLng('.$lat.', '.$long.');

          var latlng = new google.maps.LatLng('.($lat+0.0015).', '.($long-0.004).');
          var myOptions = {
                 zoom: ' . $zoom . ',
                 center: latlng,
                 mapTypeId: google.maps.MapTypeId.ROADMAP
             	};
           var map = new google.maps.Map(document.getElementById("'.$id.'"), myOptions);


          	myInfoWindowOptions = {
          		content: "<div class=\"info-window-content\"><b>'.$name.'<\/b><br />'.$address.'<\/div>",
          		maxWidth: 275
          	};

          	infoWindow = new google.maps.InfoWindow(myInfoWindowOptions);

          	marker = new google.maps.Marker({
        		draggable: false,
        		raiseOnDrag: false,
        		map: map,
        		position: markerPosition
        	  });



        	google.maps.event.addListener(marker, "click", function() {
        		infoWindow.open(map,marker);
        	});

        	infoWindow.open(map,marker);
         });
         </script>';

    return $map;
  }

}


/**
 * DisplayConfirmAdd()
 * affichage confirmation de l'ajout
 * @return
 **/
if(!function_exists('DisplayConfirmAdd')) {

  function DisplayConfirmAdd() {
    $link_table= array('rub'=> $GLOBALS['links'][U_L]['directory']['linkvalue']);
    $content='<p class="confirmed">'._t('yp','confirm_pub').' <a href="'.HrefMaker($link_table).'" title="'.formatText(_t('yp','confirm_pub2'), '2ATT').'" >'._t('yp','confirm_pub2').'</a>'.PHP_EOL;
    $content.='</p>'.PHP_EOL;
    echo $content;
  }

}

/**
 * DisplayAddYellowPages()
 * affichage formulaire d'ajout
 * @param integer $btn
 * @param $table
 * @return
 **/
if(!function_exists('DisplayAddYellowPages')) {

  function DisplayAddYellowPages() {
    include_once('../lib/input_helpers.php');
    include_once('../class/class.yellowpages.php');
    $form_name='';
    $form_activity='';
    $form_level='';
    $form_street='';
    $form_postal_code='';
    $form_city='';
    $form_phone='';
    $form_fax='';
    $form_email='';
    $form_website='http://';

    
    //  testing $_POST['yp_name'] and not $_POST['valider'] because of OPERA bug
    if(isset($_POST['yp_name'])) {
      $table[0]=$_POST['yp_name'];
      $table[1]=$_POST['yp_activity'];
      $table[2]=$_POST['yp_level'];
      $table[3]=$_POST['yp_street'];
      $table[4]=$_POST['yp_postal_code'];
      $table[5]=$_POST['yp_city'];
      $table[6]='';
      $table[7]=str_replace(' ', '', $_POST['yp_phone']);
      $table[8]=str_replace(' ', '', $_POST['yp_fax']);
      $table[9]=$_POST['yp_email'];
      ($_POST['yp_website'] != 'http://') ? $table[10]=$_POST['yp_website'] : $table[10]='';
      $table[11]="D";
      $yp_object= new yellowpages;

      // prevent spam
      if($_SESSION['securityaction']!=md5($_POST['securitycode'])) {
        $integrity=_t('security','message');
      }
      if(!isset($integrity)) $integrity=$yp_object->CheckDataIntegrity($table);

      if (is_string($integrity)) {
        echo "<p class=\"error\">".$integrity."</p>";
        $form_name=formatText($_POST['yp_name'], '2FIELD');
        $form_activity=formatText($_POST['yp_activity'], '2FIELD');
        $form_level=$_POST['yp_level'];
        $form_street=formatText($_POST['yp_street'], '2FIELD');
        $form_postal_code=$_POST['yp_postal_code'];
        $form_city=formatText($_POST['yp_city'], '2FIELD');
        $form_phone=str_replace(' ', '', $_POST['yp_phone']);
        $form_fax=str_replace(' ', '', $_POST['yp_fax']);
        $form_email=formatText($_POST['yp_email'], '2FIELD');
        $form_website=formatText($_POST['yp_website'], '2FIELD');
      } else {
        $result=$yp_object->AddYellowPages($table, $GLOBALS['sql_object']);
        $link_confirm=HrefMaker(array('rub'=> $GLOBALS['links'][U_L]['directory']['linkvalue']));
        if(is_numeric($result)) DisplayConfirmAdd();
        else  echo "<p class=\"error\">".system_error()."</p>";
      }
    }
    
    // select-box des niveaux
    $data=$GLOBALS['sql_object']->DBSelect(SQL_getLevelsList());
    $select_level=LevelSelectBox($data, "yp_level", $form_level);
    
    if (!isset($integrity) || is_string($integrity)) {
      $form ='<div class="sub-title">'._t('yp','h1_public_add').'</div>';
      $form.='<form action="'. CURRENT_APP_URL .'index.php" method="post">'.PHP_EOL;
      $form.='<div>'.PHP_EOL;
      $form.='<p><label for="yp_name" class="labelised">'.mb_ucfirst(_t('yp','name2')).' * : </label>'.PHP_EOL;
      $form.='<input type="text" maxlength="150"  name="yp_name" id="yp_name" value="'.$form_name.'" class="textfield" /></p>'.PHP_EOL;
      $form.='<p><label for="yp_activity" class="labelised">'.mb_ucfirst(_t('yp','activity')).' * : </label>'.PHP_EOL;
      $form.='<input type="text" maxlength="255"  name="yp_activity" id="yp_activity" value="'.$form_activity.'" class="textfield" /></p>'.PHP_EOL;
      $form.='<p><label for="yp_level" class="labelised">'.mb_ucfirst(_t('yp','level')).' : </label>'.PHP_EOL;
      $form.=$select_level.'</p>'.PHP_EOL;
      $form.='<p><label for="yp_street" class="labelised">'.mb_ucfirst(_t('yp','street')).' * : </label>'.PHP_EOL;
      $form.='<input type="text" maxlength="200" class="textfield" name="yp_street" id="yp_street"  value="'.$form_street.'" /></p>'.PHP_EOL;
      $form.='<p><label for="yp_postal_code" class="labelised">'.mb_ucfirst(_t('yp','postal_code')).' * : </label>'.PHP_EOL;
      $form.='<input type="text" maxlength="6" class="textfield" name="yp_postal_code" id="yp_postal_code" value="'.$form_postal_code.'" /></p>'.PHP_EOL;
      $form.='<p><label for="yp_city" class="labelised">'.mb_ucfirst(_t('yp','city')).' * : </label>'.PHP_EOL;
      $form.='<input type="text" maxlength="100" class="textfield" name="yp_city" id="yp_city" value="'.$form_city.'" /></p>'.PHP_EOL;
      $form.='<p><label for="yp_phone" class="labelised">'.mb_ucfirst(_t('yp','phone')).' : </label>'.PHP_EOL;
      $form.='<input type="text" maxlength="14" class="textfield phone-format" name="yp_phone" id="yp_phone" value="'.$form_phone.'" /></p>'.PHP_EOL;
      $form.='<p><label for="yp_fax" class="labelised">'.mb_ucfirst(_t('yp','fax')).' : </label>'.PHP_EOL;
      $form.='<input type="text" maxlength="14" class="textfield phone-format" name="yp_fax" id="yp_fax" value="'.$form_fax.'" /></p>'.PHP_EOL;
      $form.='<p><label for="yp_email" class="labelised">'.mb_ucfirst(_t('yp','email')).' * : </label>'.PHP_EOL;
      $form.='<input type="text" maxlength="150" class="textfield" name="yp_email" id="yp_email" value="'.$form_email.'" /></p>'.PHP_EOL;
      $form.='<p><label for="yp_website" class="labelised">'.mb_ucfirst(_t('yp','website')).' : </label>'.PHP_EOL;
      $form.='<input type="text" maxlength="150" class="textfield" name="yp_website" id="yp_website" value="'.$form_website.'" /></p>'.PHP_EOL;
      $form.='<p class="yp_antispam">'.PHP_EOL;
      $form.='<span class="labelmargin labelised">' . mb_ucfirst(_t('security','info2')) . ' : </span>'.PHP_EOL;
      $form.='<img src="../lib/securitycode.php" alt="' .mb_ucfirst( _t('security','info2')) .'" id="securityimg"  />';
      $form.='</p>'.PHP_EOL;
      $form.='<p><label for="securitycode" class="labelised">' . mb_ucfirst(_t('antispam','info')) . ' * : </label>'.PHP_EOL;
      $form.='<input type="text" class="textfield" id="securitycode" maxlength="5" name="securitycode" /></p> ';
      $form.='<input type="hidden" id="rub_yp" value="'.$GLOBALS['links'][U_L]['directory-add']['linkvalue'].'" name="rub" /> ';
      $form.='<input type="submit" class="submitbut"  value="'._t('btn','valid').'" name="valider" id="valider" />'.PHP_EOL;
      $form.='</div>'.PHP_EOL;
      $form.='</form>'.PHP_EOL;


      if(U_L == 'fr') {
      	footerAddJS('../lib/js/jquery-mask-plugin/dist/jquery.mask.min.js');
      	footerAddInlineJS("
			 	$( '.phone-format').each(function( index ) {
				  	$(this).mask('00 00 00 00 00');
				});");
      }
      echo $form;
    }
  }

}
?>