<?php
    // session_start();
    include "../db.php";
    require '../auth.php';
    restrictAccess(['master_admin']);
    date_default_timezone_set('Asia/Kolkata');
    $currentTime = date('M j, Y g:i a');

    if ( !isset($_SESSION['uid']) && !isset($_SESSION['uref']) && !isset($_SESSION['utype']) ) {
        header("Location: logout.php");
        exit();
    }

    if ( $_SESSION['utype'] != 'master_admin' && $_SESSION['uref'] != 'fssdf4543frts' ) {
        header("Location: logout.php");
        exit();
    }
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <?php include "include/meta.php"; ?>
    <?php include "include/css.php"; ?>
    <?php include "include/php-functions.php"; ?>
    <link rel="stylesheet" href="../assets/croppie/croppie.css" />
    <script src="https://cdn.ckeditor.com/4.6.2/standard-all/ckeditor.js"></script>
</head>

<body>
    <!--  Header -->
    <?php 
    include "include/header.php"; 
    ?>
    <!-- #header -->

    <section id="inner-body">
        <div class="body-content">
            <div class="container-fluid">
                <?php if(isset($_GET["edit_id"])){
                    $edit_run = mysqli_query($con, "SELECT * FROM data  WHERE data_sl_no = '$_GET[edit_id]'");
                    if($edit_row = mysqli_fetch_assoc($edit_run)){
                    ?>
                <div class="card">
                    <div class="card-header">
                        <h4 class="m-0">Edit Document : <?php echo $edit_row["data_title"];?></h4>
                    </div>
                    <div class="card-body">
                        <form class="user" method="post" enctype="multipart/form-data">
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="mb-3">
                                        <label for="blogTitle" class="form-label">Document Title</label>
                                        <input type="text" class="form-control mb-2" id="course_name"
                                            value="<?php echo $edit_row["data_title"]; ?>" name="data_title">
                                    </div>
                                </div>

                                <div class="col-md-12">
                                    <button type="submit" class="btn btn-success btn-user m-2" name="edit_blog">
                                        <i class="fa fa-edit"></i> Update
                                    </button>
                                    <a href="document-list.php?show_list" class="btn btn-warning btn-user m-2"> <i
                                            class="fas fa-ban"></i>
                                        Cancel </a>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <?php } }  elseif(isset($_GET["add_new"])){?>
                <div class="card">
                    <div class="card-header text-center">
                        <h4 class="card-title mb-0">Service Documents List</h4>
                    </div>
                    <div class="card-body">
                        <form action="" method="POST" enctype="multipart/form-data">
                            <div class="row">
                                <div class="col-md-12 mb-3">
                                    <div class="mb-2">
                                        <label for="exampleFormControlInput1" class="form-label">Enter Document
                                            Title</label>
                                        <input type="Text" class="form-control" name="data_title"
                                            placeholder="Enter document-list Title">
                                    </div>
                                </div>
                                <div class="mb-3">
                                    <button class="btn btn-success text-white me-md-2" name="addsubmit" type="submit"><i
                                            class="fa fa-paper-plane"></i> Submit</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <?php }?>
                <?php if(isset($_GET["show_list"])){?>
                <div class="card">
                    <?php
                        $records_per_page = 10; // Number of records per page

                        if (isset($_GET['page'])) {
                            $page = intval($_GET['page']);
                        } else {
                            $page = 1;
                        }

                        $start_from = ($page-1) * $records_per_page;
                    ?>

                    <?php
                        if (isset($_GET['recycle_table'])) {
                    ?>
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h3>Recycle document-list List</h3>
                            </div>
                            <div>
                                <a href="document-list.php?show_list" class="btn btn-primary text-white">Active
                                    document-list</a>
                            </div>
                        </div>

                        <div class="table-responsive">
                            <input type="text" id="searchRecycle" class="form-control mb-3"
                                placeholder="Search Recycle Document by Document Title">
                            <table class="table table-hover table-striped table-bordered" id="thisismytable">
                                <thead>
                                    <tr>
                                        <th>No.</th>
                                        <th>Document Title</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody id="table-body-recycle">
                                    <?php
                                        $sql = "SELECT * FROM data WHERE data_catagory='serviceDocument' AND data_recycle = '0' ORDER BY data_sl_no DESC LIMIT $start_from, $records_per_page";
                                        $run = mysqli_query($con, $sql);
                                        $c = 1 + $start_from;
                                        while ($rows = mysqli_fetch_assoc($run)) {
                                            echo "
                                            <tr id='$rows[data_sl_no]'>
                                                <td class='align-middle'>
                                                    <span class='text-dark'>$c</span>
                                                </td>
                                                <td class='align-middle'>
                                                    $rows[data_title]
                                                </td>";
                                    ?>
                                    <td class='align-middle text-center' style="max-width:77px;">
                                        <a class="btn btn-primary btn-sm" style="margin-left:5px;"
                                            href="document-list.php?edit_id=<?php echo $rows['data_sl_no']; ?>">
                                            Edit</a>
                                        <a href='document-list.php?rec_id=<?php echo $rows["data_sl_no"]; ?>'
                                            class='delete m-2 btn btn-danger btn-sm rounded-circle'
                                            title='Click to Delete'>
                                            <i class="fa fa-recycle" aria-hidden="true"></i>
                                        </a>
                                        <a href='document-list.php?del_id=<?php echo $rows["data_sl_no"]; ?>'
                                            class='delete m-2 btn btn-danger btn-sm rounded-circle'
                                            title='Click to Delete'>
                                            <i class="fa fa-trash" aria-hidden="true"></i>
                                        </a>
                                    </td>
                                    </tr>
                                    <?php
                                        $c++;
                                        }
                                    ?>
                                </tbody>
                            </table>
                            <?php
                                $sql = "SELECT COUNT(data_sl_no) FROM data WHERE data_catagory='document-list' AND data_recycle = '0'";
                                $run = mysqli_query($con, $sql);
                                $row = mysqli_fetch_row($run);
                                $total_records = $row[0];
                                $total_pages = ceil($total_records / $records_per_page);
                            ?>
                            <nav>
                                <ul class="pagination">
                                    <?php for ($i=1; $i<=$total_pages; $i++) { ?>
                                    <li class="page-item"><a class="page-link"
                                            href="document-list.php?show_list&recycle_table&page=<?php echo $i; ?>"><?php echo $i; ?></a>
                                    </li>
                                    <?php } ?>
                                </ul>
                            </nav>
                        </div>
                    </div>
                    <?php } else { ?>
                    <div class="card-body">
                        <div class="row justify-content-between mb-3">
                            <div class="col-md-9 mb-2">
                                <h3>Active Service Documents</h3>
                            </div>
                            <div class="col-md-3 d-flex justify-content-between">
                                <a href="document-list.php?add_new" class="btn btn-primary text-white btn-sm"><i
                                        class="fa fa-plus"></i>
                                    Add Document</a>
                                <a href="document-list.php?show_list&recycle_table"
                                    class="btn btn-info text-white btn-sm">Recycle
                                    Document</a>
                            </div>
                        </div>
                        <div class="table-responsive">
                            <input type="text" id="searchActive" class="form-control form-control-sm mb-3"
                                placeholder="Search Active document-list By document-list Title">
                            <table class="table table-hover table-striped table-bordered" id="thisismytable">
                                <thead>
                                    <tr>
                                        <th>No.</th>
                                        <th>Document Title</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody id="table-body-active">
                                    <?php
                                        $sql = "SELECT * FROM data WHERE data_catagory = 'serviceDocument' AND data_recycle = '1' ORDER BY data_sl_no DESC LIMIT $start_from, $records_per_page";
                                        $run = mysqli_query($con, $sql);
                                        $c = 1 + $start_from;
                                        while ($rows = mysqli_fetch_assoc($run)) {
                                            echo "
                                            <tr id='$rows[data_sl_no]'>
                                                <td class='align-middle'>
                                                    <span class='text-dark '>$c</span>
                                                </td>
                                                <td class='align-middle'>
                                                    $rows[data_title]
                                                </td>";
                                    ?>
                                    <td class='align-middle text-center' style="max-width:77px;">
                                        <a class="btn btn-primary btn-sm" style="margin-left:5px;"
                                            href="document-list.php?edit_id=<?php echo $rows['data_sl_no']; ?>">
                                            Edit</a>
                                        <a href='document-list.php?rec_id=<?php echo $rows["data_sl_no"]; ?>'
                                            class='delete m-2 btn btn-danger btn-sm rounded-circle'
                                            title='Click to Recycle'>
                                            <i class="fa fa-recycle" aria-hidden="true"></i>
                                        </a>
                                    </td>
                                    </tr>
                                    <?php
                                        $c++;
                                        }
                                    ?>
                                </tbody>
                            </table>
                            <?php
                                $sql = "SELECT COUNT(data_sl_no) FROM data WHERE data_catagory='document-list' AND data_recycle = '1'";
                                $run = mysqli_query($con, $sql);
                                $row = mysqli_fetch_row($run);
                                $total_records = $row[0];
                                $total_pages = ceil($total_records / $records_per_page);
                            ?>
                            <nav>
                                <ul class="pagination">
                                    <?php for ($i=1; $i<=$total_pages; $i++) { ?>
                                    <li class="page-item"><a class="page-link"
                                            href="document-list.php?show_list&page=<?php echo $i; ?>"><?php echo $i; ?></a>
                                    </li>
                                    <?php } ?>
                                </ul>
                            </nav>
                        </div>
                    </div>
                    <?php
                        }
                    ?>
                </div>
                <?php }?>
            </div>
        </div>

        <?php include "include/footer.php"; ?>
    </section>

    <!-- JavaScript Libraries -->

    <?php include "include/js.php"; ?>

    <script>
    $(document).ready(function() {
        $('#searchActive').on('keyup', function() {
            var query = $(this).val();
            $.ajax({
                url: 'document-listSearch.php',
                method: 'POST',
                data: {
                    query: query,
                    type: 'active'
                },
                success: function(data) {
                    $('#table-body-active').html(data);
                }
            });
        });

        $('#searchRecycle').on('keyup', function() {
            var query = $(this).val();
            $.ajax({
                url: 'document-listSearch.php',
                method: 'POST',
                data: {
                    query: query,
                    type: 'recycle'
                },
                success: function(data) {
                    $('#table-body-recycle').html(data);
                }
            });
        });
    });
    </script>

</body>

</html>


<!-- Add to database  Blog-->
<?php
  if (isset($_POST['addsubmit'])) {
    $title = mysqli_real_escape_string($con, strip_tags($_POST['data_title']));

    $prefix = "serviceDocument"; // Your prefix
    $random_number = str_pad(rand(0, 99999), 5, '0', STR_PAD_LEFT);
    $timestamp = date("YmdHis"); 

    $ref_id = $prefix . $random_number . $timestamp;
    
    $up_date = date("j F, Y, g:i a");
    $recycle = "1";
    $up_by= $_SESSION['uid'];
    $catagory= 'serviceDocument';

    $courseCatagory_sql = "INSERT INTO data ( data_ref_id, data_catagory, data_title, data_up_by, data_up_date, data_recycle) VALUES ( '$ref_id', '$catagory', '$title', '$up_by', '$up_date', $recycle)";
    
    if( mysqli_query($con, $courseCatagory_sql) ){
        ?>
<script>
alert("Details Sent Successfully");
window.location = "document-list.php?show_list";
</script>
<?php
    }
    else{
        ?>
<script>
alert("Something's Wrong");
window.location = "document-list.php?add_new";
</script>
<?php
    }
  }
?>


<!-- Edit database  Blog-->
<?php
    if(isset($_POST['edit_blog'])){ 
	$title = mysqli_real_escape_string($con, strip_tags($_POST['data_title']));
        
    $edit_date = date("j F, Y, g:i a");
        {
            $up_sql = "UPDATE data SET data_title='$title', data_edit_date = '$edit_date' ";
   
        $up_sql .= " WHERE data_sl_no = '$_GET[edit_id]'";
		 if(mysqli_query($con, $up_sql)){
       
            ?>
<script>
alert("Data Updated Successfully");
window.location = 'document-list.php?show_list';
</script>
<?php
        }
     else{
?>
<script>
alert('OOPS !!!!');
setTimeout(() => {
    window.location = 'document-list.php?show_list';
}, 1200);
</script>
<?php
        }
        
?>
<?php
        }
    }

?>


<!-- Recycle database  document-list-->
<?php
  if ( isset($_GET["rec_id"]) ) {
    $find_sql = "SELECT * FROM data WHERE data_sl_no = '$_GET[rec_id]'";
    $find_run = mysqli_query($con, $find_sql);
    if ($f_rows = mysqli_fetch_assoc($find_run)) {
        $old_rec = $f_rows["data_recycle"];
    
        if ($old_rec == 1) {
            $new_rec = 0;
        } elseif ($old_rec == 0) {
            $new_rec = 1;
        }
    
        $update_sql = "UPDATE data SET data_recycle = '$new_rec' WHERE data_sl_no = '$_GET[rec_id]'";
        $update_run = mysqli_query($con, $update_sql);

        if ( $update_run ) {
            ?>
<script>
alert("Sent to Recycle Successfully");
window.location = "document-list.php?show_list";
</script>
<?php
        } else {
            ?>
<script>
alert('OOPS !!!!');
setTimeout(() => {
    window.location = 'document-list.php?show_list';
}, 1200);
</script>
<?php
        }
        
    }

}
?>


<!-- delete database  Blog-->
<?php
if (isset($_GET["del_id"])) {
    $id = mysqli_real_escape_string($con, $_GET["del_id"]);
    
    $find_sql = "SELECT * FROM data WHERE data_sl_no = '$id'";
    $find_run = mysqli_query($con, $find_sql);

    if ($f_rows = mysqli_fetch_assoc($find_run)) {
        $old_img = $f_rows['data_img'];

        if (!empty($old_img)) {
            $previous_image_path = '../upload/document-list/' . $old_img;

            if (file_exists($previous_image_path)) {
                if (unlink($previous_image_path)) {
                    // Image deleted successfully
                } else {
                    // Failed to delete image
                    echo "Error deleting image: " . mysqli_error($con);
                }
            }
        }
    }

    $delete_sql = "DELETE FROM data WHERE data_sl_no = '$id'";
    
    if (mysqli_query($con, $delete_sql)) {
        ?>
<script>
alert("Deleted Successfully");
window.location = "document-list.php?show_list";
</script>
<?php
    } else {
        ?>
<script>
alert("Failed to delete");
window.location = "document-list.php?show_list";
</script>
<?php
    }
}
?>