<?php
error_reporting(0);
include("/var/www/bloomnwa/login/logincheck.php");
include('Header.php');
include("DbCon.php");
 ?>
 <?php
// error_reporting(0);
session_start();

$access_level = json_decode($_COOKIE["login_user_access_level"]);
if (in_array("IUT-ADMIN", $access_level) || in_array("IUT-USER", $access_level))
  {
  //echo "Match found";
  }
else
  {
  echo '    
    <span class="text-danger text-center">

        <div class="alert alert-danger py-0 mt-2 mb-0" role="alert">
        <svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" fill="currentColor" class="bi bi-person-x-fill" viewBox="0 0 16 16">
        <path fill-rule="evenodd" d="M1 14s-1 0-1-1 1-4 6-4 6 3 6 4-1 1-1 1H1zm5-6a3 3 0 1 0 0-6 3 3 0 0 0 0 6zm6.146-2.854a.5.5 0 0 1 .708 0L14 6.293l1.146-1.147a.5.5 0 0 1 .708.708L14.707 7l1.147 1.146a.5.5 0 0 1-.708.708L14 7.707l-1.146 1.147a.5.5 0 0 1-.708-.708L13.293 7l-1.147-1.146a.5.5 0 0 1 0-.708z"/>
        </svg><br>      
        You are not authorized to access this resource.
        </div>

    </span>';
  // exit();
  }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upload Order Image</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>


</head>
<body>
<!-- start please wait overlay -->

<style>

    body{
  font-family: Arial, Sans;
  margin: 0;
} 

.wrapper{
  position: absolute;
  top: 50%;
  left: 50%;
  width: 300px;
  text-align:center;
  transform: translateX(-50%);
}

.spanner{
  position:absolute;
  top: 50%;
  left: 0;
  background: #2a2a2a55;
  width: 100%;
  display:block;
  text-align:center;
  height: 300px;
  color: #FFF;
  transform: translateY(-50%);
  z-index: 1000;
  visibility: hidden;
}

.overlay{
  position: fixed;
	width: 100%;
	height: 100%;
  background: rgba(0,0,0,0.5);
  visibility: hidden;
}

.loader,
.loader:before,
.loader:after {
  border-radius: 50%;
  width: 2.5em;
  height: 2.5em;
  -webkit-animation-fill-mode: both;
  animation-fill-mode: both;
  -webkit-animation: load7 1.8s infinite ease-in-out;
  animation: load7 1.8s infinite ease-in-out;
}
.loader {
  color: #ffffff;
  font-size: 10px;
  margin: 80px auto;
  position: relative;
  text-indent: -9999em;
  -webkit-transform: translateZ(0);
  -ms-transform: translateZ(0);
  transform: translateZ(0);
  -webkit-animation-delay: -0.16s;
  animation-delay: -0.16s;
}
.loader:before,
.loader:after {
  content: '';
  position: absolute;
  top: 0;
}
.loader:before {
  left: -3.5em;
  -webkit-animation-delay: -0.32s;
  animation-delay: -0.32s;
}
.loader:after {
  left: 3.5em;
}
@-webkit-keyframes load7 {
  0%,
  80%,
  100% {
    box-shadow: 0 2.5em 0 -1.3em;
  }
  40% {
    box-shadow: 0 2.5em 0 0;
  }
}
@keyframes load7 {
  0%,
  80%,
  100% {
    box-shadow: 0 2.5em 0 -1.3em;
  }
  40% {
    box-shadow: 0 2.5em 0 0;
  }
}

.show{
  visibility: visible;
}

.spanner, .overlay{
	opacity: 0;
	-webkit-transition: all 0.3s;
	-moz-transition: all 0.3s;
	transition: all 0.3s;
}

.spanner.show, .overlay.show {
	opacity: 1
}
</style>
<!-- end please wait overlay -->


<!-- start please wait overlay -->

<div class="wrapper">
<!--<input type="submit"/>-->
</div>
<div class="overlay"></div>
<div class="spanner">
  <div class="loader"></div>
  <p>Please wait.</p>
</div>

<!-- end please wait overlay -->



  
 
<form class = "border" action="UploadOrderImage.php" enctype="multipart/form-data" method="post" id="form">
<table class="table table-borderless" >

<tr>


<div class="alert alert-success my-0" role="alert">
<a href="main.php" class="alert-link text-decoration-none">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-arrow-left" viewBox="0 0 16 16">
  <path fill-rule="evenodd" d="M15 8a.5.5 0 0 0-.5-.5H2.707l3.147-3.146a.5.5 0 1 0-.708-.708l-4 4a.5.5 0 0 0 0 .708l4 4a.5.5 0 0 0 .708-.708L2.707 8.5H14.5A.5.5 0 0 0 15 8z"/>
</svg></a>&emsp;
            <a href="" class="alert-link text-decoration-none"> Upload Order Image</a>
</div>


</tr>
<?php
                         
                        $Qry = "SELECT * FROM `default_order_number`";
                        $Run = mysqli_query($con,$Qry);
                        if(mysqli_num_rows($Run)<1)
                        {
                            ?>
                            <td><label class="form-label">Order Number <span></span></label><input type="number" id="order_number" maxlength="9" pattern="[0-9]{9}" title="Enter 9 numeric character" class="form-control"name="DefaultOrderNumber" placeholder="No Default Number Found" required></td>
                            <?php
                        }
                        else
                        { 
                            
                        $Data = mysqli_fetch_array($Run);
                           
                                ?>
                               <td><label class="form-label">Order Number <span style="display:none"id="order_number_error" class="text-danger"> Enter 9 character</span></label><input type="number" id="order_number" maxlength="9" pattern="[0-9]{9}" title="Enter 9 numeric character" class="form-control"name="DefaultOrderNumber" value="<?php echo $Data["DefaultOrderNumber"];?>" required></td>
                                <?php
                        
                        }
                    ?>
<tr>
    <!-- <th>Order ID</th> -->
    
</tr>
<tr>
<!-- <th class="form-label">Designer</th> -->
    <td>    
            <label class="form-label">Designer</label>
            <select name="Designer" id="" class="form-control" required>
            <option hidden disabled selected value> -- Select Designer-- </option>
                    <?php 
                         //include("DbCon.php");
                        $Qry = "SELECT * FROM `designer` ORDER BY `DesignerName` ASC"; 
                        $Run = mysqli_query($con,$Qry);
                        if(mysqli_num_rows($Run)<1)
                        {
                            echo" No Record";
                        }
                        else
                        { 
                            //echo $Data['RSOID'];
                            while ($Data = mysqli_fetch_array($Run)) 
                            {
                                //echo $Data["CompanyName"];
                                ?>
                                <option value="<?php echo $Data['DesignerName'];?>"><?php echo $Data['DesignerName'];?></option>
                                <?php
                            }
                        }
                    ?>
            </select>
            
        
    </td>
</tr>
<?php
        $useragent=$_SERVER['HTTP_USER_AGENT'];

        if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($useragent,0,4)))
        {
          ?>
          <tr>
              <td><ul class="nav nav-tabs">
                  <li class="nav-item">
                      <a class="nav-link text-success" id="CaptureImage" onclick="show_hide_image_source('capture_image_row', 'upload_image_row', 'CaptureImage', 'UploadImage')">Captures</a>
                  </li>
                  <li class="nav-item">
                      <a class="nav-link text-success" id="UploadImage" onclick="show_hide_image_source('upload_image_row', 'capture_image_row', 'UploadImage', 'CaptureImage')">Upload</a>
                  </li>    
              </ul>
              </td>
          </tr>

            <tr id="capture_image_row"><td><label class="form-label">Capture Image</label><input type="file" id="capture_image"name="CaptureImage" style="buttonText:Open;" class="form-control" onchange="loadFile(event, 'CaptureImage')" accept="image/*" capture required></td></tr>
            <tr id="upload_image_row" style="display:none"><td><label class="form-label">Upload Image</label><input type="file" id="upload_image" name="UploadImage" class="form-control"onchange="loadFile(event, 'UploadImage')" accept="image/*" data-icon="false" required></td></tr>  
            <?php       
        }
        else
        {
            ?>
                <tr><td><label class="form-label">Upload Image</label><input type="file" id="upload_image" name="UploadImage" class="form-control"onchange="loadFile(event, 'UploadImage')" accept="image/*" data-icon="false" required></td></tr>     
            <?php
        }
    ?>
    
        <tr>
            <td>
            <img id="output"/ style="display:none;"width="200px" height="250px" class="position-relative top-0 start-50 translate-middle-x">
            </td>
        </tr>
    <input type="hidden" name="ImageSource" id="image_source">

 <tr>
    <td colspan="2" align="center"><input type="submit" style="display:block" class="btn btn-success" name="submit" id="submit" onclick="show_loader()" value="Submit" required ></td>
</tr>
 <tr>
    <td class="text-center"  id="loader" style="display: none">
        <div class="spinner-border text-success" role="status">
        
    </div>
    <br>
    <span class="sr-only">Please wait...</span>
    </td>
</tr>
</table>


</form>
<?php
if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($useragent,0,4)))
{
    
      echo '<script>
        let params = (new URL(document.location)).searchParams;
        let name = params.get("ImageSource");
        document.getElementById(name).classList.add("active");
      </script>';
   
}
?>

<script>
var $order_nymber = $('#order_number')
$order_nymber.keyup(function() {
  
    var max = 9;
    $('#order_number_error').css("display","none");
    if ($order_nymber.val().length > max) {
        $order_nymber.val($order_nymber.val().substr(0, max));
    }
});

function show_hide_image_source(show, hide, active, deactive)
{
  document.getElementById(show).style.display = "block";
  document.getElementById(hide).style.display = "none";
  document.getElementById(active).classList.add("active");
  document.getElementById(deactive).classList.remove("active");
}

// start please wait overlay
$("form").submit(function(e){
  var $order_number = $('#order_number');
  var limit = 9;
 
    if ($order_nymber.val().length != limit) 
    {
      $('#order_number_error').css("display","inline");
      e.preventDefault();
    }
    else
    {
      $("div.spanner").addClass("show");
      $("div.overlay").addClass("show");
    } 
});


$("#submit").click(function(){
  var $order_number = $('#order_number');
  var limit = 9;
    if ($order_nymber.val().length != limit) 
    {
      $('#order_number_error').css("display","inline");      
    }
});


  var loadFile = function(event, ImageSource) {
    // alert(ImageSource);
    document.getElementById("image_source").value = ImageSource;

    document.getElementById("upload_image").required = false;
    document.getElementById("capture_image").required = false;

    var output = document.getElementById('output');
    // document.getElementById("city").required = false;
    //output.style.display = "block";
    output.src = URL.createObjectURL(event.target.files[0]);
    output.onload = function() {
      URL.revokeObjectURL(output.src) // free memory
    }
    //process();
  };
</script>


<script>

let camera_button = document.querySelector("#start-camera");
let video = document.querySelector("#video");
let click_button = document.querySelector("#click-photo");
let canvas = document.querySelector("#canvas");

camera_button.addEventListener('click', async function() {
   	let stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: false });
	video.srcObject = stream;
});

click_button.addEventListener('click', function() {
   	canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
   	let image_data_url = canvas.toDataURL('image/jpeg');

   	// data url of the image
   	console.log(image_data_url);
});

</script>

</body>
</html>
<?php
if(isset($_POST["submit"]))
{
    $DefaultOrderNumber= $_POST["DefaultOrderNumber"];
    $Designer= $_POST["Designer"];
    $ImageSource = $_POST["ImageSource"];
    if(strlen($DefaultOrderNumber) !=9 )
    {
        ?>
        <script>
            alert("Please enter 9 digit number")
        </script>
        <?php
        exit();
    }
    $UserID= 1;
        $PictureName=$_FILES[$ImageSource]["name"];
        $PicturetemporaryName=$_FILES[$ImageSource]["tmp_name"];        
        $location = "OrderImage/".$UserID."/".$DefaultOrderNumber;

        
        $exif = exif_read_data($PicturetemporaryName);

            if(!is_dir($location))
            {
              mkdir($location, 0755);

              $maxDim = 480;
        
              list($width, $height, $type, $attr) = getimagesize( $PicturetemporaryName );
              if ( $width > $maxDim || $height > $maxDim ) 
              {
                  $target_filename = "OrderImage/".$UserID."/".$DefaultOrderNumber."/".$PictureName;
                  $ratio = $width/$height;
                  if( $ratio > 1) {
                      $new_width = $maxDim;
                      $new_height = $maxDim/$ratio;
                  } else {
                      $new_width = $maxDim*$ratio;
                      $new_height = $maxDim;
                  }
                 

                  if (!empty($exif['Orientation']))
                  {
                    echo "Rotate hai";
                    // echo "<br> new width".$new_width;
                    $src = imagecreatefromstring( file_get_contents( $PicturetemporaryName ) );
                    //$src = imagecreatefromjpg($PicturetemporaryName);
                    
                    $dst = imagecreatetruecolor( $new_width, $new_height );
                    imagecopyresampled( $dst, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
                    //$src = imagecreatefromjpeg($filePath); // provided that the image is jpeg. Use relevant function otherwise
                    //echo "here : <br>";
                    //print_r($exif['Orientation']);
                    switch ($exif['Orientation']) 
                    {
                        case 3:
                          echo "3";
                        $dst = imagerotate($dst, 180, 0);
                        break;
                        case 6:
                          //echo "6";
                        $dst = imagerotate($dst, -90, 0);

                        break;
                        case 8:
                          echo "8";
                        $dst = imagerotate($dst, 90, 0);
                        break;
                        default:
                        // $dst = $src;
                    } 
                   
                  }
                  else
                  {
                    echo "Rotate nhi hai";

                    // $src = imagecreatefrompng($PicturetemporaryName);
                    $src = imagecreatefromstring( file_get_contents( $PicturetemporaryName ) );

                    $dst = imagecreatetruecolor( $new_width, $new_height );
                    imagecopyresampled( $dst, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height );

                    //echo "orient nhi hai";
                  }

                  imagedestroy( $src );
                  imagejpeg( $dst, $target_filename ); // adjust format as needed
                  imagedestroy( $dst );
              }

              // $compress_image = "OrderImage/".$UserID."/".$DefaultOrderNumber."/".$PictureName;
              // imagejpeg($img,$compress_image,10);     
            }
            //echo "Processing done";
          
       
     # create directory if not exists in OrderImage/userID directory

        //move_uploaded_file($PicturetemporaryName,"OrderImage/".$UserID."/".$DefaultOrderNumber."/".$PictureName);
        // echo $DefaultOrderNumber.','.$Designer.','.$UserID.','.$PictureName;
        $Qry2="INSERT INTO `orders`(`OrderNumber`, `DesignerName`, `UserID`, `Image`) VALUES ('$DefaultOrderNumber','$Designer','$UserID','$PictureName')";
        $Run2 = mysqli_query($con,$Qry2);
        if($Run2==true)
        {
            ?>
            <script>
                //alert("Image Uploaded successfully");
                if ( window.history.replaceState ) 
                {
                //window.history.replaceState( null, null, window.location.href );
                }
            </script>
            <?php
            unset($_POST["submit"]);
   
        }
        else
        {
            ?>
            <script>
        alert("Image Uploaded failed");
            </script>
            <?php
        }
    
}
    unset($_POST["submit"]);   
?>


