<?php
	session_start();
	include_once('../../db/saucerer.php');

	if(isset($_POST['submit'])){
		$id = mysqli_real_escape_string($mysqli, $_POST['id']);
		$code = mysqli_real_escape_string($mysqli, $_POST['code']);
		$title = mysqli_real_escape_string($mysqli, $_POST['title']);
		$cat = mysqli_real_escape_string($mysqli, $_POST['cat']);
		$topic = mysqli_real_escape_string($mysqli, $_POST['topic']);
		$author = mysqli_real_escape_string($mysqli, $_POST['author']);
		$paragraph1 = mysqli_real_escape_string($mysqli, $_POST['paragraph1']);
		$paragraph2 = mysqli_real_escape_string($mysqli, $_POST['paragraph2']);
		$paragraph3 = mysqli_real_escape_string($mysqli, $_POST['paragraph3']);
		$paragraph4 = mysqli_real_escape_string($mysqli, $_POST['paragraph4']);
		$paragraph5 = mysqli_real_escape_string($mysqli, $_POST['paragraph5']);
		$paragraph6 = mysqli_real_escape_string($mysqli, $_POST['paragraph6']);
		$web_link = mysqli_real_escape_string($mysqli, $_POST['web_link']);
		$summ1 = mysqli_real_escape_string($mysqli, $_POST['summ1']);
		$summ2 = mysqli_real_escape_string($mysqli, $_POST['summ2']);
		$summ3 = mysqli_real_escape_string($mysqli, $_POST['summ3']);

		if ($_FILES['image1']['name']=='') {
			$image1 = $_POST['image1'];
		} else {
		$ext1 = substr($_FILES['image1']['name'], strrpos($_FILES['image1']['name'], '.')+1);
			$image1 = $code.'_1.'.$ext1;
			if(is_file('../images/'. $image1))
				unlink('../images/'. $image1);
				move_uploaded_file($_FILES['image1']['tmp_name'],'../images/'. $image1);
		}

		if ($_FILES['image2']['name']=='') {
			$image2 = $_POST['image2'];
		} else {
		$ext2 = substr($_FILES['image2']['name'], strrpos($_FILES['image2']['name'], '.')+1);
			$image2 = $code.'_2.'.$ext2;
			if(is_file('../images/'. $image2))
				unlink('../images/'. $image2);
				move_uploaded_file($_FILES['image2']['tmp_name'],'../images/'. $image2);
		}

		if ($_FILES['image3']['name']=='') {
			$image3 = $_POST['image3'];
		} else {
		$ext3 = substr($_FILES['image3']['name'], strrpos($_FILES['image3']['name'], '.')+1);
			$image3 = $code.'_3.'.$ext3;
			if(is_file('../images/'. $image3))
				unlink('../images/'. $image3);
				move_uploaded_file($_FILES['image3']['tmp_name'],'../images/'. $image3);
		}
		
		$sql = "UPDATE blogs SET title = '$title', cat = '$cat', topic = '$topic', author = '$author', paragraph1 = '$paragraph1', paragraph2 = '$paragraph2', paragraph3 = '$paragraph3', paragraph4 = '$paragraph4', paragraph5 = '$paragraph5', paragraph6 = '$paragraph6', web_link = '$web_link', image1 = '$image1', image2 = '$image2', image3 = '$image3', summ1 = '$summ1', summ2 = '$summ2', summ3 = '$summ3' WHERE id = '$id'";

		//use for MySQLi OOP
		if(mysqli_query($mysqli, $sql)){
			$_SESSION['success'] = 'Blog updated successfully';
		}
		
		else{
			$_SESSION['error'] = 'Something went wrong while updating the blog!';
		}
	}

	header('location: ../#nav_'.$id.'');

?>