<?php
session_start();
include("includes/site_config.php");
include('session_handler.inc');
include('error.php');
include('imagesizer.php');
include('message.php');
include_once("functions.php");
include(__INCLUDE_CLASS_PATH.'/class.StaticProfile.php');
include_once __INCLUDE_CLASS_PATH."/class.Picture.php";
include_once __INCLUDE_CLASS_PATH."/class.ItemManager.php";
$option_manager = new OptionManager();
?>
<script>
function popup(Site)
{
window.open(Site,'PopupName','toolbar=no,statusbar=no,location=no,scrollbars=yes,resizable=yes,width=275,height=200,left=350,top=300');
}
</script>


<?
if($_REQUEST['avatar']=="on")
{
$im_approve = "1";
}

$Sess_UserId = $_SESSION['Sess_UserId'];
$Sess_UserName = $_SESSION['Sess_UserName'];

 $mode=$_POST['mode'];
 $mode='update';
$client_ip = $_SERVER["REMOTE_ADDR"]." ".$_SERVER["HTTP_X_FORWARDED_FOR"];
$txtLocation=form_get('txtLocation');
$lstSeeking=form_get('lstSeeking');
if (!$GEOGRAPHY_JAVASCRIPT){
    $aCountry= split(";",form_get('WCountry'));
    $WCountry=$aCountry[0];
    $WState=$aCountry[1];
} else {
    $WCountry=form_get('WCountry');
    $WState=form_get('WState');
}
$pictureS=form_get('picture');
$targetfile=form_get('targetfile');
//if($targetfile==''){$targetfile=$picture;}



$WCity=form_get('WCity');
$WState=form_get('WState');
$lstSmoker=form_get('lstSmoker');
$lstDrink=form_get('lstDrink');
$lstBodyType=form_get('lstBodyType');
$lstChildren=form_get('lstChildren');
$lstMarital=form_get('lstMarital');
$lstReligion=form_get('lstReligion');
$lstEthnicity=form_get('lstEthnicity');
$lstEyecolor=form_get('lstEyecolor');
$lstHaircolor=form_get('lstHaircolor');
$lstEducation=form_get('lstEducation');
$lstHeight=form_get('lstHeight');
$lstEmployment=form_get('lstEmployment');
$lstIncome=form_get('lstIncome');
$txtTitle=form_get('txtTitle');
$txtComment=form_get('txtComment');
if ($CONST_ZIPCODES=='Y') {
        $WPostcode=form_get('WPostcode');
} else {
        $WPostcode="";
}
if (isset($_POST['chkSeekmen'])) $chkSeekmen=$_POST['chkSeekmen'];
if (isset($_POST['chkSeekwmn'])) $chkSeekwmn=$_POST['chkSeekwmn'];
if (isset($_POST['chkSeekcpl'])) $chkSeekcpl=$_POST['chkSeekcpl'];
$chkDelPhoto = $_POST['chkDelPhoto'];

# My match variables
$lstMySex=form_get('lstMySex');
$lstMySmoker=form_get('lstMySmoker');
$txtMyFromAge=form_get('txtMyFromAge');
$txtMyToAge=form_get('txtMyToAge');
$lstMyMinHeight=form_get('lstMyMinHeight');
$lstMyMaxHeight=form_get('lstMyMaxHeight');
$lstMySeeking=form_get('lstMySeeking');
$txtMyComment=form_get('txtMyComment');
$lstMyBodyType=form_get('lstMyBodyType');


# gives basic validation if the javascript fails to catch the error
/*if ($WCountry == "0") {
        $error_message=PRGADVERTISE_TEXT1;
        error_page($error_message,GENERAL_USER_ERROR);
}
if (trim($WCountry) == "") {
        $error_message=PRGADVERTISE_TEXT1;
        error_page($error_message,GENERAL_USER_ERROR);
}
*/
if ($CONST_ZIPCODES=='Y') {
        if (trim($WPostcode) != "") {
                // Check for valid areacode
                $sql = "SELECT zip_latitude,zip_longitude FROM zipcodes WHERE zip_zipcode = '$WPostcode' LIMIT 1";
                //echo $sql;
                $result=mysql_query($sql,$link);
                if (mysql_num_rows($result) < 1) {
                        $error_message=PRGADVERTISE_TEXT4;
                        error_page($error_message,GENERAL_USER_ERROR);
                }
        }
}
if ($lstSeeking == "- Choose -") {
        $error_message=PRGADVERTISE_TEXT5;
        error_page($error_message,GENERAL_USER_ERROR);
}

/*if (!$GEOGRAPHY_JAVASCRIPT && (strlen($txtLocation) < 2 || strlen($txtLocation) > 30)) {
        $error_message=PRGADVERTISE_TEXT2;
        error_page($error_message,GENERAL_USER_ERROR);
}*/

if ($lstBodyType == "- Choose -") {
        $error_message=PRGADVERTISE_TEXT6;
        error_page($error_message,GENERAL_USER_ERROR);
}
if ($lstHeight == "- Choose -") {
        $error_message=PRGADVERTISE_TEXT7;
        error_page($error_message,GENERAL_USER_ERROR);
}
if ($lstChildren == "- Choose -") {
        $error_message=PRGADVERTISE_TEXT8;
        error_page($error_message,GENERAL_USER_ERROR);
}
if ($lstSmoker == "- Choose -") {
        $error_message=PRGADVERTISE_TEXT9;
        error_page($error_message,GENERAL_USER_ERROR);
}
if ($lstDrink == "- Choose -") {
    $error_message=PRGADVERTISE_TEXT10;
    error_page($error_message,GENERAL_USER_ERROR);
}
if ($lstReligion == "- Choose -") {
        $error_message=PRGADVERTISE_TEXT11;
        error_page($error_message,GENERAL_USER_ERROR);
}
if ($lstMarital == "- Choose -") {
        $error_message=PRGADVERTISE_TEXT12;
        error_page($error_message,GENERAL_USER_ERROR);
}
if ($lstEthnicity == "- Choose -") {
        $error_message=PRGADVERTISE_TEXT13;
        error_page($error_message,GENERAL_USER_ERROR);
}
if ($lstEyecolor == "- Choose -") {
    $error_message=PRGADVERTISE_TEXT31;
    error_page($error_message,GENERAL_USER_ERROR);
}
if ($lstHaircolor == "- Choose -") {
    $error_message=PRGADVERTISE_TEXT32;
    error_page($error_message,GENERAL_USER_ERROR);
}
if ($lstEducation == "- Choose -") {
        $error_message=PRGADVERTISE_TEXT14;
        error_page($error_message,GENERAL_USER_ERROR);
}
if ($lstEmployment == "- Choose -") {
        $error_message=PRGADVERTISE_TEXT15;
        error_page($error_message,GENERAL_USER_ERROR);
}
if ($lstIncome == "- Choose -") {
        $error_message=PRGADVERTISE_TEXT16;
        error_page($error_message,GENERAL_USER_ERROR);
}
if ((! isset($chkSeekmen)) && (! isset($chkSeekwmn)) && (! isset($chkSeekcpl))) {
        $error_message=PRGADVERTISE_TEXT17;
        error_page($error_message,GENERAL_USER_ERROR);
}
if (strlen($txtTitle) < 5 || strlen($txtTitle) > 30) {
        $error_message=PRGADVERTISE_TEXT18;
        error_page($error_message,GENERAL_USER_ERROR);
}
if (strlen($txtComment) < 120) {
        $error_message=PRGADVERTISE_TEXT19;
        error_page($error_message,GENERAL_USER_ERROR);
}
if (strlen($txtComment) > 4000) {
        $error_message=PRGADVERTISE_TEXT20;
        error_page($error_message,GENERAL_USER_ERROR);
}

$query_adv="SELECT adv_createdate FROM adverts WHERE adv_userid = '$Sess_UserId'";
if (! $result_adv=mysql_query($query_adv,$link)) {
        error_page(mysql_error(),GENERAL_SYSTEM_ERROR);
}
$sql_adv=mysql_fetch_object($result_adv);
 $tempDate=$sql_adv->adv_createdate;


//$max_size=$option_manager->GetValue('maxpicsize');

# checks to see if a member exists and extracts certain info for use in the advert
//$tempDate=date("Y-m-d H:i:s"); // this is used as the create/update date of the advert
$query="SELECT mem_userid, mem_dob, mem_username, mem_sex, mem_expiredate FROM members WHERE mem_userid = '$Sess_UserId'";
if (! $result=mysql_query($query,$link)) {
        error_page(mysql_error(),GENERAL_SYSTEM_ERROR);
}
if (mysql_num_rows($result) < 1) {
        error_page(PRGADVERTISE_TEXT21,GENERAL_SYSTEM_ERROR);
} else {
        # extract member information from members table
        $sql_array=mysql_fetch_object($result);
        $tempdob=$sql_array->mem_dob;
        $tempusername=$sql_array->mem_username;
        $tempsex=$sql_array->mem_sex;
        $tempid=$sql_array->mem_userid;
        $tempexpire=$sql_array->mem_expiredate;
        
		$tempseekmen='N'; 
		$tempseekwmn='N'; 
		$tempseekcpl='N';
        if ($chkSeekmen!='') {$tempseekmen='Y';}
        if ($chkSeekwmn!='') {$tempseekwmn='Y';}
        if (isset($chkSeekcpl)) {$tempseekcpl='Y';}
}

/*
# check to see if picture should be uploaded
if ($_FILES['fupload']['size'] != 0) {
        if ($_FILES['fupload']['size'] > $max_size) {
                $max_size=$max_size/1000;
                error_page(sprintf(PRGADVERTISE_TEXT22,$max_size),GENERAL_USER_ERROR);
        }
        # Picture exists
        if ($_FILES['fupload']['type'] == "image/pjpeg" ||$_FILES['fupload']['type'] == "image/jpeg") {
                if ($_FILES['fupload']['type'] == "image/pjpeg" ) { $extension=".jpg"; }
                if ($_FILES['fupload']['type'] == "image/jpeg" ) { $extension=".jpg"; }
                $filename="$tempusername"."$extension";
                $targetfile="members/"."$filename";
                copy($_FILES['fupload']['tmp_name'],"$targetfile");
                if ($CONST_THUMBS == 'Y') {
                        $thumbfile=str_replace("members/", "thumbs/", $targetfile);
                        $new_w=60;
                        $new_h=66;
                        createthumb($targetfile, $thumbfile,$new_w,$new_h);
                        $thumbfile=str_replace("members/", "thumbs/large-", $targetfile);
                        $new_w=120;
                        $new_h=160;
                        createthumb($targetfile, $thumbfile,$new_w,$new_h);
                }
                $targetfile="/members/"."$filename";
        } else {
                error_page(PRGADVERTISE_TEXT23.$_FILES['fupload']['type'],GENERAL_USER_ERROR);
        }
} elseif(($_POST['avatar'])&&($CONST_AVATARS_GALLERY == "Y")) {
                    $avatar_id = $_POST['avatar'];
                    $res_avatar = mysql_query($query_avat = "SELECT * FROM avatars AS a
                                                                INNER JOIN pictures AS p
                                                                    ON (a.pic_id = p.pic_id)
                                                                WHERE
                                                                    a.avatar_id = $avatar_id
                                                                ");
                    $oAvatar = mysql_fetch_object($res_avatar);
                    $targetfile = $oAvatar->pic_picture;
//                    echo '<pre>';
//                    print_r($targetfile);
//                    exit;
} else {
        	if ($mode=='create') {
				if ($tempsex=='M') {$targetfile='/images/genericm.gif';}
				if ($tempsex=='F') {$targetfile='/images/genericf.gif';}
				if ($tempsex=='C') {$targetfile='/images/genericc.gif';}
			} else {
			    # no picture exists
                $query="SELECT adv_picture FROM adverts WHERE adv_userid = '$Sess_UserId'";
                if (! $result=mysql_query($query,$link)) {error_page(mysql_error(),GENERAL_SYSTEM_ERROR);}
                $sql_array=mysql_fetch_object($result);
                $targetfile=$sql_array->adv_picture;
			}
}
if ($chkDelPhoto) {
    if ($tempsex=='M') {$targetfile='/images/genericm.gif';}
    if ($tempsex=='F') {$targetfile='/images/genericf.gif';}
    if ($tempsex=='C') {$targetfile='/images/genericc.gif';}
}
*/

if($targetfile !='') {
                

 $picture = new Picture();

    $data = array(

        "pic_userid"    => $_SESSION['Sess_UserId'],

        "pic_private"   => 'N',

        "pic_default"   => 'Y',

       "filepath"      => $targetfile,

                );

    $result = $picture->InitForSave($data);

    if ($result === null) {

     // error_page(join("<br>",$picture->error),GENERAL_USER_ERROR);

    }

    $picture->Save();


    
 
                # if it doesn't exist then put in the generic picture

                } elseif($_REQUEST['avatar']) {

                    $avatar_id = $_REQUEST['avatar'];

                    $res_avatar = mysql_query($query_avat = "SELECT * FROM avatars AS a

                                                                INNER JOIN pictures AS p

                                                                    ON (a.pic_id = p.pic_id)

                                                                WHERE

                                                                    a.avatar_id = $avatar_id

                                                                ");

                    $oAvatar = mysql_fetch_object($res_avatar);

                    $targetfile = $oAvatar->pic_picture;

//                    echo '<pre>';

//                    print_r($targetfile);

//                    exit;

                } else {
				
						if($pictureS==''){

                                if ($WGender=='M') {$pictureS='templates/default/images/genericm.gif';}

                                if ($WGender=='F') {$pictureS='templates/default/images/genericf.gif';}

                                if ($WGender=='C') {$pictureS='templates/default/images/genericc.gif';}
							}
                }



# check whether immediate authorisation
$approved=$option_manager->GetValue('authorisead');
$txtComment=mysql_escape_string($txtComment);
$txtTitle=mysql_escape_string($txtTitle);
$expiredate=mktime (0,0,0,date("m") ,date("d")-1,date("Y"));
$expiredate=date('Y-m-d',$expiredate);
if ($tempexpire > $expiredate) {
        $expiredate=$tempexpire;
}

$sel=mysql_query("SELECT adv_userid from adverts where adv_userid='$Sess_UserId'");
$count=mysql_num_rows($sel);

if ($mode=='update' && $count > 0) {
		$query="UPDATE adverts SET
				adv_zipcode='$WPostcode',
				adv_title = '$txtTitle',
				
				adv_comment = '$txtComment',
				adv_countryid = '$WCountry',
				adv_stateid = '$WState',
                adv_cityid = '$WCity',
                adv_location = '$txtLocation',
				
				adv_approved = '$approved',
				adv_createdate = '$tempDate',
				
				adv_picture = '$pictureS',
				adv_expiredate = '$expiredate',
				adv_ip = '$client_ip',
				adv_seekmen = '$tempseekmen',
				adv_seekwmn = '$tempseekwmn',
				adv_seekcpl = '$tempseekcpl'
				
				WHERE adv_userid = '$Sess_UserId'";
				
				 mysql_query($query) or die(mysql_error()); 
				$arrOptions=$_REQUEST['drop_value'];
				$arrQuestions=$_REQUEST['Question_value'];

				if($arrOptions!="")
				{
				for($intCounter=0;$intCounter<=count($arrOptions)-1;$intCounter++)
						{
							$Options=$arrOptions[$intCounter];
							$Questions=$arrQuestions[$intCounter];
							//echo $Questions;
							$lowelcase = strtolower($Questions);
							$newphrase9 = str_replace(" ","", $lowelcase);
							$tablefield = "adv_$newphrase9";
							$strQuery = "UPDATE adverts_dropdown SET ";
							$strQuery .= $tablefield . " = ";
							$strQuery .= "'" . addslashes($Options) . "',";
							//echo $tablefield;
							//echo $Options;
							if (trim(strlen($strQuery)) > 0)
							$strQuery = substr($strQuery,0,strlen($strQuery)-1);
					
							$strQuery .= " WHERE adv_userid = $Sess_UserId";
					
							//echo $strQuery ;
							mysql_query($strQuery) or die(mysql_error());
						}
				}
				
					/*$strQuery = "UPDATE adverts_dropdown SET ";
					// get field names
					$res=mysql_query("SELECT * FROM adverts_dropdown");
					$fields = mysql_num_fields($res);
					$count=count($_REQUEST['dropoptions']); 
					for ($j = 0; $j < $fields; $j++) 
					{
						if ($j == ($fields -1))
							break;
					
						$fname=mysql_field_name($res, $j+1);
						$strQuery .= $fname . " = ";
						$strQuery .= "'" . $arrOptions[$j] . "',";
						
					}
					//remove comma at the end
					if (trim(strlen($strQuery)) > 0)
					$strQuery = substr($strQuery,0,strlen($strQuery)-1);
					
					$strQuery .= " WHERE adv_userid = $Sess_UserId";
					
					//echo $strQuery ;
					mysql_query($strQuery) or die(mysql_error()); */
				 	/*$arrOptions1=$_REQUEST['drop_value'];
					$arrOptions2 = array_fill(0, 1, "$Sess_UserId");	  
					
					$arrOptions=array_merge($arrOptions2,$arrOptions1);
					//print_r($arrOptions); 
							$strQuery = "UPDATE adverts_dropdown set ";
							
							// get field names
							$res=mysql_query("SELECT * FROM adverts_dropdown");
							$fields = mysql_num_fields($res); 
							for ($j = 1; $j < $fields; $j++) 
							{
								$fname=mysql_field_name($res, $j);
								$strQuery .= $fname . "=" ."'" . $arrOptions[$j] . "',";
							}
							
							//remove comma at the end
							//if (trim(strlen($strQuery)) > 0)
//								$strQuery = substr($strQuery,0,strlen($strQuery)-1);
//							
							
//							 
//							 $count=count($_REQUEST['drop_value']);
//							for($intcounter=0; $intcounter<=$count-1; $intcounter++){
//								$strQuery .= "'" . $arrOptions[$intcounter] . "',";
//							}
							
							//remove comma at the end
							if (trim(strlen($strQuery)) > 0)
								$strQuery = substr($strQuery,0,strlen($strQuery)-1);
								
							//$strQuery .= ")"; 
							$strQuery .="where adv_userid= '$Sess_UserId'"; 
							//echo $strQuery;
							//die;
							 mysql_query($strQuery) or die(mysql_error()); */
				
				
 //die;
	if (!mysql_query($strQuery,$link)) {error_page(mysql_error(),GENERAL_SYSTEM_ERROR);}

	$txtMyComment=mysql_escape_string($txtMyComment);
	$query="REPLACE mymatch SET 
				
				mym_comment='$txtMyComment',
				
				mym_userid=$Sess_UserId";
//
	mysql_query($query,$link) or die(mysql_error());
} else {
							$arrOptions=$_REQUEST['drop_value'];
						   	$strQuery = "INSERT INTO adverts_dropdown (";
							// get field names
							$res=mysql_query("SELECT * FROM adverts_dropdown");
							$fields = mysql_num_fields($res); 
							for ($j = 0; $j < $fields; $j++) 
							{
								$fname=mysql_field_name($res, $j);
								$strQuery .= $fname . ",";
							}
							//remove comma at the end
							if (trim(strlen($strQuery)) > 0)
								$strQuery = substr($strQuery,0,strlen($strQuery)-1);
							
							$strQuery .= ") VALUES ('$Sess_UserId',"; 
							 
							 $count=count($_REQUEST['drop_value']);
							for($intcounter=0; $intcounter<=$count-1; $intcounter++){
								$strQuery .= "'" . addslashes($arrOptions[$intcounter]) . "',";
							}
							//remove comma at the end
							if (trim(strlen($strQuery)) > 0)
								$strQuery = substr($strQuery,0,strlen($strQuery)-1);
								
							$strQuery .= ")"; 
							
							
							 mysql_query($strQuery) or die(mysql_error()); 
							 
	$query="INSERT INTO adverts
			(adv_zipcode, adv_userid, adv_username, adv_smoker, adv_drink, adv_children, adv_dob, adv_comment,  adv_countryid, adv_stateid, adv_cityid, adv_location, adv_height, adv_marital, adv_bodytype, adv_ethnicity, adv_religion, adv_sex, adv_seeking, adv_picture, adv_createdate, adv_seekmen, adv_seekwmn,adv_seekcpl, adv_approved, adv_title, adv_profession,adv_income,adv_education, adv_expiredate, adv_views, adv_eyecolor, adv_haircolor, adv_ip)
			VALUES
			('$WPostcode', '$tempid','$tempusername','$lstSmoker','$lstDrink','$lstChildren','$tempdob','$txtComment', '$WCountry','$WState','$WCity', '$txtLocation','$lstHeight', '$lstMarital','$lstBodyType','$lstEthnicity','$lstReligion','$tempsex','$lstSeeking', '$pictureS', '$tempDate', '$tempseekmen', '$tempseekwmn','$tempseekcpl', '$approved', '$txtTitle' ,'$lstEmployment','$lstIncome','$lstEducation','$expiredate',0,'$lstEyecolor','$lstHaircolor','$client_ip')";
			
			

	if (!mysql_query($query,$link)) 
	{
			if (mysql_errno($link) == 1062) {
					$query="UPDATE adverts  SET
					adv_zipcode='$WPostcode',
					adv_title = '$txtTitle',
					adv_smoker = '$lstSmoker',
					adv_drink = '$lstDrink',
					adv_children = '$lstChildren',
					adv_comment = '$txtComment',
					adv_countryid = '$WCountry',
					adv_stateid = '$WState',
					adv_cityid = '$WCity',
                    adv_location = '$txtLocation',
					adv_height = '$lstHeight',
					adv_marital = '$lstMarital',
					adv_bodytype = '$lstBodyType',
					adv_approved = '$approved',
					adv_createdate = '$tempDate',
					adv_ethnicity = '$lstEthnicity',
					adv_religion = '$lstReligion',
					adv_education = '$lstEducation',
					adv_Income = '$lstIncome',
					adv_profession= '$lstEmployment',
					adv_seeking = '$lstSeeking',
					adv_picture = '$pictureS',
					adv_expiredate = '$expiredate',
					adv_seekmen = '$tempseekmen',
					adv_ip = '$client_ip',
					adv_seekwmn = '$tempseekwmn',
				adv_seekcpl = '$tempseekcpl',
					adv_eyecolor = '$lstEyecolor',
					adv_haircolor = '$lstHaircolor'
					WHERE adv_userid = '$Sess_UserId'";
					if (!mysql_query($query,$link)) {error_page(mysql_error(),GENERAL_SYSTEM_ERROR);}

			}else{
					error_page(mysql_error(),GENERAL_SYSTEM_ERROR);
			}
	}

	$txtMyComment=mysql_escape_string($txtMyComment);

	 $query="REPLACE INTO mymatch (mym_userid, mym_comment)
					VALUES ($Sess_UserId, '$txtMyComment')";
	mysql_query($query,$link) or die(mysql_error());
}

	//include("generate_profile.php");
?>

<script language="javascript">

window.location='<?="my_account.php?status=yes&PHPSESSID=".session_id()?>';
   // header("Location: prgpicadmin.php");

   // exit;
</script>
