<?php
    session_start();
    include "../db.php";
    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)){
                        
                        $cat_sql = mysqli_query($con, "SELECT * FROM category WHERE cid = '$edit_row[data_subCategory]'");
                        if($cat_row = mysqli_fetch_assoc($cat_sql)){
                            $cat_name = $cat_row["cname"];
                        } else{
                            $cat_name = "";
                        }
                    ?>
                <div class="card">
                    <div class="card-header">
                        <h4 class="m-0">Edit Service : <?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-4 mb-3">
                                    <label for="category" class="form-label">Select Service Category</label>
                                    <select name="category" class="form-control">
                                        <option value="<?php echo $edit_row["data_subCategory"];?>">
                                            <?php echo $cat_name;?></option>
                                        <?php 
                                            $sql = "SELECT * FROM category";
                                            $res = mysqli_query($con, $sql);
                                            while ($row = mysqli_fetch_assoc($res)) {
                                        ?>
                                        <option data-id="<?php echo $row['cid']; ?>" value="<?php echo $row['cid']; ?>">
                                            <?php echo $row['cname']; ?></option>
                                        <?php } ?>
                                    </select>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label for="blogTitle" class="form-label">Service 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 class="col-md-2 mb-3">
                                    <label for="blogTitle" class="form-label">Service Pricing</label>
                                    <input type="number" class="form-control mb-2" id="course_name"
                                        value="<?php echo $edit_row["data_seo_tag"]; ?>" name="pricing">
                                </div>
                                <div class="col-md-12 mb-3">
                                    <label class="form-label" for="shortDes">Service Short Description</label>
                                    <textarea name="data_short_des" class="form-control" id="" cols="30"
                                        rows="5"><?php echo $edit_row['data_short_des'];?></textarea>
                                </div>
                                <div class="col-md-12 mb-3">
                                    <label for="blogABOUT">Service About</label>
                                    <textarea name="content" id="content"
                                        class="form-control ckeditor"><?php echo $edit_row["data_long_des"]; ?></textarea>
                                </div>
                                <div class="col-md-12 mb-3">
                                    <label for="blogABOUT">Service Required Documents</label>
                                    <div class="row">
                                        <?php
                                        // Convert the stored document IDs into an array
                                        $selected_docs = explode(', ', $edit_row["data_seo_title"]);

                                        $doc_sql = mysqli_query($con, "SELECT * FROM data WHERE data_catagory = 'serviceDocument' AND data_recycle = '1' ORDER BY data_title ASC");
                                        while ($doc_row = mysqli_fetch_assoc($doc_sql)) {
                                            // Check if the current document is in the selected list
                                            $is_checked = in_array($doc_row["data_sl_no"], $selected_docs) ? "checked" : "";
                                        ?>
                                        <div class="col-md-3 mb-2">
                                            <div class="card p-2">
                                                <div class="form-check text-center">
                                                    <input class="form-check-input" type="checkbox" name="documents[]"
                                                        value="<?php echo $doc_row["data_sl_no"]; ?>"
                                                        id="doc-<?php echo $doc_row["data_sl_no"]; ?>"
                                                        <?php echo $is_checked; ?>>
                                                    <label class="form-check-label"
                                                        for="doc-<?php echo $doc_row["data_sl_no"]; ?>">
                                                        <?php echo $doc_row["data_title"]; ?>
                                                    </label>
                                                </div>
                                            </div>
                                        </div>
                                        <?php } ?>
                                    </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="service.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["view_id"])){
                    $view_sql = "SELECT * FROM data WHERE data_sl_no='$_GET[view_id]'";
                    $view_data = mysqli_query($con,$view_sql);
                    if($view_rows = mysqli_fetch_array($view_data)){
                        $cat_sql = mysqli_query($con, "SELECT * FROM category WHERE cid = '$view_rows[data_subCategory]'");
                        if($cat_row = mysqli_fetch_assoc($cat_sql)){
                            $cat_name = $cat_row["cname"];
                        } else{
                            $cat_name = "";
                        }
                    ?>
                <div class="card">
                    <div class="card-header text-center">
                        <h4 class="m-0">Service Title : <span
                                class="underline"><?php echo $view_rows['data_title']; ?></span></h4>
                    </div>
                    <div class="card-body">
                        <div class="mb-2">
                            <?php
                                if (!empty($view_rows['data_img']))
                                {
                            ?>
                            <h5 class="underline">Service Image</h5>
                            <a href='../upload/corpedImage/<?php echo $view_rows["data_img"];?>' title='Click to open'
                                target='_blank'>
                                (<b>Already Uploaded - <img src='<?php echo $view_rows["data_img"];?>' height='50'
                                        data-toggle='modal' data-target='#show-img' class='showModal'>
                                </b> Click To View</a> )
                            <?php }
                                if (!empty($edit_row['data_img']))
                                { 
                            ?>
                            <a href='../upload/corpedImage/<?php echo $view_rows["data_img"];?>' title='Click to open'
                                target='_blank'>
                                (<b>Already Uploaded - <img src='<?php echo $view_rows["data_img"];?>' height='50'
                                        data-toggle='modal' data-target='#show-img' class='showModal'>
                                </b> Click To View</a> )
                            <?php } ?>
                        </div>
                        <hr>
                        <div class="mb-2">
                            <h5 class="underline">Service Category</h5>
                            <p><?php echo $cat_name; ?></p>
                            <h5 class="underline">Service Short Description</h5>
                            <p><?php echo $view_rows['data_short_des']; ?></p>
                            <h5 class="underline">Service Pricing</h5>
                            <p><i class="fa fa-inr"></i> <?php echo $view_rows['data_seo_tag']; ?> </p>
                        </div>
                        <hr>
                        <div class="mb-2">
                            <h5 class="underline">Service About</h5>
                            <p><?php echo $view_rows['data_long_des']; ?></p>
                            <h5 class="underline">Service Required documents</h5>
                            <ol>
                                <?php
                                // Convert the stored document IDs into an array
                                $selected_docs = explode(', ', $view_rows["data_seo_title"]);

                                $doc_sql = mysqli_query($con, "SELECT * FROM data WHERE data_catagory = 'serviceDocument' AND data_recycle = '1' ORDER BY data_title ASC");
                                while ($doc_row = mysqli_fetch_assoc($doc_sql)) {
                                    // Check if the current document is in the selected list
                                    if(in_array($doc_row["data_sl_no"], $selected_docs)){
                                ?>
                                <li>
                                    <?php echo $doc_row["data_title"]; ?>
                                </li>
                                <?php } } ?>
                            </ol>
                        </div>
                        <hr>
                        <p><strong>Service upload by : </strong><?php echo "Master_Admin"; ?></p>
                        <p><strong>Service edit date : </strong><?php echo $view_rows['data_edit_date']; ?></p>
                        <p><strong>Service Visitor Count : </strong><?php echo $view_rows['data_count']; ?></p>
                        <hr>
                        <a href="service.php?show_list" class="btn btn-warning btn-user m-2"> <i class="fas fa-ban"></i>
                            Cancel </a>
                    </div>
                </div>
                <?php } } elseif(isset($_GET["thumbnail_id"])){
                    $thumb_run = mysqli_query($con, "SELECT `data_img` FROM data WHERE data_sl_no = '$_GET[thumbnail_id]' ");
                    $thumb_row = mysqli_fetch_assoc($thumb_run);
                ?>
                <div class="card">
                    <div class="card-header">
                        <h4 class="mb-0"> Thumbnail Upload</h4>
                    </div>
                    <div class="card-body">
                        <div class="row mb-5">
                            <input type="hidden" id="thumbnailId" value="<?php echo $_GET['thumbnail_id']; ?>">
                            <div class="col-md-6">
                                <label color="black">Upload Thumbnail</label>
                                <div class="custom-file" style="height: 134px;">
                                    <input type="file" class="custom-file-input" name="up_position" id="file"
                                        accept="image/*" required>
                                    <label class="custom-file-label" for="file">Select
                                        an Image for thumbnail </label>
                                </div>
                            </div>
                            <?php    
                                if( !empty($thumb_row['data_img']) ){
                            ?>
                            <div class="col-md-6 mt-5" align='center'>
                                <img src="<?php echo $thumb_row['data_img']?>" class="img-fluid" alt=""
                                    style="border: solid 1px grey;">
                                <input type="hidden" id="previousThumbnail"
                                    value="<?php echo $thumb_row['data_img']; ?>">
                            </div>
                            <?php
                                }
                            ?>
                        </div>
                        <a href="service.php?show_list" class="btn btn-warning btn-user m-2"> <i class="fas fa-ban"></i>
                            Cancel </a>
                    </div>
                </div>
                <?php } elseif(isset($_GET["add_new"])){?>
                <div class="card">
                    <div class="card-header text-center">
                        <h4 class="card-title mb-0">Add Service</h4>
                    </div>
                    <div class="card-body">
                        <form action="" method="POST" enctype="multipart/form-data">
                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label for="category" class="form-label">Select Service Category</label>
                                    <select name="category" class="form-control" required>
                                        <option value="">Select From The List</option>
                                        <?php 
                                            $sql = "SELECT * FROM category ORDER BY cname ASC";
                                            $res = mysqli_query($con, $sql);
                                            while ($row = mysqli_fetch_assoc($res)) {
                                        ?>
                                        <option data-id="<?php echo $row['cid']; ?>" value="<?php echo $row['cid']; ?>">
                                            <?php echo $row['cname']; ?></option>
                                        <?php } ?>
                                    </select>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label for="exampleFormControlInput1" class="form-label">Service
                                        Name</label>
                                    <input type="Text" class="form-control" name="data_title"
                                        placeholder="Enter Service Title" required>
                                </div>
                                <div class="col-md-2 mb-3">
                                    <label for="exampleFormControlInput1" class="form-label">Service
                                        Pricing</label>
                                    <input type="number" class="form-control" name="pricing"
                                        placeholder="Enter Service Title">
                                </div>
                                <div class="col-md-12 mb-3">
                                    <label for="exampleFormControlTextarea1" class="form-label">Service Short
                                        Description</label>
                                    <textarea class="form-control " name="data_short_des" rows="3"></textarea>
                                </div>
                                <div class="col-md-12 mb-3">
                                    <label for="exampleFormControlTextarea1" class="form-label">Service Long
                                        Description</label>
                                    <textarea class="form-control ckeditor" name="content" id="content"
                                        rows="3"></textarea>
                                </div>
                                <div class="col-md-12 mb-3">
                                    <label for="exampleFormControlTextarea1" class="form-label">Required
                                        Documents</label>
                                    <div class="row">
                                        <?php
                                            $doc_sql = mysqli_query($con, "SELECT * FROM data WHERE data_catagory = 'serviceDocument' AND data_recycle = '1' ORDER BY data_title ASC");
                                            while ($doc_row = mysqli_fetch_assoc($doc_sql)) {
                                        ?>
                                        <div class="col-md-3 mb-2">
                                            <div class="card p-2">
                                                <div class="form-check text-center">
                                                    <input class="form-check-input" type="checkbox" name="documents[]"
                                                        value="<?php echo $doc_row["data_sl_no"]; ?>"
                                                        id="doc-<?php echo $doc_row["data_sl_no"]; ?>">
                                                    <label class="form-check-label"
                                                        for="doc-<?php echo $doc_row["data_sl_no"]; ?>">
                                                        <?php echo $doc_row["data_title"]; ?>
                                                    </label>
                                                </div>
                                            </div>
                                        </div>
                                        <?php } ?>
                                    </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 mt-3">
                    <div class="card-header">
                        <div class="row align-items-center">
                            <div class="col-md-8">
                                <div class="d-flex justify-content-between">
                                    <h4 class="text-gray-800 m-0">Service List</h4>
                                    <a class="btn btn-primary btn-sm" href="service.php?add_new"><i
                                            class="fa fa-wrench"></i>
                                        Add
                                        Service</a>
                                </div>
                            </div>
                            <div class="col-md-4 mt-2 mt-lg-0">
                                <div class="d-flex">
                                    <div class="form-group">
                                        <input type="text" list="Cat" class="form-control form-control-sm"
                                            id="catFilterValue" placeholder="Search By Category">
                                        <datalist id="Cat">
                                            <?php 
                                                $sql = "SELECT cid, cname FROM category WHERE cposition = '1' AND catby = '1' ORDER BY cname ASC";
                                                $res = mysqli_query($con, $sql);
                                                while ($row = mysqli_fetch_assoc($res)) {
                                            ?>
                                            <option value="<?php echo $row['cname']; ?>"
                                                data-cid="<?php echo $row['cid']; ?>">
                                                <?php echo $row['cname']; ?>
                                            </option>
                                            <?php } ?>
                                        </datalist>
                                    </div>

                                    <div class="form-group">
                                        <input type="text" list="First" class="form-control form-control-sm"
                                            id="FirstFilterValue" placeholder="Search By Service">
                                        <datalist id="First">
                                            <!-- Options will be populated by JavaScript -->
                                        </datalist>
                                    </div>
                                    <div class="d-none">
                                        <button type="button" id="filter" class="btn btn-primary btn-sm"> Search
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <!--loader -->
                            <div class="col-12" id='loader'>
                                <ul style="list-style: none; padding-left: 0;">
                                    <?php
                                    for ($count = 0; $count < 4; $count++) {
                                        echo '<li>
                                        <div class="ph-item">
                                        <div cl ass="ph-test">
                                        <div class="ph-row">
                                        <div class="ph-col-12 big"></div>
                                        <div class="ph-col-12"></div>
                                        <div class="ph-col-12"></div>
                                        <div class="ph-col-12"></div>
                                        <div class="ph-col-12"></div>
                                        <div class="ph-col-12"></div>
                                        </div>
                                        </div>
                                        </div>
                                        </li>';
                                        }
                                    ?>
                                </ul>
                            </div>

                            <!-- loader -->
                            <div class="col-12" id="full-table">
                                <ul class="timeline" id="full-table-data" style="list-style: none; padding: 0;">
                                    </>
                                </ul>
                            </div>

                            <div class="col-12" id="filter-table" style="display: none;">
                                <ul class="timeline" id="filter-table-data" style="list-style: none; padding: 0;">
                                    </>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
                <?php }?>
            </div>
        </div>

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

    <!-- JavaScript Libraries -->

    <?php include "include/js.php"; ?>
    <script src="../assets/croppie/croppie.js"></script>

    <script>
    CKEDITOR.replace('content', {
        height: 300,
        filebrowserUploadUrl: "upload.php"
    });
    CKEDITOR.replace('content2', {
        height: 300,
        filebrowserUploadUrl: "upload.php"
    });
    </script>



    <script>
    // Function to fetch services based on selected category or all services if no category is selected
    function fetchServices(categoryName = '') {
        fetch(`fetch_services.php?category=${encodeURIComponent(categoryName)}`)
            .then(response => response.json())
            .then(data => {
                const firstDatalist = document.getElementById('First');
                firstDatalist.innerHTML = ''; // Clear previous options

                data.forEach((service, index) => {
                    const option = document.createElement('option');
                    option.value = service.data_title;
                    option.textContent = `${service.data_title}`;
                    // option.textContent = `${index + 1}. ${service.data_title}`;
                    firstDatalist.appendChild(option);
                });
            })
            .catch(error => console.error('Error fetching services:', error));
    }

    // Event listener for category input
    document.getElementById('catFilterValue').addEventListener('input', function() {
        const categoryName = this.value;

        if (categoryName) {
            // Fetch services for the selected category
            fetchServices(categoryName);
        } else {
            // Fetch all services if no category is selected
            fetchServices();
        }
    });

    // Initial fetch to load all services on page load
    fetchServices();
    </script>

    <!-- thumbnail Upload-->
    <div id="uploadimageModal" class="modal" role="dialog" style="padding:15px;">
        <div class="modal-dialog" style="max-width: 100%; width:auto;">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Upload & Crop Image</h4>
                </div>
                <div class="modal-body">
                    <div class="row mx-0">
                        <div class="col-md-12 col-sm-12 col-12 text-center">
                            <div id="image_demo" style="margin-top:10px;height:40%;"></div>
                            <p class="small">scroll through mouse to zoom in or out</p>
                        </div>
                        <div class="col-md-12 col-sm-12 col-12 text-center">
                            <button class="btn btn-success crop_image" id="cropppp">Crop & Upload Image</button>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-warning" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
    <!-- thumbnail Upload-->

    <!-- Thumbnail Script -->
    <script>
    function checkFileDetails() {
        var fi = document.getElementById('file');
        if (fi.files.length > 0) {
            for (var i = 0; i <= fi.files.length - 1; i++) {
                var fileName, fileExtension, fileSize, fileType, dateModified;
                fileName = fi.files.item(i).name;
                fileExtension = fileName.replace(/^.*\./, '');
                if (fileExtension == 'png' || fileExtension == 'jpg' || fileExtension == 'jpeg') {
                    readImageFile(fi.files.item(i));
                }
            }

            function readImageFile(file) {
                var reader = new FileReader();
                reader.onload = function(e) {
                    var img = new Image();
                    img.src = e.target.result;
                    img.onload = function() {
                        var imgWidth = this.width;
                        var imgHeight = this.height;
                        if (imgWidth == 1200 && imgHeight == 512 || imgWidth == 1500 && imgHeight == 640) {
                            var imgCheck = "<i class='fas fa-check-circle text-success'></i>";
                        } else {
                            var imgCheck = "<i class='fas fa-times-circle text-danger'></i>";
                        }
                        document.getElementById('fileInfo').innerHTML =
                            document.getElementById('fileInfo').innerHTML + '<br> ' +
                            'Name: <b>' + file.name + '</b> <br>' +
                            'Size: <b>' + Math.round((file.size / 1024)) + '</b> KB <br>' +
                            'Dimension: <b>' + imgWidth + '</b> x <b>' + imgHeight + '</b> ' + imgCheck +
                            ' <br>';
                    }
                };
                reader.readAsDataURL(file);
            }
        }
    }
    </script>

    <script>
    $(document).ready(function() {
        $('#show-img').on('show.bs.modal', function(e) {
            var src = $(e.relatedTarget).attr('src');
            $(this).find('.modal-body > img').attr('src', src);
        });
        $image_crop = $('#image_demo').croppie({
            enableExif: true,
            viewport: {
                width: 1200,
                height: 620,
                type: 'square'
            },
            boundary: {
                width: 1210,
                height: 630
            }
        });

        $('#file').on('change', function() {
            var reader = new FileReader();
            reader.onload = function(event) {
                $image_crop.croppie('bind', {
                    url: event.target.result
                }).then(function() {
                    console.log('jQuery bind complete');
                });
            }
            reader.readAsDataURL(this.files[0]);
            $('#uploadimageModal').modal('show');
        });

        $('.crop_image').click(function(event) {
            $('#cropppp').html('uploading <i class="fas fa-spinner fa-pulse"></i>');
            $image_crop.croppie('result', {
                type: 'canvas',
                size: 'viewport'
            }).then(function(response) {
                var refid = $('#thumbnailId').val();
                var previousThumbnail = $('#previousThumbnail').val();
                // Send cropped image data to the server for processing
                $.ajax({
                    url: "update-alldata-thumbnail-ajax.php", // Replace with your PHP processing script
                    method: "POST",
                    data: {
                        image: response,
                        refid: refid,
                        previousThumbnail: previousThumbnail
                    },
                    success: function(data) {
                        // Handle success (e.g., show success message or update UI)
                        $('#uploadimageModal').modal('hide');
                        $('#uploaded_image').html(
                            data); // Update uploaded image display
                        var refid = $('#thumbnailId').val();
                        $(location).attr('href', 'service.php' + '?thumbnail_id=' +
                            refid); // Redirect if needed
                    },
                    error: function() {
                        // Handle error (e.g., show error message)
                    }
                });
            });
        });
    });
    </script>
    <!-- Thumbnail Script -->


    <script>
    $(document).ready(function() {
        let currentPage = 1;
        const perPage = 2;

        function fetchData(page, filters) {
            $("#loader").show();
            $.ajax({
                url: 'service-Ajax.php',
                type: 'POST',
                data: {
                    page: page,
                    perPage: perPage,
                    ...filters
                },
                success: function(result) {
                    $('#full-table-data').html(result);
                    currentPage = page;
                    $('html, body').animate({
                        scrollTop: 0
                    }, 'fast');
                },
                error: function() {
                    alert('An error occurred while fetching data.');
                },
                complete: function() {
                    $("#loader").hide();
                }
            });
        }

        function getFilters() {
            return {
                FirstFilterValue: $("#FirstFilterValue").val(),
                catFilterValue: $("#catFilterValue").val()
            };
        }

        // Initial load
        fetchData(currentPage, getFilters());

        // Handle filter changes
        $('#FirstFilterValue, #catFilterValue').on('change', function() {
            fetchData(1, getFilters());
        });

        // Handle pagination
        $('#full-table-data').on('click', '.page-link', function(e) {
            e.preventDefault();
            const targetPage = $(this).data('page');
            if (targetPage !== undefined && targetPage !== currentPage) {
                fetchData(targetPage, getFilters());
                // Scroll to the top after pagination
                $('html, body').animate({
                    scrollTop: 0
                }, 'slow');
            }
        });
    });
    </script>

</body>

</html>


<!-- Add to database  Blog-->
<?php
  if (isset($_POST['addsubmit'])) {
    $title = mysqli_real_escape_string($con, strip_tags($_POST['data_title']));
    $short_des = mysqli_real_escape_string($con, strip_tags($_POST['data_short_des']));
    $subCategory = mysqli_real_escape_string($con, strip_tags($_POST['category']));
    $pricing = mysqli_real_escape_string($con, strip_tags($_POST['pricing']));
    $long_des = $_POST['content'];
    $long_des2 = $documents = isset($_POST['documents']) ? implode(', ', $_POST['documents']) : '';

    $prefix = "SERVICE"; // 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= 'service';

    // new File Upload
    $file = $_FILES["file"]["tmp_name"];
    $f = $_FILES["file"]["name"];
    $ext = pathinfo($f,PATHINFO_EXTENSION);
    $fname = rand(10000, 999999).".".$ext;
  

    $courseCatagory_sql = "INSERT INTO data ( data_ref_id, data_catagory, data_title, data_img, data_short_des, data_long_des, data_up_by, data_up_date, data_recycle, data_subCategory, data_seo_title, data_seo_tag) VALUES ( '$ref_id', '$catagory', '$title',  '$fname', '$short_des', '$long_des', '$up_by', '$up_date', '$recycle', '$subCategory', '$long_des2', '$pricing')";
    
    if( mysqli_query($con, $courseCatagory_sql) ){
        // Move Files
      move_uploaded_file($file,'../upload/service/'.$fname);
        ?>
<script>
alert("Details Sent Successfully");
window.location = "service.php?show_list";
</script>
<?php
    }
    else{
        ?>
<script>
alert("Something's Wrong");
window.location = "service.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']));
    $short_des = mysqli_real_escape_string($con, strip_tags($_POST['data_short_des']));
    $subCategory = mysqli_real_escape_string($con, strip_tags($_POST['category']));
    $pricing = mysqli_real_escape_string($con, strip_tags($_POST['pricing']));
    $long_des = $_POST['content'];
    $long_des2 = $documents = isset($_POST['documents']) ? implode(', ', $_POST['documents']) : '';
        
    $edit_date = date("j F, Y, g:i a");

        
        if ($_FILES["file"]["tmp_name"]) {
            // new File Upload
            $file = $_FILES["file"]["tmp_name"];
            $f = $_FILES["file"]["name"];
            $ext = pathinfo($f, PATHINFO_EXTENSION);
            $fname = rand(10000, 999999) . "." . $ext;
            $sql_select = "SELECT data_img FROM data WHERE data_sl_no = '$_GET[edit_id]'";
            $result = $con->query($sql_select);
            if ($result && $row = $result->fetch_assoc()) {
                $previous_logo = $row['data_img'];
                if (!empty($previous_logo)) {
                    $previous_image_path = '../upload/service/' . $previous_logo;
                    if (file_exists($previous_image_path)) {
                        unlink($previous_image_path);
                    }
                }
            }
        } else {
            // If no new file is uploaded, keep the previous image filename
            $fname = $edit_row['data_img'];
        }
	
        {
            $up_sql = "UPDATE data SET data_title='$title', data_short_des='$short_des', data_subCategory = '$subCategory', data_long_des='$long_des', data_img = '$fname', data_seo_title = '$long_des2', data_seo_tag = '$pricing', data_edit_date = '$edit_date' ";
   
        $up_sql .= " WHERE data_sl_no = '$_GET[edit_id]'";
		 if(mysqli_query($con, $up_sql)){

         // Move Files
         move_uploaded_file($file,'../upload/service/'.$fname);
       
            ?>
<script>
alert("Data Updated Successfully");
window.location = 'service.php?show_list';
</script>
<?php
        }
     else{
?>
<script>
alert('OOPS !!!!');
setTimeout(() => {
    window.location = 'service.php?show_list';
}, 1200);
</script>
<?php
        }
        
?>
<?php
        }
    }

?>


<!-- Recycle database  service-->
<?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 = "service.php?show_list";
</script>
<?php
        } else {
            ?>
<script>
alert('OOPS !!!!');
setTimeout(() => {
    window.location = 'service.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/service/' . $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 = "service.php?show_list";
</script>
<?php
    } else {
        ?>
<script>
alert("Failed to delete");
window.location = "service.php?show_list";
</script>
<?php
    }
}
?>