<?php
include('../includes/functions.php');
include('../includes/validations.php');
global $uploadOk;
global $booksizeerror;
session_start();
make_connection();
global $connection;
if(is_loggedin());
else
  redirect_to('index.php');
$user=get_user();
if(!$user)
 redirect_to('index.php');

$addbookerrors=array();//empty array
//if form submits
if(isset($_POST['addbooksubmit']))
{
  $name=$_POST['name'];
  $authority=$_POST['authority'];
  $health=$_POST['health'];
  $location=$_POST['location'];
  
  if(isset($_POST['dispmyname']) && $_POST['dispmyname'])
  {
    $dispmyname=1;
  }
  else
  {
    $dispmyname=0;
  }
  if(isset($_POST['dispmyemail']) && $_POST['dispmyemail'])
  {
    $dispmyemail=1;
  }
  else
  {
    $dispmyemail=0;
  }
  if(isset($_POST['dispmyphone']) && $_POST['dispmyphone'])
  {
    $dispmyphone=1;
  }
  else
  {
    $dispmyphone=0;
  }
  if(isset($_POST['dispmyhostel']) && $_POST['dispmyhostel'])
  {
    $dispmyhostel=1;
  }
  else
  {
    $dispmyhostel=0;
  }
  if($userisdayscholar)
  {
    $dispmyhostel=1;
  }
  if(true)
  {
    $owner_id=$user['regno'];
    $name=sql_escape($name);
    $authority=sql_escape($authority);
    $health=sql_escape($health);
    $owner_id=sql_escape($owner_id);
    $uploadOk=1;
    if(isset($_FILES['photoofbook']) && !empty($_FILES['photoofbook']) && isset($_FILES['photoofbook']["tmp_name"]) && !empty($_FILES['photoofbook']["tmp_name"]))
    {
      $imageuploaded=1;
    }
    else
      $imageuploaded=0;
    $query="INSERT INTO grievance(name,authority,health,owner_id,location,imageuploaded,dispmyname,dispmyemail,dispmyphone,dispmyhostel)";
    $query.=" values('$name','$authority','$health','$owner_id','$location',$imageuploaded,$dispmyname,$dispmyemail,$dispmyphone,$dispmyhostel);";
    $result=mysqli_query($connection,$query);
 // echo $query;
    if(!$result)
      $addbookerrors['addbookerror']="database update failed. Please try later.";
    else
      $book_id=mysqli_insert_id($connection);

//upload file
    if($result && empty($addbookerrors) && isset($_FILES['photoofbook']) && !empty($_FILES['photoofbook']) && !empty($_FILES["photoofbook"]["tmp_name"]))
    {
      $target_dir = "grievances_images/";

    $target_file = $target_dir . $book_id.".png";//new name of the file
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
    $check = getimagesize($_FILES["photoofbook"]["tmp_name"]);
    if($check !== false) {
      //echo "File is an image - " . $check["mime"] . ".";
      $uploadOk = 1;
    } else {
      $addbookerrors['file']= "File is not an image.";
      $uploadOk = 0;
    }
// Check file size
    if ($_FILES["photoofbook"]["size"] > 1000000) {
      $addbookerrors['file']= "Sorry, your file is too large. Try <a href='http://compressnow.com/' target='_blank'>Compressing</a>.";
      $uploadOk = 0;
      $booksizeerror="Sorry, your file is too large. Try <a href='http://compressnow.com/' target='_blank'>Compressing</a>.";
    }
// Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
      && $imageFileType != "gif" ) {
      $addbookerrors['file']= "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
  }
// Check if $uploadOk is set to 0 by an error
  if ($uploadOk == 0) {
    if(!isset($addbookerrors['file']))
      $addbookerrors['file']= "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
  } else {
    if (move_uploaded_file($_FILES["photoofbook"]["tmp_name"], $target_file)) {
      $to_echo_to_check= "The file ". basename( $_FILES["photoofbook"]["name"]). " has been uploaded.";
    } else {
      if(!isset($addbookerrors['file']))
        $addbookerrors['file']= "Sorry, there was an error uploading your file.";
    }
  }
}
}

if(empty($addbookerrors) and $uploadOk==1)
{
    //success. now insert into database
  $addbookerrors['addbooksuccess']="successfully added a new Grievance";
}
else
{
  if(!isset($addbookerrors['addbookerror']))
    $addbookerrors['addbookerror']="Some error occurred. Please try again later";
  if(isset($book_id))
  {
    $query="DELETE FROM book WHERE id=$book_id";
    $result=mysqli_query($connection,$query);
  }
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <?php include('../includes/head.php');?>
  <title>Utopia- Add new Grievance</title>
  <link rel="stylesheet" type="text/css" href="font-awesome/css/font-awesome.min.css">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link rel="stylesheet" type="text/css" href="materialize/css/materialize.css">
  <link rel="stylesheet" type="text/css" href="css/home.css">
  <link rel="stylesheet" type="text/css" href="css/searchbook.css">
  <style>
  .blackcolor{
    color:#000 !important;
    font-size: 20px !important;
  }
  *{

  }
  html,body{
    overflow-x:hidden;
  }
  .dispmydiv label{
    vertical-align: middle;
    display: inline-block;
  }
  .dispmydiv input{
    vertical-align: middle;

  }
  .addbookerror,.redcolorerror{
    color: red;
  }
  .thodalight{
    color: #9e9e9e !important;
  }

</style>

</head>
<body>
  <div class="body row">
    <?php
    global $navactive;
    $navactive="postgrievances";
    include('../includes/nav-griev.php');
    ?>

    <div class="main">
      <div class="container">
        <header>
          <h3 class="center">Add a new Grievance</h3>
          <?php 
          if(isset($addbookerrors) && isset($addbookerrors['addbookerror']))
          {
            ?>
            <div class="addbookerror">
              <h5 class="center redcolorerror"><?php echo $addbookerrors['addbookerror'];?></h5>
            </div>
            <?php
          }
          elseif(isset($_POST['addbooksubmit']) and !$uploadOk){
            ?>
            <div class="addbookerror">
              <h5 class="center redcolorerror">Error:File is too large(max 1MB)<h5>
              </div>
              <?php
            }
            elseif(isset($_POST['addbooksubmit']) and !$uploadOk){
              ?>
              <div class="addbookerror">
                <h5 class="center redcolorerror">Some error occurred.</h5>
              </div>
              <?php
            }
            ?>
            <?php if(isset($addbookerrors) && isset($addbookerrors['addbooksuccess']))
            {
              ?>
              <div class="addbooksuccess">
                <h5 class="center greencolor"><?php echo $addbookerrors['addbooksuccess'];?></h5>
              </div>
              <?php
            }
            ?>
            <br>
          </header>
          <div class="addnewbook">
            <form action="#" method="POST" enctype="multipart/form-data">
              <div class="row">
               <div class="input-field col s12 m12">
                <select name="authority" required>
                  <option value="0" disabled selected>Choose your option</option>
                  <option value="Governor">Governor</option>
                  <option value="Chief Minister">Chief Minister</option>
                  <option value="Mayor">Mayor</option>
                  <option value="Municipal Corporation">Municipal Corporation</option>
                  <option value="Others">Others</option>
                </select>
                <label>Select Authority</label>
              </div>
            </div>
            <div class="row">
             <div class="input-field col s12 m12">
              <input required id="name" name="name" class="validate" type="text">
              <label for="name">Heading</label>
            </div>
          </div>
          <div class="row">
           <div class="input-field col s12 m12">
            <input required id="location" name="location" class="validate" type="text">
            <label for="location">Location</label>
          </div>
        </div>
        <div class="row">
          <span>upload a photo of the issue(<i>optional</i>) <span class="thodalight">Max allowed size is 1MB</span></span>
          <div class="file-field input-field">
            <div class="btn">
              <span>File</span>
              <input type="file" name="photoofbook" id="photoofbook">
            </div>
            <div class="file-path-wrapper">
              <input class="file-path validate" type="text">
            </div>
          </div>
          <span class="addbookerror">
            <?php 
            if(isset($booksizeerror))
              echo $booksizeerror;
            else if(isset($_POST['addbooksubmit']) and !$uploadOk)
            {
              echo "Please give correct file.(Max size 1MB.)";
            }
            ?>
          </span>
        </div>
        <div class="row">
        <div class="input-field col s12"><!-- 
          <i class="material-icons prefix">mode_edit</i> -->
          <textarea required name="health" id="health" length="300" placeholder="What is your issue? What caused it? What actions by authorities are you expecting?" class="materialize-textarea"></textarea>
          <label for="health">Describe the issue in detail..</label>
        </div>
      </div>
      <div class="row">
        <h5>Select your contact information to be displayed:</h5>
      </div>
      <div class="dispmydiv">
        <div class="row">

          <input type="checkbox" onclick="dispallclicked()" class="filled-in valign" name="dispall" id="dispall"/>
          <label for="dispall" class="valign"><b>display all</b></label>

        </div>
        <div class="row">
          <input type="checkbox" name="dispmyname" id="dispmyname"/>
          <label for="dispmyname" class="valign">display my Name</label>
        </div>
        <div class="row">
          <input type="checkbox" name="dispmyemail" class="" id="dispmyemail"/>
          <label for="dispmyemail">display my Email</label>
        </div>
        <div class="row">
          <input type="checkbox" name="dispmyphone" class="" id="dispmyphone"/>
          <label for="dispmyphone">display my Phone number</label>
        </div>
        <div class="row">
          <input type="checkbox" name="dispmyhostel" class="" id="dispmyhostel"/>
          <label for="dispmyhostel">display my Location</label>
        </div>


        <div >
          <span id="phoneerror" class="addbookerror"><?php if(isset($addbookerror['phone']) &&!empty($addbookerror['phone'])) echo $addbookerror['phone'];?></span>
        </div>
      </div>
      <button class="btn waves-effect waves-light col s12 m4 right" onclick="return validate_addbook();" type="submit" name="addbooksubmit">Add Grievance <i class="material-icons right">send</i>
      </button>
      <br>
      <br>
    </form>
  </div>
</div>
</div>
</div>
<script src="js/jquery.js"></script>
<script src="materialize/js/materialize.js"></script>
<script>
  $(".button-collapse").sideNav();
  $('.button-collapse').sideNav({
      menuWidth: 300, // Default is 240
      edge: 'left', // Choose the horizontal origin
      closeOnClick: false // Closes side-nav on <a> clicks, useful for Angular/Meteor
    }
    );
  </script>
  <script>
    var dispall=document.getElementById('dispall');
    var dispmyname=document.getElementById('dispmyname');
    var dispmyemail=document.getElementById('dispmyemail');
    var dispmyphone=document.getElementById('dispmyphone');
    dispall.checked=true;
    dispallclicked();
    <?php
    if(!($userisdayscholar))
    {
      ?>
      var dispmyhostel=document.getElementById('dispmyhostel');
      <?php
    }
    ?>
    function dispallclicked()
    {
  if(dispall.checked)//it is now checked
  {
    dispmyname.checked=true;
    dispmyemail.checked=true;
    dispmyphone.checked=true;
    <?php
    if(!($userisdayscholar))
    {
      ?>
      document.getElementById('dispmyhostel').checked=true;
      <?php
    }
    ?>
  }
  else
  {
    dispmyname.checked=false;
    dispmyemail.checked=false;
    dispmyphone.checked=false;
    <?php
    if(!($userisdayscholar))
    {
      ?>
      document.getElementById('dispmyhostel').checked=false;
      <?php
    }
    ?>
  }
}
</script>
<script>
  function empty(fil){
    if(fil==''||fil=='0')
      return true;
    return false;
  }
  function validate_addbook()
  {
    var name_val=$("#name").val();
    var author_val=$("#author").val();
    var course_val=$("#course").val();
    var price_val=$("#price").val();
    var health_val=$("#health").val();
    if(empty(name_val))
    {
      document.getElementById('phoneerror').innerHTML="Name of the book Can't be blank.";
      return false;
    }
    if(empty(author_val))
    {
      document.getElementById('phoneerror').innerHTML="Author of the book Can't be blank.";
      return false;
    }
    if(empty(course_val))
    {
      document.getElementById('phoneerror').innerHTML="Course of the book Can't be blank.";
      return false;
    }
    if(empty(health_val))
    {
      document.getElementById('phoneerror').innerHTML="Description of the book Can't be blank.";
      return false;
    }
    document.getElementById('phoneerror').innerHTML="";
    return true;
  }
  $(document).ready(function() {
    $('select').material_select();
  });
</script>
<?php
if(isset($health) && empty($addbookerrors))
{
  ?>
  <script>
    health.value="<?php echo $health;?>";
    $('#health').trigger('autoresize');
  </script>
  <?php
}
?>
</body>
</html>