<?php
include '../db/db.php';
session_start();
$log=htmlspecialchars(trim($_SESSION['user']), ENT_QUOTES, 'UTF-8');
if (empty($log)) {
     
  $redirectUrl = "../../index.php";
  echo "<script type=\"text/javascript\">";
  echo "window.location.href = '$redirectUrl'";
  echo "</script>";
	 
}else{

  $sqlu="SELECT * FROM details_of_users WHERE user='$log' and val='1'";
  $resultu=mysqli_query($conn, $sqlu);
  $countu=mysqli_num_rows($resultu);
  if($countu==1){


    if(isset($_POST['description']))
      {
        $n_title = htmlspecialchars(trim($_POST['n_title']), ENT_QUOTES, 'UTF-8');
        $description = htmlspecialchars(trim($_POST['description']), ENT_QUOTES, 'UTF-8');

        $sql = "INSERT INTO newsletters VALUES (NULL, '$n_title', '$description')";
        $result = mysqli_query($conn, $sql);
        if ($result) {
          echo "Data inserted";
        }
      }

    if (array_key_exists('del_news', $_POST)) {

      $id=htmlspecialchars(trim($_POST['id']), ENT_QUOTES, 'UTF-8');

      $sql2=mysqli_query($conn,"DELETE FROM newsletters WHERE id = '$id'");

      if ($sql2) {
        echo "Data Deleted";
      }else{
        echo "Invalid";
      }

    }

    if (array_key_exists('load_news', $_POST)) {
      /*echo $_POST['uname'];*/
      $id = htmlspecialchars(trim($_POST['id']), ENT_QUOTES, 'UTF-8');

      $sql = mysqli_query($conn, "SELECT * FROM newsletters WHERE id=$id"); 
      $row = mysqli_fetch_assoc($sql);
      
      echo json_encode($row);
      //echo "In";
    }

    if(isset($_POST['up_description'])){

      $id = htmlspecialchars(trim($_POST['id_up']), ENT_QUOTES, 'UTF-8');
      $main_cat = htmlspecialchars(trim($_POST['up_n_title']), ENT_QUOTES, 'UTF-8');
      $description = htmlspecialchars(trim($_POST['up_description']), ENT_QUOTES, 'UTF-8');

      $result = mysqli_query($conn, "UPDATE newsletters SET title='$main_cat', descrip='$description' WHERE id='$id'");
      if ($result) {
        echo "Data inserted without image";
      }else{
        echo 'invalid without image';
      }
    }


  } else {
    $redirectUrl = "index.php";
    echo "<script type=\"text/javascript\">";
    echo "window.location.href = '$redirectUrl'";
    echo "</script>";

  }
}
?>	
