<?php

function search($splitMsg, $askMessage, $grpid, $rerun=null) {
 global $askcommand, $globalsettings, $channelInfoNew;
   $countSplit=0;
   $like="%";

   $current=-1;

   $c=1;
   foreach ($splitMsg as $searchTerm) { 
    if ($c>2) {
	 if (substr($searchTerm,0,8) == "channel:" && explode(":",$searchTerm)[1]=="current") $current=1;
	 if (substr($searchTerm,0,6) == "topic:") $topicclausel=" and topicname like '%".pg_escape_string($globalsettings["db"]["pg_conn"], explode(":",$searchTerm)[1])."%' "; 
	 if (substr($searchTerm,0,6) == "order:") $orderclausel=$searchTerm; 
     if (substr($searchTerm,0,1) == "-") $notlikearray[]=substr($searchTerm,1,strlen($searchTerm)); 

     if (substr($searchTerm,0,6) != "order:" && substr($searchTerm,0,1) != "-" && substr($searchTerm,0,6) != "topic:" && substr($searchTerm,0,8) != "channel:" ) $likearray[]=pg_escape_string($globalsettings["db"]["pg_conn"], $searchTerm);
    }
    $c++;
   } // foreach

   $like="%";
   if (isset($likearray)) if (is_array($likearray)) foreach ($likearray as $likes) $like.=$likes."%";
      
   $notlike="";
   if (isset($notlikearray)) if (is_array($notlikearray)) foreach ($notlikearray as $notlikes) $notlike.=" and lower(cleanmessage) not like lower('%".pg_escape_string($globalsettings["db"]["pg_conn"], $notlikes)."%')"; 

   if (!isset($topicclausel)) $topicclausel="";
   
   if (isset($orderclausel)) {
    $order=explode(":",$orderclausel);
	switch ($order[1]) {
		case "res": $sqlorder=" order by width desc";
		break;
		case "msg": $sqlorder=" order by msgid desc";
		break;
		case "date": $sqlorder=" order by msgdate desc";
		break;
		case "size": $sqlorder=" order by size desc";
		break;
		case "dur": $sqlorder=" order by duration desc";
		            $duration=0;
		break;
        default: $sqlorder=" order by width desc, height desc, size desc"; // $sqlorder=" order by cleanmessage";
	} // switch ($order[1])
   } else $sqlorder=" order by width desc, height desc, size desc"; // $sqlorder=" order by cleanmessage";

  $o_channelInfoKey=$grpid;
  if (array_key_exists("redirectout_tochannel", $channelInfoNew[$grpid]) && $channelInfoNew[$grpid]["redirectout"] != -1 && $current==-1) {
   $o_channelInfoKey=$grpid; $grpid=$channelInfoNew[$grpid]["redirectout"];
  } else {
   if (array_key_exists("redirectout_tochannel", $channelInfoNew[$o_channelInfoKey]) && $channelInfoNew[$o_channelInfoKey]["redirectout_tochannel"] != -1) {
    $grpid=$channelInfoNew[$o_channelInfoKey]["redirectout_tochannel"];	  
   } // if ($channelInfoNew[$grpid]["redirectout_tochannel"] != -1) 
  } // if ($channelInfoNew[$grpid]["redirectout"] != -1 && $current==-1)

  $sql="select msgid, substr(message, 0, ".$globalsettings["message"]["cuttext"].") as message, substr(cleanmessage, 0, ".$globalsettings["message"]["cuttext"].") as cleanmessage, msgdate, link, width, height, size, filename, mime_type, grouped_id, duration from chan_".$grpid." where type='messageMediaDocument' and (mime_type like 'audio%' or (mime_type like 'video%' and duration > 15) or (mime_type like 'application%' and mime_type not like '%sticker%')) and (lower(cleanmessage) like lower('".$like."') or lower(message) like lower('".$like."'))".$notlike.$topicclausel.$sqlorder;
  
   if ($rerun) $sql.=" limit ".$globalsettings["search"]["maxresults"];
   
   $result=pg_query($globalsettings["db"]["pg_conn"], $sql);
   $numrows=pg_num_rows($result);

    if ($numrows == 0) {
     $returnMsg[0]="TOUSER";
     $returnMsg[1]="SEARCH: no matches found";
     return $returnMsg;
    }

   $returnMsg[1]="";
   while ($row = pg_fetch_array($result))  {

    $durationout="";
    if (isset($duration)) {
	 $duration=round($row["duration"] / 60);
	 $durationout=" - ".$duration." min.";
    } // if (isset($duration))
		
	if ($row['grouped_id'] == -1) { $albumout="| Ⓢ"; } else $albumout="| Ⓐ";

    if ($numrows > $globalsettings["search"]["maxresults"] && $rerun==false) {
     $returnMsg[0]="TOUSER";
     $returnMsg[1]="SEARCH: to many results(".$numrows."), print only the first ".$globalsettings["search"]["maxresults"]." hits<br>(use search: <b>".$askcommand."search ".htmlspecialchars("<searchterm> -word1 -word2 ...")."</b>)<br>";
     $returnMsg[2]="SEARCHMAXRESULTS";
     return $returnMsg;
    }
 
    if ($row['width'] == -1) { $dim=""; } else  $dim="<code>".$row['width']."x".$row['height']."</code> ".$albumout." | ";
    $text=htmlspecialchars($row['cleanmessage']);
  
    if (str_contains($row['mime_type'], 'audio')) { $performer=" | ".htmlspecialchars($row['message']); } else $performer="";    
    if ($row['size']==-1) { $fsize=$row['filename']; } else $fsize=round($row['size'] / 1024 / 1024)." MB".$performer;
            
    $returnMsg[0]="TOCHAN";
    if (isset($orderClausel) && $order[1] == "res") {
     $returnMsgRevert[]=$dim."<a href=\"".$row['link']."\">".$text."</a><br><code>".$fsize."</code><br>"; 
    } else {
		
    if (array_key_exists("redirectout_tochannel", $channelInfoNew[$o_channelInfoKey]) && $channelInfoNew[$o_channelInfoKey]["redirectout"] != -1 && $current == -1 ) { 
     switch ($channelInfoNew[$o_channelInfoKey]["redirectout_mode"]) {
	  case "link": $returnMsg[1].=$dim."<a href=\"".$row["link"]."\">".$text."</a><br><code>".$fsize."</code>".$durationout."<br>"; 
	  break;
//	  case "id": $returnMsg[1].=$dim."".$text." <br><code>".$globalsettings["request"]["requestcommand"]."#getfile ".$row["msgid"]."</code> | ".date($globalsettings["bot"]["defaultdateformat"],$row["msgdate"])."<br>".$fsize."<br>"; // with date 
	 case "id": 

	 
	           $returnMsg[1].=$dim."".$text." <br><code>".$globalsettings["request"]["requestcommand"]."#getfile ".$row["msgid"]."</code><br>".$fsize.$durationout."<br>";
	  break;
     } // switch ($channelInfoNew[$o_channelInfoKey]["redirectout_mode"]) 
    } else $returnMsg[1].=$dim."<a href=\"".$row["link"]."\">".$text."</a><br><code>".$fsize."</code>".$durationout."<br>"; 


	/* if ($channelInfoNew[$o_channelInfoKey]["redirectout"] != -1 && $current == -1 ) { 
	  $returnMsg[1].=$dim."".$text." | <code>".$row["msgid"]."</code><br><code>".$fsize."</code><br>";
	 } else */ // $returnMsg[1].=$dim."<a href=\"".$row['link']."\">".$text."</a><br><code>".$fsize."</code><br>";

    }
   } //switch 

  if (isset($orderClausel) && !array_key_exists('2', $returnMsg) && $order[1]=="res") {   
   for ($i=count($returnMsgRevert)-1;$i>=0; $i--) {
    $returnMsg[1].=$returnMsgRevert[$i];
   }
  }
 return $returnMsg;
} // function end
