<?php
    session_start();
   
    include "../../db.php";
    date_default_timezone_set('Asia/Kolkata');
    $currentTime = date('M j, Y g:i a');
   
?>
<!DOCTYPE html>
<html lang="en">
<head>
 <?php include "includes/meta.php"; ?>             
    <?php include "includes/css.php"; ?>
    <link href="css/all.min.css" rel="stylesheet" type="text/css">
    <link href="css/alltable.css" rel="stylesheet"> 
    <link rel="stylesheet" href="vendor/croppie/croppie.css" /> 
    </head>


<body>
      <?php include "includes/header2.php"; ?>
<div class="container">
            <div class="row mx-0 just ify-content-center">
                <div class="col-12 col-sm-12 col-md-12">
                        <div class="card-body">

                        
                            <h1 class="h3 mb-2 text-gray-800 text-center" style="margin-top: 90px">Wallpaper Slider</h1>
                            <hr>
                        <?php
                        if ( isset($_GET["edit_id"]) ) 
                        {    
                            $edit_sql = "SELECT * FROM slider WHERE sid = '$_GET[edit_id]'";
                            $edit_run = mysqli_query($con, $edit_sql);
                            $edit_row = mysqli_fetch_assoc($edit_run);
                        ?>
                         
                            <form method='post' action='' enctype='multipart/form-data'>
                                <font color="black">Title</font>
                                <input type="text" class="form-control mb-2" name="stitle" value="<?php echo $edit_row['stitle']; ?>">
                                
                                <font color="black">Upload Image (Image Size: 1900 x 750 pixels)
                                 <?php
                                  if (!empty($edit_row['slgimage']))
                                    {
                                    echo " <a href='$edit_row[slgimage]' title='Click to open' target='_blank'> (<b>Already Uploaded - </b> Click To View</a> )
                                    ";
                                    }
                                 ?>
                                </font>
                                <input type='file' name='file' class="form-control"><br>
                                

                                <input type='submit' value='Notice Update' class="btn btn-primary" name='s_update'> 
                                <a href="sliderfile.php" class="btn btn-warning my-4"> Cancel </a>   

                            </form>
                        <?php 
                        }
                        else
                        {  ?>
                          
                            <form method='post' action='' enctype='multipart/form-data'>
                                <font color="black">Title</font>
                                <input type="text" class="form-control mb-2"  placeholder="Slider Title" name="stitle">
                                
                                <font color="black">Upload Image (Image Size: 1900 x 750 pixels)</font>
                                <input type='file' name='file' class="form-control" required><br>
                                

                                <input type='submit' value='Submit' class="btn btn-primary" name='s_submit'>    

                            </form>

                        <?php

                        }

                        ?> 


<BR><BR>


                            <div class="row m-0">
                             

                                <div class="col-md-12 p-0">
                                    <div class="table-responsive">
                                        <table class="table table-hover table-bordered table-sm" id="thisismytable">
                                            <thead>
                                                <tr>
                                                    <th>No.</th>
                                                    <th>Title</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php
                                                    $sql = "SELECT * FROM slider WHERE sby = '$_SESSION[uid]' ORDER BY spos ASC";
                                                    $run = mysqli_query($con, $sql);

                                                    $c = 1;
                                                    while ( $rows = mysqli_fetch_assoc($run) ) {

                                                         $trimmedTitle = mb_strimwidth($rows['stitle'], 0, 20, "...");                                                         echo "
                                                        <tr id='$rows[sid]'>
                                                            <td>
                                                            <p class='text-dark mb-0'><b>$c </b></p>
                                                            </td>
                                                            <td>
                                                            <p class='text-dark mb-0'><b>Title: </b>$trimmedTitle </p>
                                                               
                                                                <br>
                                                                <img src='$rows[slgimage]' height='50' data-toggle='modal' data-target='#show-img' class='showModal'>
                                                            </td>
                                                        ";
                                                        ?>
                                                            <td class='text-center align-middle'>
                                                                 <a href='sliderfile.php?edit_id=<?php echo $rows["sid"]; ?>&imgpath=<?php echo $rows["slgimage"]; ?>' class='m-2 btn btn-success btn-sm rounded-circle' title='Click to Edit'> <i class='fas fa-pencil-alt'></i> </a> 

                                                                <a href='sliderfile.php?del_id=<?php echo $rows["sid"]; ?>&imgpath=<?php echo $rows["slgimage"]; ?>' class='delete m-2 btn btn-danger btn-sm rounded-circle' title='Click to Delete'> <i class='fas fa-trash'></i> </a>
                                                            </td>
                                                        </tr>
                                                        <?php
                                                        $c++;
                                                    }
                                                ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>

            </div>
              <?php include "includes/ft.php"; ?>
               <?php include "includes/js.php"; ?>


    <script>
        $(document).ready(function(){
            $('#thisismytable').DataTable();

             var $sortable = $("#thisismytable > tbody");

            $sortable.sortable({
                stop: function ( event, ui ) {
                    var parameters = $sortable.sortable( "toArray" );
                    $.post("slider_position.php",{value:parameters},function(result){
                        console.log("Position Complete");
                    });
                }
            });          
        });
   </script>
  
</body>
</html>



<?php 

      if(isset($_POST['s_submit']))
       {
          $total_pages_sql = "SELECT COUNT(*) FROM slider WHERE sby = '$_SESSION[uid]'";
          $total_pages_result = mysqli_query($con,$total_pages_sql);
          $total_pages_rows = mysqli_fetch_array($total_pages_result)[0];

          if ($total_pages_rows <= 4) {
             
          
                        if (!empty($_FILES["file"]["name"]))
                        {
                                     #file name with a random number so that similar dont get replaced
                                         $fname = rand(1000,10000)."-".$_FILES["file"]["name"];
                             
                                    #temporary file name to store file
                                         $tname = $_FILES["file"]["tmp_name"];
                                       
                                    #upload directory path
                                        $uploads_dir = '../upload/slider';
                                    #TO move the uploaded file to specific location
                                        move_uploaded_file($tname, $uploads_dir.'/'.$fname);


                                        $fullname = $uploads_dir.'/'.$fname;



                           
                                 $sql = "INSERT INTO slider (stitle, slgimage, sby, screated) VALUES ('$_POST[stitle]', '$fullname', '$_SESSION[uid]', ' $currentTime') ";

                        }
                        
                        if(mysqli_query($con, $sql))
                        {
                            ?>
                            <script>
                                alert("Record updated successfully");
                                window.location = 'sliderfile.php';
                            </script>
                            <?php
                        }
                        else
                        {
                            ?>
                            <script>
                                alert('OOPS !!!!');
                                /*setTimeout(() => {
                                    window.location = 'sliderfile.php';
                                }, 500); */
                            </script>
                            <?php
                        }

            }
            else{
                ?>
                    <script>
                        alert("Sorry, You Can't Upload More Slider Image. You Reach Your Maximum Limit ");
                        window.location = 'sliderfile.php';
                    </script>
                    <?php
                }

        }

 ?>



<?php
  if ( isset($_GET["del_id"]) ) {

        unlink($_GET["imgpath"]);
           
        $del_sql = "DELETE FROM slider WHERE sid = '$_GET[del_id]'" ;

        if ( mysqli_query($con, $del_sql) ) {
            ?>
            <script>window.location = "sliderfile.php";</script>
            <?php
        } else {
            ?>
            <script>
                alert('OOPS !!!!');
                setTimeout(() => {
                    window.location = 'sliderfile.php';
                }, 1200);
            </script>
            <?php
        }
        
    }

   
?>
<?php 

      if(isset($_POST['s_update']))
       {
          
            if (!empty($_FILES["file"]["name"]))
            {       

                unlink($_GET["imgpath"]);

                 #file name with a random number so that similar dont get replaced
                     $fname = rand(1000,10000)."-".$_FILES["file"]["name"];
         
                #temporary file name to store file
                     $tname = $_FILES["file"]["tmp_name"];
                   
                #upload directory path
                    $uploads_dir = '../upload/slider';
                #TO move the uploaded file to specific location
                    move_uploaded_file($tname, $uploads_dir.'/'.$fname);

                    $fullname = $uploads_dir.'/'.$fname;

                 $edit_sql = "UPDATE slider SET stitle = '$_POST[stitle]', slgimage ='$fullname' WHERE sid = '$_GET[edit_id]'";

            }
            else{

                    $edit_sql = "UPDATE slider SET stitle = '$_POST[stitle]' WHERE sid = '$_GET[edit_id]'";
            }

               
 
    

                if(mysqli_query($con, $edit_sql))
                {
                    ?>
                    <script>
                        alert("Record updated successfully");
                        window.location = 'sliderfile.php';
                    </script>
                    <?php
                }
                else
                {
                    ?>
                    <script>
                        alert('OOPS !!!!');
                        /*setTimeout(() => {
                            window.location = 'sliderfile.php';
                        }, 500); */
                    </script>
                    <?php
                }
    }
 ?>
<?php 

     function showDate($dt) 
     {
          $date=date_create();
          date_timestamp_set($date,
          strtotime("$dt"));
          return date_format($date,"M j, Y g:i a");
    }

    function showTime($t) 
     {
          $time=date_create();
          date_timestamp_set($time,
          strtotime("$t"));
          return date_format($time,"g:i a");
    }

 ?>