<?php
include('../includes/functions.php');
include('../includes/validations.php');
session_start();
make_connection();
global $uploadOk;
global $connection;
if(is_loggedin());
else
  redirect_to('index.php');
$user=get_user();
if(!$user)
 redirect_to('index.php');
$id_to_be_edit=$_GET['id'];
$book_row=get_book_by_id($id_to_be_edit);
if($book_row['owner_id']!=$user['regno'])
  redirect_to('editbookdetails.php');
if($user['block']==99)
  $userisdayscholar=true;
else
  $userisdayscholar=false;
$addbookerrors=array();//empty array
//if form submits
if(isset($_POST['addbooksubmit']))
{
  $name=$_POST['name'];
  $author=$_POST['author'];
  $course=$_POST['course'];
  $price=$_POST['price'];
  $health=$_POST['health'];
  
  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;
  }

  $addbookerrors=validate_addbook($name,$author,$price,$health);
  if(empty($addbookerrors))
  {
    $owner_id=$user['regno'];
    $name=sql_escape($name);
    $author=sql_escape($author);
    $course=sql_escape($course);
    $price=sql_escape($price);
    $health=sql_escape($health);
    $owner_id=sql_escape($owner_id);
    $uploadOk=1;
    $phele_photo=0;
    if(isset($_POST['prev-image-uploaded']) and $_POST['prev-image-uploaded']==1)
      $phele_photo=1;
    if((isset($_FILES['photoofbook']) && !empty($_FILES['photoofbook']) && isset($_FILES['photoofbook']["tmp_name"]) && !empty($_FILES['photoofbook']["tmp_name"])) or (isset($_POST['prev-image-uploaded']) and $_POST['prev-image-uploaded']==1))
    {
      $imageuploaded=1;
    }
    else
      $imageuploaded=0;

//upload file
    if($phele_photo==0 and empty($addbookerrors) && isset($_FILES['photoofbook']) && !empty($_FILES['photoofbook']) && !empty($_FILES["photoofbook"]["tmp_name"]))
    {
      $target_dir = "book_images/";
      
    $target_file = $target_dir . $id_to_be_edit.".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"] > 300000) {
      $addbookerrors['file']= "Sorry, your file is too large. Try <a href='http://compressnow.com/' target='_blank'>Compressing</a>.";
      $uploadOk = 0;
    }
// 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)
{
  $query="UPDATE book SET name='$name',author='$author',course='$course',price=$price,health='$health',owner_id='$owner_id',imageuploaded=$imageuploaded,dispmyname=$dispmyname,dispmyemail=$dispmyemail,dispmyphone=$dispmyphone,dispmyhostel=$dispmyhostel";
  $query.=" WHERE id=$id_to_be_edit;";

  $result=mysqli_query($connection,$query);
  if(!$result)
    $addbookerrors['addbookerror']="database update failed. Please try later.";
  else
    $addbookerrors['addbooksuccess']="successfully changed details.";
}
else
{
  if(!isset($addbookerrors['addbookerror']))
    $addbookerrors['addbookerror']="Some error occurred. Please try again later";
}
$book_row=get_book_by_id($id_to_be_edit);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <?php include('../includes/head.php');?>
  <title>Utopia- Edit this book</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;
    }
    #changepica{
      cursor: pointer;
    }
    #imageisuploadedspan{
      color: #9e9e9e !important;
    }
     .thodalight{
      color: #9e9e9e !important;
    }
  </style>
  
</head>
<body>
  <div class="body row">
    <?php
    global $navactive;
    $navactive="editbookdetails";
    include('../includes/nav.php');
    ?>

    <div class="main">
      <div class="container">
        <header>
          <h3 class="center">Edit this book</h3>
          <?php if(isset($addbookerrors) && isset($addbookerrors['addbookerror']))
          {
            ?>
            <div class="addbookerror">
              <h5 class="center redcolorerror"><?php echo $addbookerrors['addbookerror'];?></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 m6">
              <input required id="name" name="name" class="validate" type="text" value="<?php echo $book_row['name']; ?>">
              <label for="name">Book Name</label>
            </div>
            <div class="input-field col s12 m6">
              <input required id="author" name="author" class="validate" type="text" value="<?php echo $book_row['author']; ?>">
              <label for="author">author</label>
            </div>
          </div>
          <div class="row">
           <div class="input-field col s12 m6">
            <input required id="course" class="validate" name="course" placeholder="Course it is useful for?" value="<?php echo $book_row['course']; ?>" type="text">
            <label for="course">Course code</label>
          </div>
          <div class="input-field col s12 m6">
            <i class="fa fa-inr prefix blackcolor valign" aria-hidden="true"></i>
            <input required id="price" value="<?php echo $book_row['price']; ?>" name="price" class="validate valign" placeholder="price you want to sell it at" type="number">
            <label for="price">price</label>
          </div>
        </div>
        <input type="number" class="prev-image-uploaded hide" value="<?php if($book_row['imageuploaded']) echo '1';?>" name="prev-image-uploaded">
        <div class="row<?php  if($book_row['imageuploaded']==1) echo ' hide';?>" id="bookphotorow">
          <span>upload a photo of the book(<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" value="imad.png">
            </div>
            <div class="file-path-wrapper">
              <input class="file-path validate" type="text">
            </div>
          </div>
          <span class="addbookerror">
            <?php 
            if(isset($_POST['addbooksubmit']) and !$uploadOk)
            {
              echo "Please give correct file.";
            }
            ?>
          </span>
        </div>
        <?php
        if($book_row['imageuploaded']==1)
        {
          ?>
          <span class="imageisuploaded" id="imageisuploadedspan">image is uploaded. Click <a id="changepica">here</a> to change it.</span>    
          <?php 
        }
        ?>
        <div class="row">
        <div class="input-field col s12"><!-- 
          <i class="material-icons prefix">mode_edit</i> -->
          <textarea required name="health" id="health" length="200" class="materialize-textarea"></textarea>
          <label for="health">Describe the condition of your book..</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 no.</label>
        </div>
        <?php
        if(!($userisdayscholar))
        {
          ?>
          <div class="row">
            <input type="checkbox" name="dispmyhostel" class="" id="dispmyhostel"/>
            <label for="dispmyhostel">display my Hostel information</label>
          </div>
          <?php
        }
        ?>

        <div >
          <span id="phoneerror" class="addbookerror"><?php if(isset($addbookerror['phone']) &&!empty($addbookerror['phone'])) echo $addbookerror['phone'];?></span>
        </div>
      </div>
        <a href="editbookdetails.php"><button class="btn waves-effect waves-light col s12 m4 left">Go back
      </button></a>
      <button class="btn waves-effect waves-light col s12 m4 right" onclick="return validate_addbook();" type="submit" name="addbooksubmit">Save changes
        <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');
    var dispmyhostel=document.getElementById('dispmyhostel');
    <?php
    if($book_row['dispmyname']==1)
      echo "dispmyname.checked=true;";
    if($book_row['dispmyemail']==1)
      echo "dispmyemail.checked=true;";
    if($book_row['dispmyphone']==1)
      echo "dispmyphone.checked=true;";
    if($book_row['dispmyhostel']==1)
      echo "dispmyhostel.checked=true;";
    ?>
    <?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;
  }
</script>
<script type="text/javascript">
  $("#health").val("<?php echo $book_row['health'];?>");

  $(document).ready(function() {
    Materialize.updateTextFields();
  });
  $("#changepica").click(function(){
    $("#imageisuploadedspan").addClass("hide");
    $("#bookphotorow").removeClass("hide");
    $(".prev-image-uploaded").val("0");
  })
</script>
</body>
</html>