<?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"; ?>

</head>

<style>

.location-item {

    background: #fff;

    padding: 5px 10px;

    display: flex;

    align-items: center;

    justify-content: space-between;

    border-radius: 3px;

}



.custom-select {

    position: relative;

}



.checkboxes {

    display: none;

    border: 1px solid #ccc;

    padding: 10px;

    position: absolute;

    background: white;

    z-index: 1;

    width: 100%;

}



.custom-select.open .checkboxes {

    display: block;

}



.custom-select.open::after {

    content: '▲';

    right: 10px;

    top: 50%;

    transform: translateY(-50%);

    position: absolute;

}

</style>



<body>

    <!--  Header -->

    <?php 

    include "include/header2.php"; 

    ?>

    <!-- #header -->



    <section id="inner-body">

        <div class="body-content">

            <div class="container-fluid">

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

                    $edit_id = $_GET["edit_id"];

                    $details_sql = mysqli_query($con, "SELECT * FROM ad WHERE ad_id = '$edit_id'");

                    if($details_row = mysqli_fetch_assoc($details_sql)){

                        $class_sql = mysqli_query($con, "SELECT sclass FROM class WHERE sid = '$details_row[ad_class]'");

                        if($class_row = mysqli_fetch_assoc($class_sql)){

                            $class_name = $class_row["sclass"];

                        }

                    ?>

                <div class="card mt-3">

                    <h5 class="card-header text-dark  text-center font-weight-bold">Edit AD Details</h5>

                    <div class="card-body">

                        <?php

                        $existing_locations = $details_row["ad_location"];

                        $existing_image = $details_row["ad_img"];

                        ?>

                        <form method="POST" action="" enctype="multipart/form-data">

                            <div class="row">

                                <div class="col-md-12 mb-2">

                                    <div class="from-group">

                                        <label for="adTitle">Edit AD Title</label>

                                        <input type="text" class="form-control" id="edit_ad_title"

                                            value="<?php echo $details_row["ad_title"];?>" name="edit_ad_title"

                                            required>

                                    </div>

                                </div>

                                <div class="col-md-4 mb-2">

                                    <div class="from-group">

                                        <label for="ad-img">Select New AD Image (<span style="font-size:12px;"><a

                                                    style="text-decoration:none; color:#735c5c;"

                                                    href="../upload/ad/<?php echo $details_row["ad_img"];?>"

                                                    target="_blank">View AD Image <i

                                                        class="fa fa-eye"></i></a></span>)</label>

                                        <input type="file" class="form-control" name="edit_file" accept="image/*">

                                        <input type="hidden" name="existing_image"

                                            value="<?php echo $existing_image; ?>">

                                    </div>

                                </div>

                                <div class="col-md-4 mb-2">

                                    <div class="from-group">

                                        <label for="adUrl">Edit AD URl (<span style="font-size:12px;"><a

                                                    style="text-decoration:none; color:#735c5c;"

                                                    href="<?php echo $details_row["ad_url"];?>" target="_blank">View AD

                                                    Url <i class="fa fa-eye"></i></a></span>)</label>

                                        <input type="text" class="form-control"

                                            value="<?php echo $details_row["ad_url"];?>" name="edit_ad_url" required>

                                    </div>

                                </div>

                                <div class="col-md-4 mb-2">

                                    <div class="form-group">

                                        <label for="class">Select Class</label>

                                        <div class="custom-select" id="classSelect">

                                            <?php

                                            $class_ids = $details_row['ad_class'];

                                            $class_sql = mysqli_query($con, "SELECT sclass FROM class WHERE sid IN ($class_ids)");

                                

                                            $class_names = [];

                                            while($class_row = mysqli_fetch_assoc($class_sql)){

                                                $class_names[] = $class_row['sclass'];

                                            }

                                

                                            $class_names_string = implode(', ', $class_names);

                                            ?>

                                            <input type="text" name="ad_class_names" id="selectedClassNames"

                                                class="form-control" placeholder="<?php echo $class_names_string;?>"

                                                readonly>

                                            <input type="hidden" name="edit_ad_class" id="selectedClassIds"

                                                value="<?php echo $class_ids;?>">

                                            <div class="checkboxes">

                                                <?php

                                                    $class_sql = mysqli_query($con, "SELECT * FROM class WHERE uploadedby = 'fssdf4543frts' AND cdisplay != 'disabled'");

                                                    while($class_row = mysqli_fetch_assoc($class_sql)){

                                                ?>

                                                <label>

                                                    <input type="checkbox" value="<?php echo $class_row['sid']; ?>"

                                                        data-name="<?php echo $class_row['sclass']; ?>">

                                                    <?php echo $class_row['sclass']; ?>

                                                </label>

                                                <br>

                                                <?php }?>

                                            </div>

                                        </div>

                                    </div>

                                </div>

                                <div class="col-md-12">

                                    <div class="ad-location-select">

                                        <div class="row">

                                            <div class="col-md-8 mb-2">

                                                <div class="row">

                                                    <div class="col-md-4 mb-2">

                                                        <label for="edit-state">State</label>

                                                        <input type="hidden" name="state" id="edit-state-id" value="">

                                                        <input type="text" list="state" class="form-control"

                                                            id="edit-state-input" placeholder="Select from the list">

                                                        <datalist id="state">

                                                            <?php 

                                                            $sql = "SELECT id, name FROM state ORDER BY id ASC";

                                                            $res = mysqli_query($con, $sql);

                                                            while ($row = mysqli_fetch_assoc($res)) {

                                                            ?>

                                                            <option data-id="<?php echo $row['id']; ?>"

                                                                value="<?php echo $row['name']; ?>">

                                                                <?php echo $row['name']; ?></option>

                                                            <?php } ?>

                                                        </datalist>

                                                    </div>

                                                    <div class="col-md-5 mb-2">

                                                        <label for="edit-district">District</label>

                                                        <input type="hidden" name="dist" id="edit-district-id" value="">

                                                        <input type="text" list="district-list" class="form-control"

                                                            id="edit-district-input" placeholder="Select from the list">

                                                        <datalist id="district-list"></datalist>

                                                    </div>

                                                    <div class="col-md-3 mb-2 d-flex align-items-end">

                                                        <button id="edit-btn-add-location"

                                                            class="btn btn-primary btn-add">Add Location</button>

                                                    </div>

                                                </div>

                                            </div>

                                            <div class="col-md-4 mb-2">

                                                <div id="edit-preview-locations"

                                                    style="background: #f1f1f1;padding: 10px;border: 1px solid #1d7a85;border-radius: 7px;">

                                                    <!-- Existing Locations -->

                                                    <?php

                                                    $pairs = explode(',', $existing_locations);

                                                    $state_district_map = [];

                                                    foreach ($pairs as $pair) {

                                                        list($state_id, $district_id) = explode('-', $pair);

                                                        if (!isset($state_district_map[$state_id])) {

                                                            $state_district_map[$state_id] = [];

                                                        }

                                                        if ($district_id != '0') {

                                                            $state_district_map[$state_id][] = $district_id;

                                                        }

                                                    }

                        

                                                    $state_ids = array_keys($state_district_map);

                                                    $state_ids_str = implode(',', $state_ids);

                                                    $state_sql = "SELECT id, name FROM state WHERE id IN ($state_ids_str)";

                                                    $state_res = mysqli_query($con, $state_sql);

                                                    $states = [];

                                                    while ($row = mysqli_fetch_assoc($state_res)) {

                                                        $states[$row['id']] = $row['name'];

                                                    }

                        

                                                    $all_district_ids = array_merge(...array_values($state_district_map));

                                                    if (count($all_district_ids) > 0) {

                                                        $district_ids_str = implode(',', $all_district_ids);

                                                        $district_sql = "SELECT id, distName, stateId FROM dist WHERE id IN ($district_ids_str)";

                                                        $district_res = mysqli_query($con, $district_sql);

                                                        $districts = [];

                                                        while ($row = mysqli_fetch_assoc($district_res)) {

                                                            $districts[$row['stateId']][$row['id']] = $row['distName'];

                                                        }

                                                    } else {

                                                        $districts = [];

                                                    }

                        

                                                    foreach ($state_district_map as $state_id => $district_ids) {

                                                        $stateName = $states[$state_id];

                                                        if (!empty($district_ids)) {

                                                            foreach ($district_ids as $district_id) {

                                                                $districtName = $districts[$state_id][$district_id];

                                                                $locationValue = $state_id . '-' . $district_id;

                                                                echo '<div class="location-item mb-2">';

                                                                echo '<input type="hidden" name="locations[]" value="' . $locationValue . '">';

                                                                echo $stateName . ' - ' . $districtName;

                                                                echo '<button type="button" class="btn btn-sm btn-danger btn-remove-location">X</button>';

                                                                echo '</div>';

                                                            }

                                                        } else {

                                                            $locationValue = $state_id . '-0';

                                                            echo '<div class="location-item mb-2">';

                                                            echo '<input type="hidden" name="locations[]" value="' . $locationValue . '">';

                                                            echo $stateName . ' - All districts selected';

                                                            echo '<button type="button" class="btn btn-sm btn-danger btn-remove-location">X</button>';

                                                            echo '</div>';

                                                        }

                                                    }

                                                    ?>

                                                </div>

                                            </div>

                                        </div>

                                    </div>

                                </div>

                            </div>

                            <div class="form-group">

                                <button type="submit" class="btn btn-success text-sm-center mt-4" name="edit_submit">

                                    <i class="fa fa-save"></i> Save Changes

                                </button>

                            </div>

                        </form>



                    </div>

                </div>

                <?php }

                } elseif(isset($_GET["add_ad"])){?>

                <div class="card mt-3">

                    <h5 class="card-header text-dark  text-center font-weight-bold">Create An AD</h5>

                    <div class="card-body">

                        <form method="POST" action="" enctype="multipart/form-data">

                            <div class="row">

                                <div class="col-md-12 mb-2">

                                    <div class="from-group">

                                        <label for="adTitle">Enter AD Title</label>

                                        <input type="text" class="form-control" id="ad_title"

                                            placeholder="Enter class name" name="ad_title" required>

                                    </div>

                                </div>

                                <div class="col-md-4 mb-2">

                                    <div class="from-group">

                                        <label for="ad-img">Select AD Image</label>

                                        <input type="file" class="form-control" name="file" accept="image/*" required>

                                    </div>

                                </div>

                                <div class="col-md-4 mb-2">

                                    <div class="from-group">

                                        <label for="adUrl">Enter AD URl</label>

                                        <input type="text" class="form-control" placeholder="Enter AD Url" name="ad_url"

                                            required>

                                    </div>

                                </div>

                                <div class="col-md-4 mb-2">

                                    <div class="form-group">

                                        <label for="class">Select Class</label>

                                        <div class="custom-select" id="classSelect">

                                            <input type="text" name="ad_class_names" id="selectedClassNames"

                                                class="form-control" placeholder="Select classes" readonly>

                                            <input type="hidden" name="ad_class" id="selectedClassIds">

                                            <div class="checkboxes">

                                                <?php

                                                    $class_sql = mysqli_query($con, "SELECT * FROM class WHERE uploadedby = 'fssdf4543frts' AND cdisplay != 'disabled'");

                                                    while($class_row = mysqli_fetch_assoc($class_sql)){

                                                ?>

                                                <label>

                                                    <input type="checkbox" value="<?php echo $class_row['sid']; ?>"

                                                        data-name="<?php echo $class_row['sclass']; ?>">

                                                    <?php echo $class_row['sclass']; ?>

                                                </label>

                                                <br>

                                                <?php }?>

                                            </div>

                                        </div>

                                    </div>

                                </div>

                                <div class="col-md-12">

                                    <div class="ad-location-select">

                                        <div class="row">

                                            <div class="col-md-8 mb-2">

                                                <div class="row">

                                                    <div class="col-md-4 mb-2">

                                                        <label for="state">State</label>

                                                        <input type="hidden" name="state" id="state-id" value="">

                                                        <input type="text" list="state" class="form-control"

                                                            id="state-input" placeholder="Select from the list">

                                                        <datalist id="state">

                                                            <?php 

                                                                $sql = "SELECT id, name FROM state ORDER BY id ASC";

                                                                $res = mysqli_query($con, $sql);

                                                                while ($row = mysqli_fetch_assoc($res)) {

                                                            ?>

                                                            <option data-id="<?php echo $row['id']; ?>"

                                                                value="<?php echo $row['name']; ?>">

                                                                <?php echo $row['name']; ?></option>

                                                            <?php } ?>

                                                        </datalist>

                                                    </div>

                                                    <div class="col-md-5 mb-2">

                                                        <label for="district">District</label>

                                                        <input type="hidden" name="dist" id="district-id" value="">

                                                        <input type="text" list="district-list" class="form-control"

                                                            id="district-input" placeholder="Select from the list">

                                                        <datalist id="district-list"></datalist>

                                                    </div>

                                                    <div class="col-md-3 mb-2 d-flex align-items-end">

                                                        <button id="btn-add-location"

                                                            class="btn btn-primary btn-add">Add

                                                            Location</button>

                                                    </div>

                                                </div>

                                            </div>

                                            <div class="col-md-4 mb-2">

                                                <div id="preview-locations"

                                                    style="background: #f1f1f1;padding: 10px;border: 1px solid #1d7a85;border-radius: 7px;">

                                                </div>

                                            </div>

                                        </div>

                                    </div>



                                </div>

                            </div>

                            <div class="from-group">

                                <button type="submit" class="btn btn-success text-sm-center mt-4" name="submit">

                                    <i class="fa fa-plus"></i> Add AD

                                </button>

                            </div>

                        </form>

                    </div>

                </div>

                <?php } else{?>

                <div class="card mt-3 mb-3">

                    <div class="card-header">

                        <div class="row align-items-center">

                            <div class="col-md-6 col-4">

                                <h4 class="m-0 text-dark font-weight-bold"><i class="fas fa-ad"></i>&nbsp;Active AD

                                    List</h4>

                            </div>

                            <div class="col-md-6 col-8">

                                <div class="d-flex justify-content-end">

                                    <div class="filter-input">

                                        <div class="form-group">

                                            <input type="text" list="First" placeholder="Search AD By Name"

                                                class="form-control" id="FirstFilterValue">

                                            <datalist id="First">

                                                <?php 

                                                    $sql = "SELECT ad_title FROM ad WHERE ad_uploadedby = 'fssdf4543frts' AND ad_display !='disabled' ORDER BY ad_id ASC";

                                                    $res = mysqli_query($con,$sql);

                                                    while ($row = mysqli_fetch_assoc($res)) {

                                                ?>

                                                <option value="<?php echo $row['ad_title']; ?>">

                                                    <?php echo $row['ad_title']; ?></option>

                                                <?php } ?>

                                            </datalist>

                                        </div>

                                    </div>

                                    <div class="#">

                                        <button type="button" id="filter" class="btn btn-primary"> 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: 0;">

                                    <?php 

                                    for ($count = 0; $count < 4; $count++) {

                                        echo '<li>

                                            <div class="ph-item">

                                            <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>

                                            </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>

    document.addEventListener('DOMContentLoaded', (event) => {

        const selectDiv = document.getElementById('classSelect');

        const checkboxesDiv = selectDiv.querySelector('.checkboxes');

        const inputFieldNames = document.getElementById('selectedClassNames');

        const inputFieldIds = document.getElementById('selectedClassIds');

        let selectedValues = [];

        let selectedNames = [];



        selectDiv.addEventListener('click', () => {

            selectDiv.classList.toggle('open');

        });



        checkboxesDiv.addEventListener('change', (event) => {

            const checkbox = event.target;

            const value = checkbox.value;

            const name = checkbox.getAttribute('data-name');



            if (checkbox.checked) {

                selectedValues.push(value);

                selectedNames.push(name);

            } else {

                selectedValues = selectedValues.filter(item => item !==

                    value);

                selectedNames = selectedNames.filter(item => item !==

                    name);

            }



            inputFieldNames.value = selectedNames.join(', ');

            inputFieldIds.value = selectedValues.join(', ');

        });



        document.addEventListener('click', (event) => {

            if (!selectDiv.contains(event.target)) {

                selectDiv.classList.remove('open');

            }

        });

    });

    </script>





    <script>

    $(document).ready(function() {

        $('#edit-state-input').on('change', function() {

            var state = $(this).val();

            if (state !== '') {

                $.ajax({

                    url: 'fetch-state-id.php',

                    type: 'POST',

                    data: {

                        state: state

                    },

                    success: function(data) {

                        $('#edit-state-id').val(data);

                    },

                    error: function() {

                        alert('Error fetching state ID. Please try again.');

                    }

                });



                $.ajax({

                    url: 'fetch-district.php',

                    type: 'POST',

                    data: {

                        state: state

                    },

                    success: function(data) {

                        $('#district-list').html(data);

                    },

                    error: function() {

                        alert('Error loading districts. Please try again.');

                    }

                });

            } else {

                $('#edit-state-id').val('');

                $('#district-list').html('');

            }

        });



        $('#edit-district-input').on('change', function() {

            var districtName = $(this).val();

            var districtOption = $('#district-list option').filter(function() {

                return this.value === districtName;

            });



            if (districtOption.length > 0) {

                $('#edit-district-id').val(districtOption.data('id'));

            } else {

                $('#edit-district-id').val('');

            }

        });



        $('#edit-btn-add-location').on('click', function(e) {

            e.preventDefault();

            var stateId = $('#edit-state-id').val();

            var districtId = $('#edit-district-id').val();

            var stateName = $('#edit-state-input').val();

            var districtName = $('#edit-district-input').val();



            if (stateId && (districtId || !districtName)) {

                var locationValue = stateId + '-' + (districtId ? districtId : '0');

                var locationHtml = '<div class="location-item mb-2">' +

                    '<input type="hidden" name="locations[]" value="' + locationValue + '">' +

                    stateName + (districtName ? ' - ' + districtName : '') +

                    ' <button type="button" class="btn btn-sm btn-danger btn-remove-location">X</button></div>';



                $('#edit-preview-locations').append(locationHtml);

                $('#edit-preview-locations').css('display', 'block');



                $('#edit-state-input').val('');

                $('#edit-state-id').val('');

                $('#edit-district-input').val('');

                $('#edit-district-id').val('');

            } else {

                alert(

                    'Please select a valid state. District selection is optional but required if provided.'

                );

            }

        });



        $(document).on('click', '.btn-remove-location', function() {

            $(this).closest('.location-item').remove();



            if ($('#edit-preview-locations').children().length === 0) {

                $('#edit-preview-locations').css('display', 'none');

            }

        });



        $('#edit-preview-locations').css('display', 'block');

    });

    </script>



    <script>

    $(document).ready(function() {

        // Fetch and set state ID and districts

        $('#state-input').on('change', function() {

            var state = $(this).val();

            if (state !== '') {

                // Fetch state ID

                $.ajax({

                    url: 'fetch-state-id.php',

                    type: 'POST',

                    data: {

                        state: state

                    },

                    success: function(data) {

                        $('#state-id').val(

                            data); // Set the hidden input field with the fetched state ID

                    },

                    error: function() {

                        alert('Error fetching state ID. Please try again.');

                    }

                });



                // Fetch districts

                $.ajax({

                    url: 'fetch-district.php',

                    type: 'POST',

                    data: {

                        state: state

                    },

                    success: function(data) {

                        $('#district-list').html(

                            data); // Populate the district datalist with the fetched data

                    },

                    error: function() {

                        alert('Error loading districts. Please try again.');

                    }

                });

            } else {

                $('#state-id').val(''); // Clear the hidden input field if no state is selected

                $('#district-list').html(''); // Clear the district list if no state is selected

            }

        });



        // Set district ID based on selection

        $('#district-input').on('change', function() {

            var districtName = $(this).val();

            var districtOption = $('#district-list option').filter(function() {

                return this.value === districtName;

            });



            if (districtOption.length > 0) {

                $('#district-id').val(districtOption.data(

                    'id')); // Set the hidden input field with the district ID

            } else {

                $('#district-id').val(''); // Clear the hidden input if the selection is not valid

            }

        });



        // Add location to preview

        $('#btn-add-location').on('click', function(e) {

            e.preventDefault();

            var stateId = $('#state-id').val();

            var districtId = $('#district-id').val();

            var stateName = $('#state-input').val();

            var districtName = $('#district-input').val();



            if (stateId && (districtId || !districtName)) {

                var locationValue = stateId + '-' + (districtId ? districtId : '0');

                var locationHtml = '<div class="location-item mb-2">' +

                    '<input type="hidden" name="locations[]" value="' + locationValue + '">' +

                    stateName + (districtName ? ' - ' + districtName : '') +

                    ' <button type="button" class="btn btn-sm btn-danger btn-remove-location">X</button></div>';



                $('#preview-locations').append(locationHtml);

                $('#preview-locations').css('display', 'block'); // Show preview locations container



                // Clear inputs

                $('#state-input').val('');

                $('#state-id').val('');

                $('#district-input').val('');

                $('#district-id').val('');

            } else {

                alert(

                    'Please select a valid state. District selection is optional but required if provided.'

                );

            }

        });



        // Remove location from preview

        $(document).on('click', '.btn-remove-location', function() {

            $(this).closest('.location-item').remove();



            // Hide preview locations if empty

            if ($('#preview-locations').children().length === 0) {

                $('#preview-locations').css('display', 'none');

            }

        });



        // Hide initial preview location

        $('#preview-locations').css('display', 'none');

    });

    </script>



    <script>

    //dropdown TWO filter Start//

    $(document).ready(function() {

        var load_filter_flag = '';

        var FirstFilterValue = '';

        var SecondFilterValue = '';

        $("#filter").click(function() {

            FirstFilterValue = $('#FirstFilterValue').val();

            SecondFilterValue = $('#SecondFilterValue').val();

            load_filter_flag = 0;

            if (FirstFilterValue != '' || SecondFilterValue != '') {

                //alert(name);

                $.ajax({

                    url: 'view-ad-Ajax.php',

                    type: 'POST',

                    data: {

                        FirstFilterValue: FirstFilterValue,

                        SecondFilterValue: SecondFilterValue,

                        start: load_filter_flag

                    },

                    success: function(result) {

                        $('#full-table').hide();

                        $('#filter-table').show();

                        $('#filter-table-data').html(result);

                        load_filter_flag += 10;

                    },

                    complete: function(data) {

                        /* Hide loader container */

                        $("#loader").hide();

                    }

                });

            } else {

                alert('Plz Select an Option');

                $('#full-table').show();

                $('#filter-table').hide();

            }

        });



        function loadMoreFilter(start) {

            console.log('Filter' + start);

            if (load_filter_flag > 0) {

                //alert(name);

                $.ajax({

                    url: 'view-ad-Ajax.php',

                    type: 'POST',

                    data: {

                        FirstFilterValue: FirstFilterValue,

                        SecondFilterValue: SecondFilterValue,

                        start: start

                    },

                    success: function(result) {

                        $('#filter-table-data').append(result);

                        load_filter_flag += 10;

                    }

                });

            }

        }

        // Scroll Loading of Full Data //

        var load_flag = 0;

        loadMore(load_flag);



        function loadMore(start) {

            //console.log('total'+start);

            $.ajax({

                url: 'view-ad-Ajax.php',

                type: 'POST',

                data: 'start=' + start,

                success: function(result) {

                    $('#full-table-data').append(result);

                    load_flag += 10;

                },

                complete: function(data) {

                    /* Hide loader container */

                    $("#loader").hide();

                }

            });

        }



        $('#inner-body').scroll(function() {

            if ($('#inner-body').scrollTop() >= $(document).height() - $('#inner-body').height()) {

                //console.log('call');

                if (load_filter_flag > 0) {

                    loadMoreFilter(load_filter_flag);

                } else {

                    loadMore(load_flag);

                }

            }

        });

    });

    </script>





</body>



</html>





<?php

if (isset($_POST['submit'])) {

    // Validate required fields

    $ad_title = mysqli_real_escape_string($con, $_POST['ad_title']);

    $ad_url = mysqli_real_escape_string($con, $_POST['ad_url']);

    $ad_class = mysqli_real_escape_string($con, $_POST['ad_class']);



    // Handle file upload

    $upload_dir = '../upload/ad/';

    $allowed_types = ['jpg', 'jpeg', 'png', 'gif'];

    $file_name = $_FILES['file']['name'];

    $file_tmp = $_FILES['file']['tmp_name'];

    $file_size = $_FILES['file']['size'];

    $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));



    // Check if file type is allowed

    if (in_array($file_ext, $allowed_types)) {

        $new_file_name = uniqid() . '.' . $file_ext;

        $upload_file = $upload_dir . $new_file_name;



        if (move_uploaded_file($file_tmp, $upload_file)) {

            // File uploaded successfully

            $locations = isset($_POST['locations']) ? implode(',', $_POST['locations']) : '';



            // Insert data into database

            $sql = "INSERT INTO ad (ad_title, ad_url, ad_class, ad_location, ad_img, ad_uploadedby, ad_creatdate, ad_recycle) VALUES ('$ad_title', '$ad_url', '$ad_class', '$locations', '$new_file_name', '$_SESSION[uref]', '$currentTime', '1')";

            if (mysqli_query($con, $sql)) {

                ?>

<script>

window.location = 'view-ad.php';

</script>

<?php

            } else {

                echo "Error: " . $sql . "<br>" . mysqli_error($con);

            }

        } else {

            echo "Failed to upload file.";

        }

    } else {

        echo "Invalid file type.";

    }

}

?>



<?php

if (isset($_POST['edit_submit'])) {

    $ad_id = $_GET['edit_id'];

    $ad_title = mysqli_real_escape_string($con, $_POST['edit_ad_title']);

    $ad_url = mysqli_real_escape_string($con, $_POST['edit_ad_url']);

    $ad_class = mysqli_real_escape_string($con, $_POST['edit_ad_class']);

    $locations = isset($_POST['locations']) ? implode(',', $_POST['locations']) : '';

    $existing_image = $_POST['existing_image'];



    $upload_dir = '../upload/ad/';

    $allowed_types = ['jpg', 'jpeg', 'png', 'gif'];

    $file_name = $_FILES['edit_file']['name'];

    $file_tmp = $_FILES['edit_file']['tmp_name'];

    $file_size = $_FILES['edit_file']['size'];

    $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

    $new_file_name = $existing_image;



    if (!empty($file_name)) {

        if (in_array($file_ext, $allowed_types)) {

            $new_file_name = uniqid() . '.' . $file_ext;

            $upload_file = $upload_dir . $new_file_name;

            if (move_uploaded_file($file_tmp, $upload_file)) {

                if (file_exists($upload_dir . $existing_image)) {

                    unlink($upload_dir . $existing_image);

                }

            } else {

                echo "Failed to upload file.";

            }

        } else {

            echo "Invalid file type.";

        }

    }



    $sql = "UPDATE ad SET ad_title = '$ad_title', ad_url = '$ad_url', ad_class = '$ad_class', ad_location = '$locations', ad_img = '$new_file_name' WHERE ad_id = '$ad_id'";

    if (mysqli_query($con, $sql)) {

        ?>

<script>

window.location = 'view-ad.php';

</script>

<?php

    } else {

        echo "Error: " . $sql . "<br>" . mysqli_error($con);

    }

}

?>









<?php

if (isset($_GET['del_id'])) {

    $del_id = mysqli_real_escape_string($con, $_GET['del_id']);

    $delete_sql = "UPDATE ad SET ad_display = 'disabled' WHERE ad_id = '$del_id'";



    if (mysqli_query($con, $delete_sql)) {

        ?>

<script>

window.location = 'view-ad.php';

</script>

<?php

    } else {

        ?>

<script>

alert('OOPS !!!!');

setTimeout(() => {

    window.location = 'view-ad.php';

}, 1200);

</script>

<?php

    }

}

?>