<?php
session_start();
include("../include/config.php");
include("../include/functions.php"); 
include("../include/simpleimage.php");
 validate_admin();

 $base_url= 'https://www.quicklly.com/blog';
   
  if($_REQUEST['submitForm']=='yes'){
    $id=$_REQUEST['id'];
    $preview = $_REQUEST['preview'];
    $url=mysqli_real_escape_string($GLOBALS['conn'],$_REQUEST['url']);
	$metatitle=mysqli_real_escape_string($GLOBALS['conn'],$_REQUEST['title']);
    $viewallproduct_url = mysqli_real_escape_string($GLOBALS['conn'],$_REQUEST['viewallproduct_url']);
    $urlLabel=mysqli_real_escape_string($GLOBALS['conn'],$_REQUEST['urlLabel']);
	$metadesc=mysqli_real_escape_string($GLOBALS['conn'],$_REQUEST['description']);
	$metakeyword=mysqli_real_escape_string($GLOBALS['conn'],$_REQUEST['keyword']);
	$h1=mysqli_real_escape_string($GLOBALS['conn'],$_REQUEST['h1']);
	$imagealt=mysqli_real_escape_string($GLOBALS['conn'],$_REQUEST['imagealt']);
	$posteddate=$_REQUEST['posteddate'].' '.date('H:i:s');
	$content=mysqli_real_escape_string($GLOBALS['conn'],$_REQUEST['content']);
	$item_heading=$_REQUEST['product_heading'];
	$changeposted_date = strtotime($posteddate);
//date('Y-m-d', $d);
	$posted_date=date('d M', $changeposted_date);
	$year=date('Y', $changeposted_date);
	$pname_count = count($_POST['pname']);

    $auth_name=mysqli_real_escape_string($GLOBALS['conn'],$_REQUEST['auth_name']);
    $auth_designation=mysqli_real_escape_string($GLOBALS['conn'],$_REQUEST['auth_designation']);
    $auth_bio=mysqli_real_escape_string($GLOBALS['conn'],$_REQUEST['auth_bio']);
    $auth_web=mysqli_real_escape_string($GLOBALS['conn'],$_REQUEST['auth_web']);
    $auth_fb=mysqli_real_escape_string($GLOBALS['conn'],$_REQUEST['auth_fb']);
    $auth_tw=$_REQUEST['auth_tw'];
    $auth_in=mysqli_real_escape_string($GLOBALS['conn'],$_REQUEST['auth_in']);

	$where='';
			
 if($_FILES['photo']['size']>0 && $_FILES['photo']['error']==''){

  $image_name = buildURL($metatitle);
  $image_name = str_replace("'","",str_replace('"',"",$image_name));

  $Image= new SimpleImage();

  $filename = $_FILES['photo']['name'];
  $ext = pathinfo($filename, PATHINFO_EXTENSION);
  
  $img=time()."-".$image_name.".".$ext;
  
  //ftp start
  if(SITE_URL==MAINSITE_URL){
$conn_id = ftp_connect("3.133.214.148") or die("Error in FTP connection");  // the FTP server you want to connect to.
$login_status = ftp_login($conn_id, "mainuser@quicklly.com", "n3At8hv3LZKCiF6") or die("Error in FTP login");  // Login to the FTP server.
//echo $img; exit;
//to upload from local
ftp_pasv($conn_id, true);
//to create dir
//ftp_mkdir($conn_id, "imageststs");
  $target_file = $_FILES['photo']['tmp_name'];
  $destination_file = "upload_images/blog/".$img;  // since you want to upload to a directory called "images".
  
$upload_status = ftp_put($conn_id, $destination_file, $target_file, FTP_BINARY);

if (!$upload_status)
{
   echo "Something went wrong, Contact to site administrator."; // do whatever it is that you want to do when you are unable to upload the file.
}

// Close the FTP connection after you are done.
ftp_close($conn_id);
}else{
die("FTP connection failed");
}
  //ftp ends
 move_uploaded_file($_FILES['photo']['tmp_name'],"../upload_images/blog/".$img);
  $imgvalue=", feature_img='$img'";
  } else {
	  $imgvalue="";
  }

   if($_FILES['auth_photo']['size']>0 && $_FILES['auth_photo']['error']==''){

  $auth_image_name = buildURL($auth_name);
  $auth_image_name = str_replace("'","",str_replace('"',"",$auth_image_name));

  $Image= new SimpleImage();

  $auth_filename = $_FILES['auth_photo']['name'];
  $auth_ext = pathinfo($auth_filename, PATHINFO_EXTENSION);
  
  $auth_img=time()."-".$auth_image_name.".".$auth_ext;
  
  //ftp start
  if(SITE_URL==MAINSITE_URL){
$conn_id = ftp_connect("3.133.214.148") or die("Error in FTP connection");  // the FTP server you want to connect to.
$login_status = ftp_login($conn_id, "mainuser@quicklly.com", "n3At8hv3LZKCiF6") or die("Error in FTP login");  // Login to the FTP server.

//echo $img; exit;
//to upload from local
ftp_pasv($conn_id, true);
//to create dir
//ftp_mkdir($conn_id, "imageststs");
  $auth_target_file = $_FILES['auth_photo']['tmp_name'];
  $auth_destination_file = "upload_images/blog/author/".$auth_img;  // since you want to upload to a directory called "images".
  
$auth_upload_status = ftp_put($conn_id, $auth_destination_file, $auth_target_file, FTP_BINARY);

if (!$auth_upload_status)
{
   echo "Something went wrong, Contact to site administrator."; // do whatever it is that you want to do when you are unable to upload the file.
}

// Close the FTP connection after you are done.
ftp_close($conn_id);
}else{
die("FTP connection failed");
}
  //ftp ends
 move_uploaded_file($_FILES['auth_photo']['tmp_name'],"../upload_images/blog/author/".$auth_img);
  $auth_imgvalue=", author_photo='$auth_img'";
  } else {
      $auth_imgvalue="";
  }

  if($preview == '')
  {
      $status = "status='1'";
    } else {

        if ($id == '') {

            $status = "status='1'";
        } else {
            $sqlpreviewstatus = $obj->Query("select * from tbl_blog where id = '$id'  order by id desc limit 1");


            $checkpreviewstatus = $obj->fetchNextObject($sqlpreviewstatus);
            if ($checkpreviewstatus->status == 1) {
                $status = "status='1'";
            } else {
      $status = "status='0'";
  }
        }
    }

if($id==''){	

        $sqlcheck = $obj->Query("select * from tbl_blog  where  title= '$metatitle' and description = '$metadesc' and  h1 = '$h1' ");
        $checkdata = $obj->fetchNextObject($sqlcheck);
  
     if(($checkdata->title != $metatitle) && ($checkdata->description != $metadesc) && ($checkdata->h1 != $h1))
     {

	$sql=$obj->query("insert into tbl_blog set title='$metatitle', keyword='$metakeyword', description='$metadesc', content='$content', h1='$h1', url='$url', image_alt='$imagealt', posted_by='".$_SESSION['sess_admin_username']."', item_heading='$item_heading', posteddate='$posteddate', posted_date='$posted_date', year='$year', viewallproduct_url = '$viewallproduct_url',urlLabel='$urlLabel',author_name='$auth_name', author_designation='$auth_designation', author_bio='$auth_bio', author_web='$auth_web', author_fb='$auth_fb', author_tw='$auth_tw', author_in='$auth_in', $status  $imgvalue $auth_imgvalue "); 
	$blog_id=$obj->lastInsertedId();
	
	if ($pname_count >= 0){
    for ($x=0; $x < $pname_count; $x++) { 

        $pname = $_POST["pname"][$x];
        $product_id = $_POST["q_id"][$x];

        $obj->query("INSERT INTO tbl_blog_product(`blog_id`, `product_id`) VALUES ('$blog_id', '$product_id')");
    }
}
}


} else {

	$sql=$obj->query("update tbl_blog set title='$metatitle', keyword='$metakeyword', description='$metadesc', content='$content', h1='$h1', url='$url', image_alt='$imagealt', posted_by='".$_SESSION['sess_admin_username']."', item_heading='$item_heading', viewallproduct_url = '$viewallproduct_url',urlLabel='$urlLabel',author_name='$auth_name', author_designation='$auth_designation', author_bio='$auth_bio', author_web='$auth_web', author_fb='$auth_fb', author_tw='$auth_tw', author_in='$auth_in', $status, posteddate='$posteddate',posted_date='$posted_date',year='$year' $imgvalue $auth_imgvalue where id='$id' ");



     $image_name = buildURL($metatitle);
     $image_name = str_replace("'","",str_replace('"',"",$image_name));
	if ($pname_count >= 0){
		$obj->query("delete from tbl_blog_product where blog_id='$id'");
    for ($x=0; $x < $pname_count; $x++) { 

        $pname = $_POST["pname"][$x];
        $product_id = $_POST["q_id"][$x];

        $obj->query("INSERT INTO tbl_blog_product(`blog_id`, `product_id`) VALUES ('$id', '$product_id')");
    }
}
}

if($preview != 'Preview')
{

  header("location:blog-list.php?success=Added Successfully!");
}     

else{
    
    if(($checkdata->title != $metatitle) && ($checkdata->description != $metadesc) && ($checkdata->h1 != $h1))
    {
    if($id==''){
  
  header("location:$base_url/$blog_id/$image_name");
    }
    else
    {
    header("location:$base_url/$id/$image_name");
    }
   }

   else{
    header("location:blog-list.php?Blog Already Submmitted!");
   }

}
  
   
}     

	
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title><?php echo SITE_TITLE; ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="css/admin.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="../include/ckeditor/ckeditor.js"></script>

</head>
<body>
<table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0">
<?php include("header.php");
$sql=$obj->query("select * from tbl_blog where id='".$_REQUEST['id']."'");
$result=$obj->fetchNextObject($sql); 

?>

<tr>
	<td align="right" class="paddRtLt70" valign="top">
		<table width="99%" border="0" cellspacing="0" cellpadding="0">
			<tr>
				
				<td align="right" valign="top">
					<table width="100%" border="0" cellspacing="0" cellpadding="0">
						<tr>
							<td align="left" valign="middle" class="headingbg bodr text14">
					<em><img src="images/arrow2.gif" width="21" height="21" hspace="10" align="absmiddle" /></em>Admin: Add  Blog 
					<span  style="float:right; padding-right:10px;">
					<input type="button" name="add" value="View  Blogs"  class="button" onclick="location.href='blog-list.php'" /></span></td>
						</tr>
						
						<tr>
							<td height="100" align="left" valign="top" bgcolor="#f3f4f6" class="bodr">
                            <form name="blog" enctype="multipart/form-data" method="post"   onsubmit="return validate(this)" action="">
						<input type="hidden" name="submitForm" value="yes" />
						<input type="hidden" name="id" value="<?php echo $_REQUEST['id'];?>" />
							<table width="100%" cellpadding="0" cellspacing="0">
									<tr>
										<td align="center" colspan="2" class="paddRt14 paddBot11">
										<font color="#FF0000"><strong><?php echo $_SESSION['sess_msg']; $_SESSION['sess_msg']='';?></strong></font></td>
									</tr>
									
									<tr>
                                      <td align="right" class="paddBot11 paddRt14"><strong> Meta Title:</strong></td>
									  <td align="left" class="paddBot11"><input name="title" type="text" size="150" value="<?php echo stripslashes($result->title);?>" /></td>
							  </tr>
							  <tr>
                                      <td align="right" class="paddBot11 paddRt14"><strong> Meta Keyword:</strong></td>
									  <td align="left" class="paddBot11"><input name="keyword" type="text" size="150" value="<?php echo stripslashes($result->keyword);?>" /></td>
							  </tr>
							  <tr>
                                      <td align="right" class="paddBot11 paddRt14"><strong> Meta Description:</strong></td>
									  <td align="left" class="paddBot11"><input name="description" type="text" size="150" value="<?php echo stripslashes($result->description);?>" /></td>
							  </tr>
							  <tr>
                                      <td align="right" class="paddBot11 paddRt14"><strong>H1:</strong></td>
									  <td align="left" class="paddBot11"><input name="h1" type="text" size="150" value="<?php echo stripslashes($result->h1);?>" /></td>
							  </tr>
							  <tr>
                                      <td align="right" class="paddBot11 paddRt14"><strong>Custom URL:</strong></td>
									  <td align="left" class="paddBot11"><input name="url" type="text" size="150" value="<?php echo stripslashes($result->url);?>" /></td>
							  </tr>
                               <tr>
                                      <td align="right" class="paddBot11 paddRt14"><strong>Featured Image:</strong></td>
									  <td align="left" class="paddBot11"><input name="photo" type="file"  /><br/>
                                      <?php if(is_file("../upload_images/blog/".$result->feature_img)) {?>
                                      <img src="../upload_images/blog/<?php echo $result->feature_img; ?>" width="100" height="100" />
                                      <?php } ?>
                                      </td>
							       </tr>
							<tr>
                                      <td align="right" class="paddBot11 paddRt14"><strong>Image ALT Tag:</strong></td>
									  <td align="left" class="paddBot11"><input name="imagealt" type="text" size="150" value="<?=$result->image_alt ?>" /></td>
							  </tr>
                          <tr>
                                      <td align="right" class="paddBot11 paddRt14"><strong>Content</strong></td>
									  <td align="left" class="paddBot11"><textarea id="content" class="ckeditor" name="content" rows="5" cols="40"><?php echo stripslashes($result->content); ?></textarea>
                                      </td>
							       </tr>


                                   <tr>
                                      <td align="right" class="paddBot11 paddRt14"><strong>Author Name:</strong></td>
                                      <td align="left" class="paddBot11"><input name="auth_name" type="text" size="150" value="<?php echo stripslashes($result->author_name);?>" /></td>
                              </tr>
                              <tr>
                                      <td align="right" class="paddBot11 paddRt14"><strong>Author Designation:</strong></td>
                                      <td align="left" class="paddBot11"><input name="auth_designation" type="text" size="150" value="<?php echo stripslashes($result->author_designation);?>" /></td>
                              </tr>
                              <tr>
                                      <td align="right" class="paddBot11 paddRt14"><strong>Author Bio:</strong></td>
                                      <td align="left" class="paddBot11"><textarea name="auth_bio" cols="100" rows="5" ><?php echo stripslashes($result->author_bio);?></textarea></td>
                              </tr>

                              <tr>
                                      <td align="right" class="paddBot11 paddRt14"><strong>Author Web Page:</strong></td>
                                      <td align="left" class="paddBot11"><input name="auth_web" type="text" size="150" value="<?php echo stripslashes($result->author_web);?>" /></td>
                              </tr>

                              <tr>
                                      <td align="right" class="paddBot11 paddRt14"><strong>Author Facebook Page:</strong></td>
                                      <td align="left" class="paddBot11"><input name="auth_fb" type="text" size="150" value="<?php echo stripslashes($result->author_fb);?>" /></td>
                              </tr>
                              <tr>
                                      <td align="right" class="paddBot11 paddRt14"><strong>Author Twitter Page:</strong></td>
                                      <td align="left" class="paddBot11"><input name="auth_tw" type="text" size="150" value="<?php echo stripslashes($result->author_tw);?>" /></td>
                              </tr>
                              <tr>
                                      <td align="right" class="paddBot11 paddRt14"><strong>Author Linkedin Page:</strong></td>
                                      <td align="left" class="paddBot11"><input name="auth_in" type="text" size="150" value="<?php echo stripslashes($result->author_in);?>" /></td>
                              </tr>
                               <tr>
                                      <td align="right" class="paddBot11 paddRt14"><strong>Author Photo:</strong></td>
                                      <td align="left" class="paddBot11"><input name="auth_photo" type="file"  /><br/>
                                      <?php if(is_file("../upload_images/blog/author/".$result->author_photo)) {?>
                                      <img src="../upload_images/blog/author/<?php echo $result->author_photo; ?>" width="100" height="100" />
                                      <?php } ?>
                                      </td>
                                   </tr>


                             <tr>
                             	<td align="right" class="paddBot11 paddRt14"><strong>Product List Heading</strong></td>
                             	<td align="left" class="paddBot11"><input type="text" name="product_heading" value="<?php echo stripslashes($result->item_heading); ?>" style="width: 320px"> &nbsp; </td>
                             </tr>
                             <tr>

                             	<td align="right" class="paddBot11 paddRt14"><strong>Url Label</strong></td>

                             	<td align="left" class="paddBot11"><input type="text" name="urlLabel" value="<?php echo $result->urlLabel; ?>" style="width: 320px"> &nbsp; </td>

                             </tr>
                             <tr>

                             	<td align="right" class="paddBot11 paddRt14"><strong>Enter URL</strong></td>

                             	<td align="left" class="paddBot11"><input type="text" name="viewallproduct_url" value="<?php echo $result->viewallproduct_url; ?>" style="width: 320px"> &nbsp; </td>

                             </tr>
                              
<!--<tr>
<td align="right" class="paddBot11 paddRt14"><strong>Category</strong></td>
<td align="left" class="paddBot11"><select name="bloglistcategory" required>
<option value="">Select Category</option>
<?php /*$sqlcategory=$obj->query("select id,maincategory from tbl_maincategory where status=1 and parent_id=0 and section_id=1 order by maincategory");
while($resulcategory=$obj->fetchNextObject($sqlcategory)){ ?>
<option value="<?php echo $resulcategory->id; ?>"><?php echo ucwords($resulcategory->maincategory); ?></option>
<?php } */?>
</select></td>
</tr>
-->

<?php $sqlblogprod=$obj->query("select *,bp.id,product_name,bp.storeid from tbl_blog_product bp join tbl_product p on p.id=bp.product_id where bp.blog_id='".$_REQUEST['id']."'");
$blogprodnum=$obj->numRows($sqlblogprod);
if($_REQUEST['id']=='' || $blogprodnum==0){ ?>
<tr>
<td align="right" class="paddBot11 paddRt14"><strong>Product</strong></td>
<td align="left" class="paddBot11" id="TextBoxContainer"><strong>Product List</strong></td>
</tr>

<tr>
<td align="right" class="paddBot11 paddRt14"></td>
<td align="left" class="paddBot11">
<button id="btnAdd" type="button" style="background: #078712; color: #FFF; border: none; padding: 3px 8px; border-radius: 4px;cursor: pointer">Add Product</button>
</td>
</tr>
<?php }else{ ?>
<tr>
<td align="right" class="paddBot11 paddRt14"><strong>Product</strong></td>
<td align="left" class="paddBot11"><strong>Product List</strong></td>
</tr>
<?php $p=0;
while($resultproduct=$obj->fetchNextObject($sqlblogprod)){
$p++; ?>
<tr>
    <td></td>
    <td>
<table>
    <tr>
<td align="" class=""></td>

<td align="" class="" style="">

<input type="text" name="pname[]" value="<?php echo $resultproduct->product_name; ?>" onkeyup="myFunction(this.value,'search-box<?=$p+100?>')" class="form-controls srchAddexist" required style="width:320px" autocomplete="off"/><div class="result" id="resultsearch-box<?php echo $p+100; ?>"></div><input name ="q_id[]" type="hidden" value="<?php echo $resultproduct->product_id; ?>" class="form-control srcAddexist"/>

</td>
<td >
    <button type="button" class="remove" style="background:none; border:none; cursor:pointer;margin-top:0px; 

"><img src="images/remove.png" style="width:25px;"></button>
</td>
</tr>
</table>
</td>
</tr>

<?php } ?>
<tr>
<td align="right" class="paddBot11 paddRt14"></td>
<td align="left" class="paddBot11" id="TextBoxContainer"></td>
</tr>
<tr>
<td align="right" class="paddBot11 paddRt14"></td>
<td align="left" class="paddBot11">
<button id="btnAdd" type="button" style="background: #078712; color: #FFF; border: none; padding: 3px 8px; border-radius: 4px;cursor: pointer">Add Product</button>
</td>
</tr>
<?php } ?>
</tr>
                              
									<tr>
									  <td align="right" class="paddRt14 paddBot11">&nbsp; Post Date</td>
									  <td align="left" class="paddBot11">&nbsp;<input type="date" value="<?php 
									  $d = strtotime($result->posteddate);
echo date('Y-m-d', $d); // 2018-06-12
									  ?>" required name="posteddate"></td>
							  </tr>
									<tr>
										<td width="18%" align="right" class="paddRt14 paddBot11">&nbsp;</td>
										<td width="82%" align="left" class="paddBot11">
											<input type="submit" name="submit" value="Submit" onclick='this.form.target="_self";'  class="submit" border="0"/> 	                  		 &nbsp;&nbsp;
											<input type="submit" name="preview" onclick='this.form.target="_blank";'  value="Preview" id="preview"   class="submit" border="0"/> 
											<input name="Reset" type="reset" id="Reset" value="Reset" class="submit" border="0" />									  </td>
									</tr>
								</table></form>
							</td>
						</tr>
						
					</table>
				</td>
			</tr>
		</table>
	</td>
</tr>
<?php include('footer.php'); ?>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-tagsinput/1.3.6/jquery.tagsinput.min.js"></script>

        <script type="text/javascript">
    $("#btnAdd").bind("click", function () {
        var div = $("<tr/>");
        div.html(GetDynamicTextBox());
        $("#TextBoxContainer").append(div);
    });
    $("body").on("click", ".remove", function () {
        $(this).closest("tr").remove();
    });
   var x = 1;

    function GetDynamicTextBox() {
        var x =  $('#TextBoxContainer .srchAdd').length;
        x = x + 1;
        var srchId ='search-box'+x;
        return '<td><input type="text" name="pname[]"  id="'+srchId+'" onkeyup="myFunction(this.value,this.id)" class="form-controls srchAdd" required style="width:320px; margin-left:6px;" autocomplete="off"/><div class="result" id="result'+srchId+'"></div><input name ="q_id[]" type="hidden" class="form-control srcAdd"/></td>'+'<td><button type="button" class="remove" style="background:none; border:none; cursor:pointer"><img src="images/remove.png" style="width:25px;margin-left: 6px;"></button></td>'
    }
    
    function validate(obj)
{
    
if(obj.title.value==''){
alert("Please enter Meta Title");
obj.title.focus();
return false;
}
if(obj.description.value==''){
alert("Please enter Meta Description");
obj.description.focus();
return false;
}
if(obj.h1.value==''){
alert("Please enter H1");
obj.h1.focus();
return false;
}

if(obj.id.value == ''){
if(obj.photo.value==''){
alert("Please Upload Image");
obj.photo.focus();
return false;
}
}

}




</script>
<script>
    function myFunction(val,s_id){
       var search = val;
        var searchItmId = s_id;
        var sid = 'result'+s_id;
    $.ajax({
    type: "POST",
    url: "add_product.php",
        data: {keyword: search ,search_id:sid},
    beforeSend: function(){
      // $("#"+searchItmId).css("background","#FFF url(./images/chef/LoaderIcon.gif)");
    },
    success: function(data){
     // console.log(data);
      $("#result"+searchItmId).show();
      $("#result"+searchItmId).html(data);
      $("#"+searchItmId).css("background","#FFF");
    }
    });
};

//To select list
function selectCountry(val,search_id,id) {
$('.srchAdd:last').val(val);
$('.srcAdd:last').val(id);
$("#"+search_id).hide();
}
</script>
    <style>
#product-list{float:left;list-style:none;margin-top:0px;padding:0;width:328px;position: absolute;z-index: 999;}
#product-list li{padding: 5px; background: #fff; border-bottom: #bbb9b9 1px solid;}
#product-list li:hover{background:#eee;cursor: pointer;}
 </style>
</body>
</html>


