<?php
/* Include Files *********************/
require_once('require.php');
/*************************************/

global $rSdb;

$user	= new userManagement();
$iphone	= new renderLayout('default-iphone-layout.css');

if(  !$user->_logged_in  )
	die(__('Access denied.','recipeshelf'));

if( ! check_ajax_referer('search', false) )
	die(__('Security Alert: Direct access not permitted!','recipeshelf'));

function mergeArr($a,$b,$u=''){
    foreach($b as $ik=>$iv){
        if( $u!='' )
            $a['-'.$u.'-'.$iv] = $ik;
        else
            $a[$iv] = $ik;
    }
    return $a;
}

$storedoptions	= $rSdb->get_option("recipeShelf_options");

$arrFlip		= array_flip( $storedoptions["rS_season"] );
$arrFlip		= mergeArr( $arrFlip, $storedoptions["rS_course"] );
$arrFlip		= mergeArr( $arrFlip, $storedoptions["rS_cuisine"] );
$arrFlip		= mergeArr( $arrFlip, $storedoptions["rS_type"] );
$arrFlip		= mergeArr( $arrFlip, $storedoptions["rS_additional"] );
$arrFlip		= mergeArr( $arrFlip, $storedoptions["rS_diet"] );

if( is_array($storedoptions["rS_custom"]) && count($storedoptions["rS_custom"])>0 )
    foreach( array_keys($storedoptions["rS_custom"]) as $u ){
        $arrFlip  = mergeArr( $arrFlip, $storedoptions["rS_custom"][$u],$u );
        }
		
$s = _rem_magic_quote($_POST['search-text']);

if(  $_POST['action']=='tag'  ){

    $sql		= "SELECT id,name,tags,description,options FROM {$rSdb->DBrecipes} WHERE tags LIKE '%".esc_sql($s)."%'";
	$recipes 	= $rSdb->fetchArr( $sql );

}else if(  $_POST['action']=='id'  ){

    $sql		= "SELECT id,name,tags,description,options FROM {$rSdb->DBrecipes} WHERE id='".esc_sql((int)$s)."'";
	$recipes 	= $rSdb->fetchArr( $sql );

}else if(  $_POST['action']=='star'  ){

/*	$offset_result	= mysql_query("SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM {$rSdb->DBrecipes}");
	$offset_row 	= mysql_fetch_object( $offset_result );
	$offset			= $offset_row->offset;
	$sql			= "SELECT id,name,tags,description,options FROM {$rSdb->DBrecipes} LIMIT $offset, 1";
*/

	### Grab Options
	$useroptions	= $rSdb->get_option( $user->_user_name."_options" );
	$favesArr 		= $useroptions['rS_favorites'];

	$faves = '';
	if( is_array($favesArr) && count($favesArr)>0 ){
		foreach( $favesArr as $f )
		    $faves .= "'".$f."',";
		$faves	= rtrim($faves,',');
	} else
		$faves	= '0';

	$sql		= "SELECT id,name,tags,description,options FROM {$rSdb->DBrecipes} WHERE id IN ({$faves})";
	$recipes 	= $rSdb->fetchArr($sql);

}else{

	if( strpos('*', $s)===false )
        $s = '*'.$s.'*';

	if( $s=='*' )
	    $m = "1 ";
	else
	    $m = "MATCH(name,description,tags,ingredients) AGAINST('".esc_sql($s)."' IN BOOLEAN MODE) ";

	$o 			= '';  // e.g. LIMITs..
	$sql		= "SELECT * FROM {$rSdb->DBrecipes} WHERE ".$m.$o;
    $recipes	= $rSdb->fetchArr($sql);

}



$photos	= array();
$resArr = array();

if( !is_array($recipes) || count($recipes)==0 ){

	$resArr[0]->result = 0;
	$resArr[0]->err = __('No recipes found!','recipeshelf');
	die (json_encode($resArr));

} else {

	### Grab Favorites
	$useroptions	= $rSdb->get_option( $user->_user_name."_options" );
	$favesArr 		= $useroptions['rS_favorites'];

	$resArr[0]->result = 1;

	$j=0;
	foreach( $recipes as $r ){

        $t = (strlen($r->name)<80) ? $r->name : substr($r->name,0,79).'...';
        $d = (strlen($r->description)<251) ? $r->description : substr($r->description,0,250).'...';

		$resArr[$j]->id = (int)$r->id;

		$arrIMGs = glob(  dirname(__FILE__).'/../../photos/'.$r->id.'_*.*'  );

       	$i		= 0;
       	$photos = array();
        if ( is_array($arrIMGs) && count($arrIMGs) > 0 ){
	        foreach( $arrIMGs as $img ){
				$photos[$i++]->src = basename($img);
	        }
        }else
			$photos[$i]->src = -1;

		$resArr[$j]->img = $photos;


		$cats = '';
        $arrCats = explode('$%&',$r->options);
		if( strlen($r->options)>3 ){
			foreach($arrCats as $c)
            	$cats .= __( $arrFlip[$c] ,'recipeshelf').', ';
		}

	$resArr[$j]->name = esc_html($t);
	$resArr[$j]->desc = esc_html($d); 

	if( $_POST['sync']==1 ){
		$resArr[$j]->catIDs	= esc_html( $r->options );
		$resArr[$j]->tags 	= esc_html( $r->tags );
		$resArr[$j]->ctime 	= esc_html( $r->cookingtime );
		$resArr[$j]->yield 	= esc_html( $r->yield );
		$resArr[$j]->ing 	= esc_html( _rem_script($r->ingredients) );
		$resArr[$j]->steps 	= esc_html( _rem_script($r->steps) );
		$resArr[$j]->notes 	= esc_html( _rem_script($r->notes) );
		$resArr[$j]->cfor 	= esc_html( $r->cooked );
		$resArr[$j]->urls 	= esc_html( $r->urls );
		$resArr[$j]->fave 	= in_array($r->id,$favesArr) ? 1:0;
 	}else
		$resArr[$j]->cats 	= substr($cats, 0, -2);

	$j++;

	}
	
	echo json_encode($resArr);
}
?>