<?php include_once("../includes/cmain.inc.php");

$customSessionPath = __DIR__ . "/tmp_sessions";
if (!file_exists($customSessionPath)) {
    mkdir($customSessionPath, 0777, true);
}
session_save_path($customSessionPath);
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
$headerTitleName = "Add New Blog";
$page_id = $_REQUEST['page_id'];
$id = '1';



if(is_post_back()) {
	if($page_id!='') {	
	    $heading=$_POST['heading'];
	$post_writer=$_POST['post_writer'];
	$cat_name=$blogTagIm ?? '';
	$status=$_POST['status'];
	$title=$_POST['title'];
	$description=$_POST['description'];
	$keyword=$_POST['keyword'];
//	$blog_banner=$sv_image_1;
	$content=$_POST['content'];
	//$conclusion=$_POST['conclusion'];
	$alt=$_POST['alt'];
	$tag1=$_POST['tag1'];
	$tag2=$_POST['tag2'];
	$tag3=$_POST['tag3'];
	$tag4=$_POST['tag4'];
	$tag5=$_POST['tag5'];
$blogTagIm = '';
if (!empty($_POST['cat_name']) && is_array($_POST['cat_name'])) {
    $blogTagIm = implode(",", $_POST['cat_name']);
}		$sql = "update `tbl_blog` set heading='".addslashes($heading)."', content='".addslashes($content)."',alt='".addslashes($alt)."',tag1='".addslashes($tag1)."',tag2='".addslashes($tag2)."',tag3='".addslashes($tag3)."',tag4='".addslashes($tag4)."',tag5='".addslashes($tag5)."',title='".addslashes($title)."',description='".addslashes($description)."', keyword='".addslashes($keyword)."', status='".addslashes($status)."', post_writer='".addslashes($post_writer)."',cat_name='".$blogTagIm."', post_date=now() where id = $page_id ";
		db_query($sql);
		########### Uploading Image ################
		if($_FILES['sv_image']['name']!='')
		{
		    		  	    $sv_image = isset($sv_image) ? $sv_image : ''; // or use $sv_image = $sv_image ?? '';

			if(strlen($sv_image) && file_exists(UP_FILES_FS_PATH."/blog/thumb/".$sv_image)){
				@unlink(UP_FILES_FS_PATH."/blog/thumb/".$sv_image);
			}
			$sv_image_1 = $_FILES['sv_image']['name'];
		//	$sv_image_1 = md5(uniqid(rand(), true)).'.'.file_ext($_FILES[sv_image]['name']);
				copy($_FILES['sv_image']['tmp_name'], UP_FILES_FS_PATH."/blog/thumb/".$sv_image_1) or die("Image is not uploaded");
				copy($_FILES['sv_image']['tmp_name'], UP_FILES_FS_PATH."/blog/original/".$sv_image_1) or die("Image is not uploaded");
			$n_width=225; // Fix the width of the thumb nail images
			$n_height=168; // Fix the height of the thumb nail imaage
			
			$tsrc=UP_FILES_FS_PATH."/blog/thumb/".$sv_image_1;
			$add=UP_FILES_FS_PATH."/blog/original/".$sv_image_1; // Path where thumb nail image will be stored
			
			//echo $tsrc;
			if (!($_FILES['sv_image']['type'] =="image/pjpeg" OR $_FILES['sv_image']['type']=="image/jpeg" OR $_FILES['sv_image']['type']=="image/png" OR $_FILES['sv_image']['type']=="image/webp")){echo "Your uploaded file must be of JPG or GIF or PNG. Other file types are not allowed<BR>";
			exit;}
				///////// starting of JPG thumb nail creation//////////
			if($_FILES['sv_image']['type']=="image/pjpeg" OR $_FILES['sv_image']['type']=="image/jpeg")
			{
				$im=ImageCreateFromJPEG($add);
				$width=ImageSx($im); // Original picture width is stored
				$height=ImageSy($im); // Original picture height is stored
				$newimage=imagecreatetruecolor($n_width,$n_height);
				imageCopyResized($newimage,$im,0,0,0,0,$n_width,$n_height,$width,$height);
				ImageJpeg($newimage,$tsrc);
				chmod("$tsrc",0777);
			}
			elseif($_FILES['sv_image']['type'] == "image/png"){
				$im=ImageCreateFromPNG($add);
				$width=ImageSx($im); // Original picture width is stored
				$height=ImageSy($im); // Original picture height is stored
				$newimage=imagecreatetruecolor($n_width,$n_height);
				imageCopyResized($newimage,$im,0,0,0,0,$n_width,$n_height,$width,$height);
				ImagePng($newimage,$tsrc);
				chmod("$tsrc",0777);
			}
			elseif ($_FILES['sv_image']['type'] == "image/webp") {
                 $im = imagecreatefromwebp($add); // Create image from WebP
                 $width = imagesx($im); // Original picture width is stored
                 $height = imagesy($im); // Original picture height is stored
                 $newimage = imagecreatetruecolor($n_width, $n_height);
                 imagecopyresized($newimage, $im, 0, 0, 0, 0, $n_width, $n_height, $width, $height);
                 imagewebp($newimage, $tsrc); // Save thumbnail as WebP
                 chmod("$tsrc", 0777);
             }
			
			db_query("update tbl_blog set blog_banner='".$sv_image_1."' where id = $page_id ");
		}
		set_session_msg("blog updated successfully.");	
				 $start = isset($_GET['start']) ? intval($_GET['start']) : 0;

	    header("Location: blog_list.php?start=$start");
	} else{	
	
	     ########### Uploading Image ################
		if($_FILES['sv_image']['name']!='')
		{
		  	    $sv_image = isset($sv_image) ? $sv_image : ''; // or use $sv_image = $sv_image ?? '';

			if(strlen($sv_image) && file_exists(UP_FILES_FS_PATH."/blog/thumb/".$sv_image)){
				@unlink(UP_FILES_FS_PATH."/blog/thumb/".$sv_image);
			}
			$sv_image_1 = $_FILES['sv_image']['name'];
			//$sv_image_1 = md5(uniqid(rand(), true)).'.'.file_ext($_FILES[sv_image]['name']);
				copy($_FILES['sv_image']['tmp_name'], UP_FILES_FS_PATH."/blog/thumb/".$sv_image_1) or die("Image is not uploaded");
				copy($_FILES['sv_image']['tmp_name'], UP_FILES_FS_PATH."/blog/original/".$sv_image_1) or die("Image is not uploaded");
			$n_width=225; // Fix the width of the thumb nail images
			$n_height=168; // Fix the height of the thumb nail imaage
			
			$tsrc=UP_FILES_FS_PATH."/blog/thumb/".$sv_image_1;
			$add=UP_FILES_FS_PATH."/blog/original/".$sv_image_1; // Path where thumb nail image will be stored
			
			//echo $tsrc;
			if (!($_FILES['sv_image']['type'] =="image/jpeg" OR $_FILES['sv_image']['type']=="image/jpeg" OR $_FILES['sv_image']['type']=="image/png" OR $_FILES['sv_image']['type']=="image/webp")){echo "Your uploaded file must be of JPG or GIF or PNG. Other file types are not allowed<BR>";
			exit;}
				///////// starting of JPG thumb nail creation//////////
			if($_FILES['sv_image']['type']=="image/jpeg" OR $_FILES['sv_image']['type']=="image/jpeg")
			{
				$im=ImageCreateFromJPEG($add);
				$width=ImageSx($im); // Original picture width is stored
				$height=ImageSy($im); // Original picture height is stored
				$newimage=imagecreatetruecolor($n_width,$n_height);
				imageCopyResized($newimage,$im,0,0,0,0,$n_width,$n_height,$width,$height);
				ImageJpeg($newimage,$tsrc);
				chmod("$tsrc",0777);
			}
			elseif($_FILES['sv_image']['type'] == "image/png"){
				$im=ImageCreateFromPNG($add);
				$width=ImageSx($im); // Original picture width is stored
				$height=ImageSy($im); // Original picture height is stored
				$newimage=imagecreatetruecolor($n_width,$n_height);
				imageCopyResized($newimage,$im,0,0,0,0,$n_width,$n_height,$width,$height);
				ImagePng($newimage,$tsrc);
				chmod("$tsrc",0777);
			}
			elseif ($_FILES['sv_image']['type'] == "image/webp") {
                  $im = imagecreatefromwebp($add); // Create image from WebP
                  $width = imagesx($im); // Original picture width is stored
                  $height = imagesy($im); // Original picture height is stored
                  $newimage = imagecreatetruecolor($n_width, $n_height);
                  imagecopyresized($newimage, $im, 0, 0, 0, 0, $n_width, $n_height, $width, $height);
                  imagewebp($newimage, $tsrc); // Save thumbnail as WebP
                  chmod("$tsrc", 0777);
                }
			
		}
	$heading=$_POST['heading'];
	$post_writer=$_POST['post_writer'];
	$cat_name=$blogTagIm ?? '';
	$status=$_POST['status'];
	$title=$_POST['title'];
	$description=$_POST['description'];
	$keyword=$_POST['keyword'];
	$blog_banner=$sv_image_1 ?? '';
	$content=$_POST['content'];
	//$conclusion=$_POST['conclusion'];
	$alt=$_POST['alt'];
	$tag1=$_POST['tag1'];
	$tag2=$_POST['tag2'];
	$tag3=$_POST['tag3'];
	$tag4=$_POST['tag4'];
	$tag5=$_POST['tag5'];
$blogTagIm = implode(",", ($_POST['cat_name'] ?? []));
		$sql = "insert into `tbl_blog` set heading='".addslashes($heading)."',content='".addslashes($content)."',alt='".addslashes($alt)."',tag1='".addslashes($tag1)."',tag2='".addslashes($tag2)."',tag3='".addslashes($tag3)."',tag4='".addslashes($tag4)."',tag5='".addslashes($tag5)."', title='".addslashes($title)."',description='".addslashes($description)."', keyword='".addslashes($keyword)."', status='".addslashes($status)."', post_writer='".addslashes($post_writer)."',cat_name='".$blogTagIm."', blog_banner='".$blog_banner."', post_date=now() ";
		db_query($sql);
		set_session_msg("New Blog added successfully.");
				 $start = isset($_GET['start']) ? intval($_GET['start']) : 0;

	header("Location: blog_list.php?start=$start");
	exit;
	}
}

if($page_id!='') {
	$sql = "select * from `tbl_blog` where id = '$page_id'";
	$result = db_query($sql);
	if ($line_raw = mysqli_fetch_array($result)) {
		
		@extract($line_raw);
	}
}
?>


<link href="styles.css" rel="stylesheet" type="text/css">
<? include("top.inc.php");?>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td id="pageHead"><div id="txtPageHead">
       Add/Edit - Blog</div></td>
  </tr>
</table>
<!--<script type="text/javascript" src="fckeditor/fckeditor.js"></script>-->
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
  <!--<link rel="stylesheet" type="text/css" href="multiSelect/example-styles.css">-->
<table width="80%" align="left">
		  	<tr><td>
		  	<form method="post" action="" enctype="multipart/form-data" name="form1" id="form1" onSubmit="return validateForm();">
		  	<input type="hidden" name="hfstateId" id="hfstateId" value="<?php echo $state_id; ?>">
        <table width="80%" align="center" border=0 cellpadding="0"  cellspacing="0" class="text">
    	<tr>
    	    <?php 		 $start = isset($_GET['start']) ? intval($_GET['start']) : 0;
 ?>
		<td  colspan="2"height="30"  align="right"><a href="blog_list.php?start=<?=$start?>" class="redcolor"><strong>Back To Blog List</strong></a></td>
		</tr>    
        <tr><td height="15"><div align="center"><span class="msg"><?=display_sess_msg();?></span></div><br /></td></tr>  
    
       
        <tr>
		  <td class="lables"><b>Heading</b></td>
          <td class="feildstxt"><input type="text" style="width:300px;" value="<?=stripslashes($heading ?? '')?>" name="heading" id="heading"  /></td>
        </tr>
          <tr><td>&nbsp;</td></tr>
	    <tr>
		  <td class="lables"><b>Writer</b></td>
          <td class="feildstxt"><input type="text" style="width:300px;" value="<?=stripslashes($post_writer ?? '')?>" name="post_writer" id="post_writer"  /></td>
        </tr>
        <tr><td>&nbsp;</td></tr>
		 <tr>
			<td class="lables"><b>Provide Categaries</b></td>
			<td class="feildstxt"> 
			   	 
				 <select name="cat_name[]" id="cat_name" style="width:300px;" multiple>	
				<?php 	
                $blogTagEx=explode(",", $cat_name);				
				$indusmenusql = db_query("select * from tbl_blogcatp where status='1'"); 
			    while($row1 =mysqli_fetch_array($indusmenusql)){?>				
				<option value="<?php echo ucwords($row1['catP_Name']); ?>"<?php echo in_array($row1['catP_Name'], $blogTagEx) ? 'selected' : ''; ?>><?php echo ucwords($row1['catP_Name']);?></option>
				<?php }?>		 
				</select>
				 
		 
				</td>
		</tr>


        <tr><td>&nbsp;</td></tr>
		<tr>
		  <td class="lables"><b>Status</b></td>
          <td class="feildstxt"><select name="status" id="status">
          <option value="1" <?php if(isset($status)=='1'){ echo 'selected="selected"'; } ?>>Active</option>
          <option value="0" <?php if(isset($status)=='0'){ echo 'selected="selected"'; } ?>>InActive</option>          
          </select></td>
        </tr>
        <tr><td>&nbsp;</td></tr>
       <tr>
		  <td class="lables" colspan="2"><hr/></td>
        </tr>
        <tr><td>&nbsp;</td></tr>
       <tr>
		  <td class="lables"><b>Title </b></td>
          <td class="feildstxt"><textarea style="width:650px; height:100px;"  name="title" id="title"><?=stripslashes($title ?? '')?></textarea></td>
        </tr>
		 <tr><td>&nbsp;</td></tr>
         <tr>
		  <td class="lables"><b>Descriptions</b></td>
          <td class="feildstxt"><textarea style="width:650px; height:100px;"  name="description" id="description"><?=stripslashes($description ?? '')?></textarea></td>
        </tr>
		<tr><td>&nbsp;</td></tr>
        <tr>
		  <td class="lables"><b>Keyword</b></td>
          <td class="feildstxt"><textarea style="width:650px; height:100px;" name="keyword" id="keyword"><?=stripslashes($keyword ?? '')?></textarea></td>
        </tr>
        <tr><td>&nbsp;</td></tr>  
		
        <tr>
		  <td class="lables"><b>Blog Content </b></td>
          <td class="feildstxt"><textarea style="width:300px;" name="content" id="content"><?=stripslashes($content ?? '')?></textarea></td>
          </td>
        </tr>
        
        <tr><td>&nbsp;</td></tr>
       <tr><td>&nbsp;</td></tr>
        <tr>
		  <td class="lables" colspan="2"><hr/></td>
        </tr>
         <tr>
		  <td class="lables"><b>Alt Tag</b></td>
          <td class="feildstxt"><input type="text" style="width:300px;" value="<?=stripslashes($alt ?? '')?>" name="alt" id="alt"  /></td>
        </tr>
          <tr><td>&nbsp;</td></tr>
        <tr><td>&nbsp;</td></tr>
         <tr>
		  <td class="lables"><b>Blog Image</b></td>
          <td class="feildstxt"><input type="file" name="sv_image" id="sv_image" />
          <span id="refreshIcon" style="display: none; cursor: pointer;font-size:17px" onclick="refreshFileInput()">
        🔄 
      </span>
          <span id="fileSizeError" style="color: red;font-size:12px;"></span>
          
          
          </td>
        </tr>

        <tr><td>&nbsp;</td></tr>
        <tr>
		  <td class="lables"><b>Current blog Image</b></td>
          <td class="feildstxt">
        <? if($page_id!='')
            {
                $sv_image = $blog_banner;
                if(strlen($sv_image) && file_exists(UP_FILES_FS_PATH."/blog/thumb/".$sv_image)){
                $imgsrc=SITE_WS_PATH."/uploaded_files/blog/thumb/".$sv_image;
                $size=getimagesize(UP_FILES_FS_PATH."/blog/thumb/".$sv_image);
				echo '<img src="'.$imgsrc.'" alt="No Image"  />';
                }
				else{  echo 'NO Images'; }
				
	if (!empty($sv_image2)) {
    $imagePath = UP_FILES_FS_PATH . "/blog/original/" . $sv_image2;

    // Check if file exists
    if (file_exists($imagePath)) {
        $imgsrcBig = SITE_WS_PATH . "/uploaded_files/blog/original/" . $sv_image2;
        $size = getimagesize($imagePath);

        // Ensure getimagesize() returns valid data
        if ($size !== false) {
            $mime = $size['mime'];

            // Choose the correct function based on image type
            switch ($mime) {
                case 'image/jpeg':
                    $img = imagecreatefromjpeg($imagePath);
                    break;
                case 'image/png':
                    $img = imagecreatefrompng($imagePath);
                    break;
                case 'image/webp':
                    $img = imagecreatefromwebp($imagePath);
                    break;
                default:
                    die("Error: Unsupported image type ($mime).");
            }

            // Check if image creation was successful
            if ($img) {
                $width = imagesx($img);
                $height = imagesy($img);
            } else {
                die("Error: Failed to create image from file.");
            }
        } else {
            die("Error: Invalid image file.");
        }
    } else {
        die("Error: Image file does not exist.");
    }
}
		
		}
        ?>
             
            </td>
        </tr>
        <tr><td>&nbsp;</td></tr>
         <tr>
		  <td class="lables"><b>Tag1</b></td>
          <td class="feildstxt"><input type="text" style="width:300px;" value="<?=stripslashes($tag1 ?? '')?>" name="tag1" id="tag1"  /></td>
        </tr>
          <tr><td>&nbsp;</td></tr>
           <tr>
		  <td class="lables"><b>Tag2</b></td>
          <td class="feildstxt"><input type="text" style="width:300px;" value="<?=stripslashes($tag2 ?? '')?>" name="tag2" id="tag2"  /></td>
        </tr>
          <tr><td>&nbsp;</td></tr>
           <tr>
		  <td class="lables"><b>Tag3</b></td>
          <td class="feildstxt"><input type="text" style="width:300px;" value="<?=stripslashes($tag3 ?? '')?>" name="tag3" id="tag3"  /></td>
        </tr>
          <tr><td>&nbsp;</td></tr>
           <tr>
		  <td class="lables"><b>Tag4</b></td>
          <td class="feildstxt"><input type="text" style="width:300px;" value="<?=stripslashes($tag4 ?? '')?>" name="tag4" id="tag4"  /></td>
        </tr>
          <tr><td>&nbsp;</td></tr>
           <tr>
		  <td class="lables"><b>Tag5</b></td>
          <td class="feildstxt"><input type="text" style="width:300px;" value="<?=stripslashes($alt ?? '')?>" name="tag5" id="tag5"  /></td>
        </tr>
          <tr><td>&nbsp;</td></tr>
        <tr>
        <td align="left" class="lables">&nbsp;</td>
        <td align="left" class="feildstxt"><input class="button" type="submit" name="submit" value="Save"></td>
        </tr>
        <tr><td height="25">&nbsp;</td></tr>
   </table>
    </form>
    </td>
</tr>
</table>  
<script>
    function getState()
	{
		$("#state_id").html('<option value="">&nbsp;&nbsp;&nbsp;Loading...&nbsp;&nbsp;&nbsp;</option>');
		$.post('get_state.php',{country_id:$("#country_id").val(),edit_state_id:$("#hfstateId").val()},function(data,status){
			if(status='success')
			{	
				$("#state_id").html(data);
			}
			else{
				alert("Something Going Error");	
			}
		});
	}
</script>  

<!--<script type="text/javascript" src="multiSelect/jquery-2.2.4.min.js"></script>
<script type="text/javascript" src="multiSelect/jquery.multi-select.js"></script>	-->
 <!--<script type="text/javascript">
    $(function(){
        $('#cat_name').multiSelect();
        $('#line-wrap-example').multiSelect({
            positionMenuWithin: $('.position-menu-within')
        });
        $('#categories').multiSelect({
            noneText: 'All categories',
            presets: [
                {
                    name: 'All categories',
                    options: []
                },
                {
                    name: 'My categories',
                    options: ['a', 'c']
                }
            ]
        })
    });
    </script>-->
<script type="text/javascript">
    CKEDITOR.replace('content');
</script>
<script>
  function validateFileSize() {
    const fileInput = document.getElementById("sv_image");
    const fileSizeError = document.getElementById("fileSizeError");
    const refreshIcon = document.getElementById("refreshIcon");

    if (fileInput.files.length > 0) {
      const fileSize = fileInput.files[0].size / 1024; // File size in KB

      if (fileSize > 100) {
        fileSizeError.textContent = "File size exceeds 100 KB. Please upload a smaller image.";
        refreshIcon.style.display = "inline"; // Show the refresh icon
        fileInput.focus(); // Focus on the file input
        return false; // Prevent form submission
      }
    }

    // Clear any previous error if file size is valid or no file is selected
    fileSizeError.textContent = "";
    refreshIcon.style.display = "none"; // Hide the refresh icon if no error
  }

  function refreshFileInput() {
    const fileInput = document.getElementById("sv_image");
    const fileSizeError = document.getElementById("fileSizeError");
    const refreshIcon = document.getElementById("refreshIcon");

    fileInput.value = ""; // Clear the file input
    fileSizeError.textContent = ""; // Clear the error message
    refreshIcon.style.display = "none"; // Hide the refresh icon
    fileInput.focus(); // Focus back to the file input if needed
  }

  function validateForm() {
    const fileInput = document.getElementById("sv_image");
    const fileSizeError = document.getElementById("fileSizeError");
    const refreshIcon = document.getElementById("refreshIcon");

    if (fileInput.files.length > 0) {
      const fileSize = fileInput.files[0].size / 1024; // File size in KB

      if (fileSize > 100) {
        fileSizeError.textContent = "File size exceeds 100 KB. Please upload a smaller image.";
        refreshIcon.style.display = "inline"; // Show the refresh icon
        fileInput.focus(); // Focus on the file input
        return false; // Prevent form submission
      }
    }

    // Clear any previous error if the file size is valid
    fileSizeError.textContent = "";
    refreshIcon.style.display = "none"; // Hide the refresh icon if no error
    return true; // Allow form submission if everything is valid
  }
</script>

<!--<script type="text/javascript">
	 var oFCKeditor=new FCKeditor('content','650','500')	;
	 oFCKeditor.BasePath="fckeditor/";	
	 oFCKeditor.ReplaceTextarea();
</script>  --> 
<? include("bottom.inc.php");?>