<?php
/* Include Files ***************************/
require_once('../db-config.php');
	if(  defined('LTDVERSION')  )
		die('DEMO VERSION!|0');
require_once('../inc/lib-compat-class.php');
require_once('../inc/lib-db-class.php');
require_once('../inc/lib-login-class.php');
/*******************************************/
global $rSdb;

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

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

if(  $user->_readonly  )
	die(__('Restricted for READ ONLY users.','recipeshelf').'|0');


### magic quotes fix & clean up
foreach( $_POST as $k => $v )
	$_P[$k] = _rem_magic_quote($_POST[$k]);


### Recipe Parts
$p = $u = $y = '';
$cC = array();
$tC = array();
$aI = array();
$uI = array();
$pI = array();
$tI = array();
$sI = array();

$pos = 1;
foreach( $_P as $pItem => $pVal ){
    if( $pVal<>'' ){
        if( preg_match('/^rs-opt/',	$pItem) ) 	$p .= $pVal.'$%&';
        if( preg_match('/^url/',	$pItem) ) 	$u .= $pVal.'$%&';
    }
    if( preg_match('/^cook/',	 	$pItem) ) 	array_push($cC,$pVal);
    if( preg_match('/^date/',	 	$pItem) ) 	array_push($tC,$pVal);

    if( preg_match('/^rs-spacer/',	$pItem) )	array_push($sI,$pos);
    if( preg_match('/^rs-amount/',	$pItem) ){	array_push($aI,$pVal); $pos++; }
    if( preg_match('/^rs-unit/',  	$pItem) )	array_push($uI,$pVal);
    if( preg_match('/^rs-produc/',	$pItem) ) 	array_push($pI,$pVal);
    if( preg_match('/^rs-attrib/',	$pItem) )	array_push($tI,$pVal);

}

$p = substr($p,0, strlen($p)-3);
$u = substr($u,0, strlen($u)-3);
$f = substr($f,0, strlen($f)-3);

### Clean up tag array
$allT = explode(',', strtolower($_P['rs-tags']));
for($i=0; $i<count($allT); $i++)
    $allT[$i] = trim($allT[$i]);
$tags = implode(',',$allT);

### Collate Ingredients
$iAll = '';
$pos = 0;
for( $i=0; $i<count($aI); $i++ ){
	if( $sI[$pos]==($i+1) ){
        $iAll .=  'rs-spacer'.'$%&';
        $pos++;
    }
    if( strlen($aI[$i].$uI[$i].$pI[$i].$tI[$i])>0 )
        $iAll .=  $aI[$i].'$$$'.$uI[$i].'$$$'.$pI[$i].'$$$'.$tI[$i].'$%&';
}
$iAll = substr($iAll,0, strlen($iAll)-3);

### Collate Ingredients
$CFor = '';
for( $i=0; $i<count($cC); $i++ ){
    if( strlen($cC[$i].$tC[$i])>0 )
        $CFor .=  $cC[$i].'$$$'.$tC[$i].'$%&';
}
$CFor = substr($CFor,0, strlen($CFor)-3);

### Yield
$y = $_P['rs-yield'].'$$$'.$_P['rs-yield-unit'].'$$$'.$_P['rs-kcal'];

### Current Time
$cur_time = gmdate('Y-m-d H:i:s', current_time('timestamp'));

### Prep Time
$preptime = $_P['rs-ctime-a'].'$$$'.$_P['rs-ctime-p'].'$$$'.$_P['rs-ctime-o'];

### Clean
$r1 = false;

$recipeID = (int)$_P['rs-recipe-id'];

if( strlen($_P['rs-name']) > 0 ){

    if( isset($_POST['rs-recipe-id']) && $recipeID > 0 ){

        ### Update Record
        $sql =  "UPDATE {$rSdb->DBrecipes} SET
                    date_added = '".esc_sql($cur_time)."',
                    name = '".esc_sql($_P['rs-name'])."',
                    description = '".esc_sql($_P['rs-desc'])."',
                    tags = '".esc_sql($tags)."',
                    tips = '".esc_sql($_P['rs-equipment'])."',
                    steps = '".esc_sql($_P['step1'])."',
                    notes = '".esc_sql($_P['note1'])."',
                    ingredients = '".esc_sql($iAll)."',
                    yield = '".esc_sql($y)."',
                    cookingtime = '".esc_sql($preptime)."',
                    level = '".esc_sql($_P['rs-level'])."',
                    servewith = '".esc_sql($_P['rs-serve-with'])."',
                    options = '".esc_sql($p)."',
                    cooked = '".esc_sql($CFor)."',
                    urls = '".esc_sql($u)."' WHERE id='{$recipeID}'; ";
        $r1 = $rSdb->fetch( $sql );

        if ( $r1 )
            echo __('Recipe updated successfully.','recipeshelf').'|'.$recipeID;
        else
            echo __('ERROR! Recipe NOT updated.','recipeshelf').'|0';

    }else{

        ### Write Record to DB
        $sql =  "INSERT INTO {$rSdb->DBrecipes} (date_added,name,description,tags,tips,steps,notes,ingredients,yield,cookingtime,level,servewith,options,cooked,urls) ".
                "VALUES ('".$cur_time."',
					'".esc_sql($_P['rs-name'])."',
					'".esc_sql($_P['rs-desc'])."',
					'".esc_sql($tags)."',
					'".esc_sql($_P['rs-equipment'])."',
					'".esc_sql($_P['step1'])."',
					'".esc_sql($_P['note1'])."',
					'".esc_sql($iAll)."',
					'".esc_sql($y)."',
					'".esc_sql($preptime)."',
					'".esc_sql($_P['rs-level'])."',
					'".esc_sql($_P['rs-serve-with'])."',
					'".esc_sql($p)."',
					'".esc_sql($CFor)."',
					'".esc_sql($u)."');";
        $r1 = $rSdb->fetch( $sql );


        ### Get Shared ID
        $recipeID = $rSdb->fetchRow("SELECT LAST_INSERT_ID() AS number FROM {$rSdb->DBrecipes};");
        $recipeID = ($recipeID->number=='')?'1':$recipeID->number;

        if ( $r1 ){

            if( isset($_POST["rs-button-dupe"]) )
                echo __('New recipe added.','recipeshelf');
            else
                echo __('Recipe saved.','recipeshelf');
                
            echo __('You can now add an image or two.','recipeshelf') . '|'.$recipeID;

        }else
            echo __('ERROR! Recipe NOT saved.','recipeshelf').'|0';

    } ### new record
}

### All Ingredients, Unit, Attributes
if( count($aI) > 0 ){
    $sql = "INSERT IGNORE INTO {$rSdb->DBobjects} (type,object,uid) VALUES ";
    for( $i=0; $i<count($aI); $i++ ){
		if (trim($pI[$i])<>'') $sql .= "('1','".esc_sql($pI[$i])."','-'),";
		if (trim($tI[$i])<>'') $sql .= "('2','".esc_sql($tI[$i])."','-'),";
        if (trim($uI[$i])<>'') $sql .= "('3','".esc_sql($uI[$i])."','-'),";
	}
    $sql = rtrim($sql, ',') . ';';
    $r2 = $rSdb->fetch( $sql );
	###echo $r2." | SQL=".$sql;//debug
}
?>