<?php
/*
* date last modified 28-11-2017
* Edited by PI-Digi Logical Solutions
* HTML Files - add_user.html.php
* Mysql Tables - tbl_designation, tbl_purchase_partner
*/
include_once('PHPMailer/class.phpmailer.php');
include('includes/imgFunctions.php');
include('includes/functions.php'); # general functions

function sendGCM($title, $body, $token, $show_in) {

    $url = 'https://fcm.googleapis.com/fcm/send';
	
	$dat = array('show_in' => $show_in);

    $fields = array('registration_ids' => array($token),
					'notification'=>array("body"=>$body, "title"=>$title, "data"=>$dat)
    );
    $fields = json_encode ( $fields );

    $headers = array (
            'Authorization: key=' . FCM_TECH_KEY,
            'Content-Type: application/json'
    );

    $ch = curl_init ();
    curl_setopt ( $ch, CURLOPT_URL, $url );
    curl_setopt ( $ch, CURLOPT_POST, true );
    curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );

    $result = curl_exec ( $ch );
	
    curl_close ( $ch );
}

function sendIosTechPush($title, $body, $token, $show_in) {
	
	// Put your device token here (without spaces):
	$deviceToken = str_replace(" ", "", $token);
	// Put your private key's passphrase here:
	$passphrase = 'swaroop';
	//// Put your alert message here:
	$message = $title." - ".$body;

	$ctx = stream_context_create();
	stream_context_set_option($ctx, 'ssl', 'local_cert', 'CKPdtnTech.pem');
	stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

	
		//gateway.sandbox.push.apple.com:2195
	if($fp = stream_socket_client('ssl://gateway.push.apple.com:2195',
							   $err, $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx)){
		// Create the payload body
		$push_body['aps'] = array('badge' => +1, 'alert' => $message, 'sound' => 'default');
		$payload = json_encode($push_body);
	
		// Build the binary notification
		$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
		// Send it to the server
		$result = fwrite($fp, $msg, strlen($msg));
		if (!$result) {
	    	//echo 'Message not delivered' . PHP_EOL;
		} else {
	    	//echo 'Message successfully delivered amar'.$message. PHP_EOL;
		}
		// Close the connection to the server
		fclose($fp);
	}	

	
}

$isEdit = FALSE;

//get cities
$citiesRs = mysqli_query($con, "SELECT id, name FROM tbl_city ORDER BY name");


if(isset($_REQUEST['id']) && $_REQUEST['id']!=''){
	
	$isEdit = TRUE;
	$editId = mysqli_real_escape_string($con, trim($_REQUEST['id']));
	
	//delete image
	if(isset($_REQUEST['action']) && $_REQUEST['action']='del_image'){
		$recImg = mysqli_fetch_array(mysqli_query($con, "SELECT image FROM tbl_purchase_partner WHERE id = '".$editId."'"));
		if(($recImg['image']!='') && file_exists(STAFF_IMG_FOLDER.$recImg['image'])){
			unlink(STAFF_IMG_FOLDER.$recImg['image']);
			unlink(STAFF_IMG_FOLDER.'thumb/'.$recImg['image']);
		}
		$update = mysqli_query($con, "UPDATE tbl_purchase_partner SET image = '' WHERE id = '".$editId."'");
		$success = 'Shop image has been deleted';
	}	
	
	$editRs = mysqli_query($con, "SELECT * FROM tbl_purchase_partner WHERE id = '".$editId."'");
	if(mysqli_num_rows($editRs)>0){
		$resEdit = mysqli_fetch_array($editRs);
	} else {
		$error = 'Shop does not exist!';
	}

} 

if(isset($_POST['add'])) {
	
	
	/*if(isset($_FILES['photo']) && $_FILES['photo']['size'] > 0) {		
		if($_FILES['photo']['type'] == 'image/gif' || $_FILES['photo']['type'] == 'image/jpeg' || 
		   $_FILES['photo']['type'] == 'image/png' || $_FILES['photo']['type'] == 'image/pjpeg') {
			$photo_name = $_FILES['photo']['name'];			
			$photo_temp_name = $_FILES['photo']['tmp_name'];
			$photo_extension = pathinfo($photo_name, PATHINFO_EXTENSION);
		} else {
			$photo_name = FALSE;
			$photo_temp_name = FALSE;
			$error = "Invalid Image type. Only gif, jpg and png allowed";
		}
	}*/
	
	if(strlen(trim($_POST['re_password'])) > 0) {
		$re_password = trim($_POST['re_password']);
		if(strlen(trim($_POST['password'])) > 0) {
			$password = trim($_POST['password']);
			if($password == $re_password){
				//ok
			} else {
				$error = 'Password mis-match error!';
			}
		}
	} else {
		$error = 'Please re-enter Password';
	}

	if(strlen(trim($_POST['password'])) > 0) {
		$password = trim($_POST['password']);
		if(strlen($password)>5){
			//ok
		} else {
			$error = 'Password should contain atleast 6 characters';
		}
	} else {
		$error = 'Please enter Password';
	}

	if(strlen(trim($_POST['discount'])) > 0) {
		$discount = trim($_POST['discount']);
		if(is_numeric($discount)){
			if($discount>=0 && $discount<=100){
				//ok
			} else {
				$error = 'Please enter a valid discount';
			}
		} else {
			$error = 'Please enter a numeric value for discount';
		}
	} else {
		$discount = 0;
	}
	
	if(strlen(trim($_POST['commission_user'])) > 0) {
		$commission_user = trim($_POST['commission_user']);
		if(is_numeric($commission_user)){
			//ok
		} else {
			$error = 'Please enter a numeric value for user commission';
		}
	} else {
		$commission_user = 0;
	}
	
	if(strlen(trim($_POST['commission'])) > 0) {
		$commission = trim($_POST['commission']);
		if(is_numeric($commission)){
			//ok
		} else {
			$error = 'Please enter a numeric value for commission';
		}
	} else {
		$commission = 0;
	}
	
	if(strlen(trim($_POST['city'])) > 0) {
		$city = trim($_POST['city']);
	} else {
		$city = '';
	}
	
	
	if(strlen(trim($_POST['longitude'])) > 0) {
		$longitude = trim($_POST['longitude']);		
	} else {
		$longitude = '';
		/*if(strlen(trim($_POST['place'])) > 0) {
			$error = 'Sorry Unable to fetch lat-long from the location. Enter location and click on map to fetch Lat-Long';
		} else {
			$error = 'Please enter location to fetch lat-long';
		}*/		
	}
	
	if(strlen(trim($_POST['latitude'])) > 0) {
		$latitude = trim($_POST['latitude']);		
	} else {
		$latitude = '';
		/*if(strlen(trim($_POST['place'])) > 0) {
			$error = 'Sorry Unable to fetch lat-long from the location. Enter location and click on map to fetch Lat-Long';
		} else {
			$error = 'Please enter location to fetch lat-long';
		}*/		
	}
	
	if(strlen(trim($_POST['place'])) > 0) {
		$place = trim($_POST['place']);		
		$placeArr = explode(',', $place);
		$place = $placeArr[0];
	} else {
		$error = 'Please enter location';
	}
	
	if(strlen(trim($_POST['address'])) > 0) {
		$address = trim($_POST['address']);
	} else {
		$address = '';
	}
	
	if(strlen(trim($_POST['building_name'])) > 0) {
		$building_name = trim($_POST['building_name']);
	} else {
		$error = 'Please enter Shop Name';
	}
	
	if(strlen(trim($_POST['mobile'])) > 0) {
		$mobile = trim($_POST['mobile']);
		if(is_numeric($mobile) && strlen($mobile)==10){
			// check 
			$checkPhone = mysqli_query($con,"SELECT id FROM tbl_purchase_partner WHERE mobile='".mysqli_real_escape_string($con,$mobile)."' AND status != 'Deleted'");
			if(isset($checkPhone) && mysqli_num_rows($checkPhone)>0) {
				$error = 'A partner with the same mobile number exists';
			}
		} else {
			$error = 'Invalid mobile number';
		}
	} else {
		$mobile = '';
	}
			
	if(strlen(trim($_POST['phone'])) > 0) {
		$phone = trim($_POST['phone']);
		if(is_numeric($phone) && (strlen($phone)>8) && (strlen($phone)<13)){
			//ok
		} else {
			$error = 'Please enter phone number only digits with coutry code';
		}
	} else {
		//$error = 'Please enter Phone Number';
		$phone = '';
	}	

	
	
	if(isset($_POST['email']) && strlen(trim($_POST['email'])) > 0) {
		$email = trim($_POST['email']);
		if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
			$error =  "E-mail is not valid";
		} else {
			// check Email
			$checkEmail = mysqli_query($con,"SELECT id FROM tbl_purchase_partner WHERE email='".mysqli_real_escape_string($con,$email)."' AND status != 'Deleted'");
			if(isset($checkEmail) && mysqli_num_rows($checkEmail)>0) {
				$error = 'Email Already Taken';
			}
		}
	} else {
		$error = 'Please enter Email';
	}
	
	if(isset($_POST['name']) && strlen($_POST['name'])>0) {
		$name = trim($_POST['name']);
	} else {
		$error = 'Please Enter Shop Name';
	}	
	
	
	
	if(empty($error)) {
		
		/*$googleAddr = array();
		$latitude = $longitude = '';
		
		//get lat long of the city		
		if($place!=''){
			$googleAddr[] = trim($_POST['place']);
		}	
		
		$formattedAddress = implode(',',$googleAddr);*/
		$mapPlace = $_POST['place'];		
		$latLong = getLatLong($mapPlace);
		//print_r($latLong);
		//exit;
		if($latitude!='' && $longitude!=''){
			//take the values
		} else if(is_array($latLong) && $latLong['latitude']!='' && $latLong['longitude']!=''){
			//ok
			$latitude = $latLong['latitude'];
			$longitude = $latLong['longitude'];
		} else {
			$error = 'Unable to find lat-long from the location - '.$mapPlace.'. Try again';
		}
		
		if(empty($error)) {						
			/* Adding New User Details */		
			$insertQry = "INSERT INTO tbl_purchase_partner(name, email, password, phone, mobile, building_name, address, place, city, latitude, longitude, commission, commission_user, discount, date, added_by, status) VALUES (
			'".mysqli_real_escape_string($con, $name)."',
			 '".mysqli_real_escape_string($con, $email)."',
			 '".mysqli_real_escape_string($con, $password)."',
			 '".mysqli_real_escape_string($con, $phone)."',
			 '".mysqli_real_escape_string($con, $mobile)."',	
			 '".mysqli_real_escape_string($con, $building_name)."',
			 '".mysqli_real_escape_string($con, $address)."',
			 '".mysqli_real_escape_string($con, $place)."',			 
			 '".mysqli_real_escape_string($con, $city)."',
			 '".mysqli_real_escape_string($con, $latitude)."',
			 '".mysqli_real_escape_string($con, $longitude)."',
			 '".mysqli_real_escape_string($con, $commission)."',
			 '".mysqli_real_escape_string($con, $commission_user)."',
			 '".mysqli_real_escape_string($con, $discount)."',					 
			 NOW(),
			 '".mysqli_real_escape_string($con, $_SESSION['adminId'])."',
			 'Active')";
			
			$execInsert = mysqli_query($con,$insertQry);
			$insert_id = mysqli_insert_id($con);		
			
			if($execInsert) {
				
				/*if(isset($_FILES['photo']) && $_FILES['photo']['size'] > 0) {
					$photo_dir = SHOP_IMG_FOLDER;
					$photo_name = $insert_id.'_'.time().'.'.$photo_extension; 
					if(move_uploaded_file($photo_temp_name, $photo_dir.$photo_name)){
						resize2(SHOP_IMG_FOLDER.$photo_name, 200, 150, SHOP_IMG_FOLDER.'thumb/'.$photo_name);
						// update photo
						mysqli_query($con, "UPDATE tbl_purchase_partner SET image = '".$photo_name."' WHERE id = ".$insert_id);
					}
				}*/
				
				//send mail
				//get from email address
				$settingsRec = mysqli_fetch_array(mysqli_query($con, "SELECT from_email FROM tbl_settings WHERE id = '1'"));
				$fromEmail = $settingsRec['from_email'];
				$mail = new PHPMailer();
				$mail->From = $fromEmail;
				$mail->FromName = SITE_NAME;
				$mail->IsHTML(true);	
				$mail->Subject = SITE_NAME.' Purchase Partner';
		
				
				$mail->AddAddress($email, $name);					
				$to_name = $name;			
		
						$email_content = '<table width="600" border="0" align="center" cellpadding="0" cellspacing="0">
					  <tr>
						<td height="68" align="left" valign="top"><a href="'.BASE_URL.'" target="_blank"><img src="'.BASE_URL.'images/logo.png" /></a></td>
						<td align="right" valign="bottom" style="color:#ff8d07;">&nbsp;</td>
					  </tr>
					   <tr>
						<td height="5" colspan="2" align="left" valign="top"></td>
					  </tr>
					  <tr>
						<td height="49" colspan="2" align="left" valign="top" bgcolor="#970198" style="padding:10px 0px 0px 20px; color:#FFFFFF; font-size:24px; font-family:Times New Roman, Times,   serif;">'.SITE_NAME.' Signup</td>
					  </tr>
					  <tr>
						<td colspan="2" align="left" valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="0" style="border:#970198 solid 1px;">
						  <tr>
							<td height="4" colspan="4" align="left" valign="top" bgcolor="#970198"></td>
						  </tr>
						  <tr>
							<td height="8" colspan="4" align="left" valign="top"></td>
						  </tr>
							<tr>
							<td width="258" align="left" valign="top" style="color:#4e4e4e; font-size:13px; line-height:16px; padding:0px 0px 0px 9px;">Hello  '. $name .',</td>
						  </tr>
							  <tr>
								<td height="8" align="left" valign="top" style="color:#4e4e4e; font-size:11px;  padding:0px 0px 0px 9px;"></td>
							</tr>
						  <tr>
							<td height="10" colspan="4" align="left" valign="top"></td>
						  </tr>
						  <tr>
							<td colspan="4" align="left" valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="0">
							  <tr>
								<td width="8" align="left" valign="top">&nbsp;</td>
								<td width="581" height="140" align="left" valign="top" bgcolor="#f0f0f0" style="border:#c9ccc5 solid 1px; line-height:18px; padding:10px 0px 0px 8px; font-size:11px; font-weight:normal; line-height:27px;">
									<p></p>
									<p>You have been registered in '.SITE_NAME.'</p>
									<p>Your login email: '.$email.'</p>
									<p>Your login password: '.$password.'</p>
									<p></p>
								  </td>
								<td width="7" align="left" valign="top">&nbsp;</td>
							  </tr>
							</table></td>
						  </tr><tr>
							<td colspan="4" align="left" valign="top">&nbsp;</td>
						  </tr>
						</table></td>
					  </tr>
					</table>';
				$mail->Body = $email_content;
				if($mail->Send()){
					$success = 'Shop Added Successfully. Mail Sent';
				} else {
					$success = 'Shop Added Successfully. Unable to send mail';
				}
								
				
				header('Location:index.php?page=manage_purchase_partner&success='.$success);
				exit();			
			} else {
				$error = 'Unable to add user';
			}		
		}		
	} 
}

if(isset($_POST['update'])) {
	
	if(isset($_FILES['photo']) && $_FILES['photo']['size'] > 0) {		
		if($_FILES['photo']['type'] == 'image/gif' || $_FILES['photo']['type'] == 'image/jpeg' || 
		   $_FILES['photo']['type'] == 'image/png' || $_FILES['photo']['type'] == 'image/pjpeg') {
			$photo_name = $_FILES['photo']['name'];			
			$photo_temp_name = $_FILES['photo']['tmp_name'];
			$photo_extension = pathinfo($photo_name, PATHINFO_EXTENSION);
		} else {
			$photo_name = FALSE;
			$photo_temp_name = FALSE;
			$error = "Invalid Image type. Only gif, jpg and png allowed";
		}
	}

	if(strlen(trim($_POST['discount'])) > 0) {
		$discount = trim($_POST['discount']);
		if(is_numeric($discount)){
			if($discount>=0 && $discount<=100){
				//ok
			} else {
				$error = 'Please enter a valid discount';
			}
		} else {
			$error = 'Please enter a numeric value for discount';
		}
	} else {
		$discount = 0;
	}
	
	if(strlen(trim($_POST['commission_user'])) > 0) {
		$commission_user = trim($_POST['commission_user']);
		if(is_numeric($commission_user)){
			//ok
		} else {
			$error = 'Please enter a numeric value for user commission';
		}
	} else {
		$commission_user = 0;
	}
		
	if(strlen(trim($_POST['commission'])) > 0) {
		$commission = trim($_POST['commission']);
		if(is_numeric($commission)){
			//ok
		} else {
			$error = 'Please enter a numeric value for commission';
		}
	} else {
		$commission = 0;
	}
	
	if(strlen(trim($_POST['city'])) > 0) {
		$city = trim($_POST['city']);
	} else {
		$city = '';
	}
	
		
	if(strlen(trim($_POST['longitude'])) > 0) {
		$longitude = trim($_POST['longitude']);		
	} else {
		if(strlen(trim($_POST['place'])) > 0) {
			$error = 'Sorry Unable to fetch lat-long from the location. Enter location and click on map to fetch Lat-Long';
		} else {
			$error = 'Please enter location to fetch lat-long';
		}		
	}
	
	if(strlen(trim($_POST['latitude'])) > 0) {
		$latitude = trim($_POST['latitude']);		
	} else {
		if(strlen(trim($_POST['place'])) > 0) {
			$error = 'Sorry Unable to fetch lat-long from the location. Enter location and click on map to fetch Lat-Long';
		} else {
			$error = 'Please enter location to fetch lat-long';
		}		
	}
	
	if(strlen(trim($_POST['place'])) > 0) {
		$place = trim($_POST['place']);		
		$placeArr = explode(',', $place);
		$place = $placeArr[0];
	} else {
		$error = 'Please enter location';
	}
	
	if(strlen(trim($_POST['address'])) > 0) {
		$address = trim($_POST['address']);
	} else {
		$address = '';
	}
	
	if(strlen(trim($_POST['building_name'])) > 0) {
		$building_name = trim($_POST['building_name']);
	} else {
		$error = 'Please enter Shop Name';
	}
	
	if(strlen(trim($_POST['mobile'])) > 0) {
		$mobile = trim($_POST['mobile']);
		if(is_numeric($mobile) && strlen($mobile)==10){
			$checkPhone = mysqli_query($con,"SELECT id FROM tbl_purchase_partner WHERE mobile='".mysqli_real_escape_string($con,$mobile)."' AND status != 'Deleted' AND id != '".$editId."'");
			if(isset($checkPhone) && mysqli_num_rows($checkPhone)>0) {
				$error = 'A partner with the same mobile number exists';
			}
		} else {
			$error = 'Invalid mobile number';
		}
	} else {
		$mobile = '';
	}
			
	if(strlen(trim($_POST['phone'])) > 0) {
		$phone = trim($_POST['phone']);
		if(is_numeric($phone) && (strlen($phone)>8 && strlen($phone)<13)){
			//ok
		} else {
			$error = 'Please enter phone number only digits with coutry code';
		}
	} else {
		//$error = 'Please enter Phone Number';
		$phone = '';
	}

	if(isset($_POST['email']) && strlen(trim($_POST['email'])) > 0) {
		$email = trim($_POST['email']);
		if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
			$error =  "E-mail is not valid";
		} else {
			// check Email
			$checkEmail = mysqli_query($con,"SELECT id FROM tbl_purchase_partner WHERE email='".mysqli_real_escape_string($con,$email)."' AND status != 'Deleted' AND id != '".$editId."'");
			if(isset($checkEmail) && mysqli_num_rows($checkEmail)>0) {
				$error = 'Email Already Taken';
			}
		}
	} else {
		$error = 'Please enter Email';
	}
	
	if(isset($_POST['name']) && strlen($_POST['name'])>0) {
		$name = trim($_POST['name']);
	} else {
		$error = 'Please Enter Shop Name';
	}	
		
	if(empty($error)) {
		
		if(isset($_POST['change_latlong']) && $_POST['change_latlong']=='yes'){	
			if(count($placeArr)>1){
				$mapPlace = $_POST['place'];		
				$latLong = getLatLong($mapPlace);			
				if(is_array($latLong) && $latLong['latitude']!='' && $latLong['longitude']!=''){
					//ok
					$latitude = $latLong['latitude'];
					$longitude = $latLong['longitude'];
				} else {
					$error = 'Unable to find lat-long from the location - '.$formattedAddress.'. Try again';
				}
			}
		}
						
		
		if(empty($error)){
			
			$updateQry = "UPDATE tbl_purchase_partner SET name = '".$name."', email = '".$email."', phone = '".$phone."', mobile ='".$mobile."', building_name = '".$building_name."', address = '".$address."', place = '".$place."', 
			city = '".$city."', latitude = '".$latitude."', longitude = '".$longitude."', commission = '".$commission."', commission_user = '".$commission_user."', discount = '".$discount."', added_by = '".$_SESSION['adminId']."' WHERE id = '".$editId."'";
			//echo $updateQry;
			$execUpdate = mysqli_query($con,$updateQry);			
			
			if($execUpdate) {
				
				if(isset($_POST['change_latlong']) && $_POST['change_latlong']=='yes'){
					$updateQry = "UPDATE tbl_purchase_partner SET latitude = '".$latitude."', longitude = '".$longitude."' WHERE id = '".$editId."'";
					mysqli_query($con,$updateQry);
				}	
				
				if(isset($_FILES['photo']) && $_FILES['photo']['size'] > 0) {
					$photo_dir = SHOP_IMG_FOLDER;
					$photo_name = $editId.'_'.time().'.'.$photo_extension; 
					if(move_uploaded_file($photo_temp_name, $photo_dir.$photo_name)){
						resize2(SHOP_IMG_FOLDER.$photo_name, 200, 150, SHOP_IMG_FOLDER.'thumb/'.$photo_name);
						// update photo
						mysqli_query($con, "UPDATE tbl_purchase_partner SET image = '".$photo_name."' WHERE id = ".$editId);
					}
				}
				
				$exec_token = mysqli_query($con, 'SELECT fcm_token, device FROM tbl_fcm_tokens WHERE tech_id='.$editId);
				if(isset($exec_token) && mysqli_num_rows($exec_token)>0) {
					while($res_token = mysqli_fetch_array($exec_token)) {	
						if($res_token['fcm_token']!='') {							
							$title = SITE_NAME;
							$body = 'Shop details have been updated';
							if($res_token['device']=='android') {								
								sendGCM($title, $body, $res_token['fcm_token'], "partner");
							} else {
								//sendIosTechPush($title, $body, $res_token['fcm_token'], "partner");
							}							
						}
					}
				}
				
				$success = 'User Updated Successfully';
				header('Location:index.php?page=manage_purchase_partner&success='.$success);
				exit();			
			} else {
				$error = 'Unable to update user';
			}		
		}			
	} 
}
?>