<?php
/* $Id: searchresults.php 1 2006-06-07 08:07:41Z hodaka $
 *  ------------------------------------------------------------------------ *
 *                XOOPS - PHP Content Management System                      *
 *                    Copyright (c) 2000 XOOPS.org                           *
 *                       <http://www.xoops.org/>                             *
 *  ------------------------------------------------------------------------ *
 *                     MyAddress - XOOPS addressbook                         *
 *                        <http://www.kuri3.net/>                            *
 *             Copyright (c) 2004 by hodaka <hodaka@kuri3.net>               *
 * ------------------------------------------------------------------------- *
 * This program is free software; you can redistribute it and/or modify      *
 * it under the terms of the GNU General Public License as published by      *
 * the Free Software Foundation; either version 2 of the License, or         *
 * (at your option) any later version.                                       *
 *                                                                           *
 * You may not change or alter any portion of this comment or credits        *
 * of supporting developers from this source code or any supporting          *
 * source code which is considered copyrighted (c) material of the           *
 * original comment or credit authors.                                       *
 *                                                                           *
 * This program is distributed in the hope that it will be useful,           *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of            *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             *
 * GNU General Public License for more details.                              *
 *                                                                           *
 * You should have received a copy of the GNU General Public License         *
 * along with this program; if not, write to the Free Software               *
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA  *
 */

if( ! defined( 'XOOPS_ROOT_PATH' ) ) exit;

//-------------------------------------------------------------------//
//               Display search results in list style                //
//-------------------------------------------------------------------//

function search_results( $mode, $cid, $skey, $c_id=0, $needSearch="y" ) {
	global $myts, $xoopsDB, $cattree, $xoopsTpl;
	global $table_addressbook, $table_company, $table_view;
	global $myaddress_numperpage, $myaddress_catorder;
	global $isadmin, $myaddress_mid, $my_uid, $my_groups, $mod_url;
	global $op, $from;

	$children = $cattree->getAllChildId( $cid );
	$children = push_gperm_array( $children, "myadrs_category" );

	$keyarray = get_keyarray();
	$skey_last = count($keyarray) - 2;
	$skey_all = count($keyarray) - 1;

	$requestStart = TRUE;
	$requestEnd = TRUE;
	if ($skey == 0) {
		$requestStart = FALSE;
	} elseif ( $skey == $skey_last ) {
		$requestEnd = FALSE;
	} elseif ( $skey == $skey_all ) {
		$requestStart = FALSE;
		$requestEnd = FALSE;
	}
	
	switch ( $mode ) {
		// name-based mode
		case 1:
			// get valid terms from $table_view (only name-based mode)
			$select_term = "SELECT table_title from $table_view where title_indication='1' order by title_sequence";
			$term_result = 	$xoopsDB->query( $select_term ) ;
			include_once( XOOPS_ROOT_PATH . '/modules/myaddress/include/viewitems_sqlfield.php');	// include $myaddress_viewtitle
			$fields = "";
			$valid_array = array();
			$addresses['title'] = array();
			$addresses['width'] = array();
			while($validterm = $xoopsDB->fetchArray( $term_result )){
				$fields .= $myaddress_viewtitle[$validterm['table_title']]['belong_table'] . "." . $validterm['table_title'] . ",";
				// assign header
				array_push($addresses['title'],$myaddress_viewtitle[$validterm['table_title']]['viewterm']);
				array_push($addresses['width'],$myaddress_viewtitle[$validterm['table_title']]['width']);
				// valid(= print to html) term 
				array_push($valid_array,$validterm['table_title']);
			}
			$fields = trim($fields,",");	// trim fields
			// when only cname required, get with cdivision
			if(preg_match("/c\.cname/",$fields) && ! preg_match("/c\.cdivision/",$fields) ){ 
				$fields = str_replace("c.cname","concat(c.cname,'<br>',c.cdivision) as cname",$fields);
			}
			// width recalcurate
			$width_sum = array_sum($addresses['width']);
			for($w = 0; $w < count($addresses['width']); $w++){
				$addresses['width'][$w] = round($addresses['width'][$w]/$width_sum*100);
			}

			$count = "SELECT count(l.aid) FROM $table_addressbook l";
			$select = "SELECT l.aid, l.cid, l.c_id, l.uid, {$fields} FROM $table_addressbook l LEFT JOIN $table_company c ON l.c_id=c.c_id ";
			$where = " WHERE";
			if ( $requestStart ) {
				$where .= " substring(l.last_name_jh, 1, 2) >= '$keyarray[$skey]' AND";
			}
			if ( $requestEnd ) {
				$skey2 = $skey + 1;
				$where .= " substring(l.last_name_jh, 1, 2) < '$keyarray[$skey2]' AND";
			}
			$where .=" ( l.uid = $my_uid || l.disclosed = 1 )";
			$where .= " AND l.cid IN (";
			foreach( $children as $child ) {
				$where .= " $child,";
			}
			$where .= " $cid )";
			$order =" ORDER BY l.fullname_jh";
			break;

		// company-based mode
		case 2:
			$count = "SELECT count(c_id) FROM $table_company";
			$select = "SELECT c_id, cid, cdivision, cname, cphone, cfax, cweb  FROM $table_company";
			$where = " WHERE";
			if ($op == "list" && $needSearch ="n") {
				$where .= " c_id=$c_id";
			} else {
				if ( $requestStart ) {
					$where .= " substring(cname_jh, 1, 2) >= '$keyarray[$skey]' AND";
				}
				if ( $requestEnd ) {
					$skey2 = $skey + 1;
					$where .= " substring(cname_jh, 1, 2) < '$keyarray[$skey2]' AND";
				}
//				$where .=" uid = $my_uid";
				$where .= " cid IN (";
				foreach( $children as $child ) {
					$where .= " $child,";
				}
				$where .= " $cid )";
			}
			$order =" ORDER BY cname_jh";
			break;
		default:
			break;
	}

	// get the total numbers of affected addresses
	$sql = $count . $where;

	$res_total = $xoopsDB->query( $sql );
	list( $total ) = $xoopsDB->fetchRow( $res_total );
	$total = intval($total);

	$addresses['lang_search'] = _MD_MYADDRESS_SEARCH;	 
	$addresses['lang_results'] = _MD_MYADDRESS_RESULTS;	 
	$addresses['total_found'] = $total;	

	if ( $total == 0 ) {
		$addresses['lang_nonefound'] = _MD_MYADDRESS_NOFOUND;

	} else  {
		// make a page navigation clause
		if ( $total > $myaddress_numperpage ) {
			include XOOPS_ROOT_PATH."/class/pagenav.php";
			$nav = new XoopsPageNav( $total, $myaddress_numperpage, $from, 'from', "mode=$mode&cid=$cid&op=search&skey=$skey" );	
			$nav_clause = $nav->renderNav( 10 );
		} else {
			$nav_clause = "";
		}

		// display the information of the present page
		$to = $from + $myaddress_numperpage;
		if( $to > $total ) $to = $total ;
		$navinfo = sprintf( _MD_MYADDRESS_NAVINFO, $from + 1, $to, $total );
		$addresses['pagenav'] = $navinfo ."&nbsp;". $nav_clause ."&nbsp";

		switch ( $mode ) {
			// name-based mode
			case 1:
				// get addressbook
				$sql = $select . $where . $order;
				$result = $xoopsDB->query( $sql, $myaddress_numperpage, $from );
				// assign addressbook data to template
				while($addr_fetchdata = $xoopsDB->fetchArray( $result ) ) {
					foreach($valid_array as $key => $value){
						${$value} = $addr_fetchdata[$value];
					}
					$aid = $addr_fetchdata['aid'];	// need this always
					$cid = $addr_fetchdata['cid'];	// need this always
					$c_id = $addr_fetchdata['c_id'];	// need this always
					$uid = $addr_fetchdata['uid'];	// need this always
					$acid =& $cid;	//$table_addressbook's field in cid ... but in this code we use acid.
					$ccphone =& $cphone;	// same reason.

					$myaddressdata = array();
					foreach($valid_array as $key => $value){
						switch($value){
							case "fullname":
								if( $fullname != "" ) {
									$myaddressdata['fullname'] = "<A href='".$mod_url."/viewaddress.php?mode=".$mode."&amp;cid=".$acid."&amp;op=edit&amp;aid=".$aid."'>".$myts->makeTboxData4Show($fullname)."<A>";
								} else {
									$myaddressdata['fullname'] = "Error: no fullname";
								}
								break;
							case "myemail1" :
							case "myemail2" :
							case "myemail3" :
							case "myemail4" :
								if ( ${$value} != "" ) {
									$myaddressdata[$value] = "<A HREF='mailto:". $myts->makeTboxData4Show(${$value}) ."'><IMG SRC='".XOOPS_URL."/images/icons/email.gif' BORDER='0' ALT='".sprintf( _SENDEMAILTO, $myts->makeTboxData4Show(${$value}) )."' /></A>";
								} else {
									$myaddressdata[$value] = "";
								}
								break;
							case "cname" :
								if( $cname != "" ) {
									$myaddressdata['cname'] = "<A href='".$mod_url."/viewcompany.php?mode=".$mode."&amp;cid=".$ccid."&amp;op=list&amp;c_id=".$c_id."'>". $cname . "</A>";
								} else {
									$myaddressdata['cname'] = "";
								}
								break;
							case "cdivision" :
								if( $cdivision != "" ) {
									$myaddressdata['cdivision'] = "<A href='".$mod_url."/viewcompany.php?mode=".$mode."&amp;cid=".$ccid."&amp;op=list&amp;c_id=".$c_id."'>".$myts->makeTboxData4Show($cdivision)."</A>";
								} else {
									$myaddressdata['cdivision'] = "";
								}
								break;
							default :
								$myaddressdata[$value] = $myts->makeTboxData4Show(${$value});
						}
					}

/*					if( $isadmin || $my_uid == $uid ) {
						$myaddressdata['adminlink'] = "<A HREF='". $mod_url ."/viewaddress.php?cid=$cid&op=edit&aid=". $aid ."'>". _MD_MYADDRESS_EDIT. "</A> | <A HREF='". $mod_url ."/viewaddress.php?cid=$cid&op=del&aid=". $aid ."'>". _MD_MYADDRESS_DELETE ."</A>";
						$addresses['title']['lang_adminlink'] = "";
					} else {
						$myaddressdata['adminlink'] = "";
					}
*/
					$addresses['myaddress'][] = $myaddressdata;
				}
				break;

			// company-based mode
			case 2:
				// get a company profile
				$sql = $select . $where . $order;

				$result = $xoopsDB->query( $sql, $myaddress_numperpage, $from );
				// assign header
				$addresses['lang_cname'] = _MD_MYADDRESS_COMPANY;
				$addresses['lang_cdivision'] = _MD_MYADDRESS_DIVISION;
				$addresses['lang_cphone'] = _MD_MYADDRESS_PHONE;
				$addresses['lang_cfax'] = _MD_MYADDRESS_FAX;
				$addresses['lang_cweb'] = _MD_MYADDRESS_WEB;
				$addresses['lang_send'] = _SEND;

				// assign a company profile data to the template
				while( list( $c_id, $ccid, $cdivision, $cname, $cphone, $cfax, $cweb ) = $xoopsDB->fetchRow( $result ) ) {
//					if( $caller == "viewcat.php" ) {
//						$companyprofile['cname'] = "<A href='".$mod_url."/viewcompany.php?mode=".$mode."&amp;cid=".$ccid."&amp;op=list&amp;c_id=".$c_id."'>".$myts->makeTboxData4Show($cname)."</A>";
//						$companyprofile['cdivision'] = "<A href='".$mod_url."/viewcompany.php?mode=".$mode."&amp;cid=".$ccid."&amp;op=list&amp;c_id=".$c_id."'>".$myts->makeTboxData4Show($cdivision)."</A>";
//					} else {
					$companyprofile['cname'] = $myts->makeTboxData4Show($cname);
					$companyprofile['cdivision'] = $myts->makeTboxData4Show($cdivision);
//					}
					$companyprofile['c_id'] = $myts->makeTboxData4Show($c_id);
					$companyprofile['company'] = $myts->makeTboxData4Show($cname)." ".$myts->makeTboxData4Show($cdivision);
					$companyprofile['cphone'] = $myts->makeTboxData4Show($cphone);
					$companyprofile['cfax'] = $myts->makeTboxData4Show($cfax);
					$companyprofile['ccid'] = $myts->makeTboxData4Show($ccid);
					if ( $cweb != "" && trim($cweb) != "http://" ) {
						$companyprofile['alt_msg'] = sprintf( _VISITWEBSITE, $myts->makeTboxData4Show($cweb) );
						$companyprofile['cweb'] = $myts->makeTboxData4Show($cweb);
//						$companyprofile['cweb'] = "<A HREF='".$myts->makeTboxData4Show($cweb)."' TARGET='_blank'><IMG SRC='".XOOPS_URL."/images/icons/www.gif' BORDER='0' ALT='".sprintf( _VISITWEBSITE, $myts->makeTboxData4Show($cweb) )."' /></A>";
					} else {
						$companyprofile['cweb'] = "";
					}
//					if( $uid == $my_uid || $isadmin ) {
					$companyprofile['lang_edit'] = _MD_MYADDRESS_EDIT;
					$companyprofile['lang_delete'] = _MD_MYADDRESS_DELETE;
//					$companyprofile['adminlink'] = "<A HREF='". $mod_url ."/viewcompany.php?cid=$cid&op=edit&c_id=". $c_id ."'>". _MD_MYADDRESS_EDIT. "</A> | <A HREF='". $mod_url ."/viewcompany.php?cid=$cid&action=del&c_id=". $c_id ."'>". _MD_MYADDRESS_DELETE ."</A>";
//					}
					$addresses['mycompany'][] = $companyprofile;
				}
				break;

			default:
				echo "mode is broken!";
				break;
		}
	}
	return $addresses;
}
?>
