<?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();
    }
?>

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

<head>
    <?php include "include/meta.php"; ?>
    <?php include "include/css.php"; ?>
    <?php include "include/php-functions.php"; ?>
    <script src="https://cdn.ckeditor.com/4.6.2/standard-all/ckeditor.js"></script>
</head>
<style>
#ck-img-preview img {
    max-width: 100%;
    height: auto;
}
</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"];
                    $edit_run = mysqli_query($con, "SELECT * FROM notice WHERE admin_ref = '$_SESSION[uref_code]' AND notice_id = '$_GET[edit_id]'");
                    
                    if($edit_row = mysqli_fetch_assoc($edit_run)){

                        $class_sql = mysqli_query($con, "SELECT * FROM class WHERE sid = '$edit_row[notice_class]'");
                        if($class_row = mysqli_fetch_assoc($class_sql)){
                            $class_name = $class_row["sclass"];
                        }else{
                            $class_name = "";
                        }
                        $sub_class_sql = mysqli_query($con, "SELECT * FROM sub_class WHERE sc_id = '$edit_row[notice_sub_class]'");
                        if($sub_class_row = mysqli_fetch_assoc($sub_class_sql)){
                            $sub_class_name = $sub_class_row["sc_name"];
                        }else{
                            $sub_class_name = "";
                        }
                        $sub_class_year_sql = mysqli_query($con, "SELECT * FROM class_year WHERE cy_id = '$edit_row[notice_year]'");
                        if($sub_class_year_row = mysqli_fetch_assoc($sub_class_year_sql)){
                            $sub_class_year_name = $sub_class_year_row["cy_name"];
                        }else{
                            $sub_class_year_name = "";
                        }
                    ?>
                <div class="card mt-3">
                    <h5 class="card-header text-dark  text-center font-weight-bold">Edit Organization Details</h5>
                    <div class="card-body">
                        <form class="user" method="post" enctype="multipart/form-data">
                            <div class="row mb-3">
                                <div class="col-md-12 mb-2">
                                    <label for="organizationName" class="">Notice Title</label>
                                    <input type="text" class="form-control" name="title"
                                        value="<?php echo $edit_row["notice_title"];?>" required>
                                </div>
                                <div class="col-md-6 mb-2">
                                    <label for="organizationName" class="">Notice Date</label>
                                    <input type="date" class="form-control" name="notice_date"
                                        value="<?php echo $edit_row["notice_date"];?>">
                                </div>
                                <div class="col-md-6 mb-2">
                                    <label for="notice_for">Category</label>
                                    <select name="notice_for" class="form-control mb-2" id="cat-select" required>
                                        <option value="<?php echo $edit_row["notice_for"];?>">
                                            <?php echo $edit_row["notice_for"];?></option>
                                        <option value="All">All</option>
                                        <option value="Teacher">Teacher</option>
                                        <option value="Student">Student</option>
                                    </select>
                                </div>
                                <div class="col-md-12 mb-2 <?php if($edit_row["notice_for"] != "Student"){ echo "d-none";}?>"
                                    id="select-student">
                                    <div class="row">
                                        <div class="col-md-4 mb-2">
                                            <div class="from-group">
                                                <label>Select Class Name</label>
                                                <select name="notice_class" class="form-control" id="class"
                                                    onchange="fetchSubClasses(this.value)">
                                                    <option value="<?php echo $edit_row["notice_class"];?>">
                                                        <?php echo $class_name;?></option>
                                                    <?php
                                                        // Assuming you have an active database connection in $con
                                                        $run = mysqli_query($con, "SELECT sclass FROM class WHERE uploadedby = '$_SESSION[uref_code]'");

                                                        if ($rows = mysqli_fetch_assoc($run)) {
                                                            $class_ids = explode(',', $rows["sclass"]);
    
                                                            foreach ($class_ids as $class_id) {
                                                                $class_id = trim($class_id); // Remove any extra whitespace
                                                                $details_query = mysqli_query($con, "SELECT * FROM class WHERE sid = '$class_id' AND uploadedby = 'fssdf4543frts'");
        
                                                                while ($details_row = mysqli_fetch_assoc($details_query)) {
                                                                    echo "<option value='{$details_row['sid']}'>{$details_row['sclass']}</option>";
                                                                }
                                                            }
                                                        }       
                                                    ?>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-4 mb-2">
                                            <div class="from-group">
                                                <label>Select Sub Class Name</label>
                                                <select name="notice_sub_class" class="form-control"
                                                    id="sub_class_select" onchange="fetchClassYear(this.value)">
                                                    <option value="<?php echo $edit_row["notice_sub_class"];?>">
                                                        <?php echo $sub_class_name;?></option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-4 mb-2">
                                            <div class="from-group">
                                                <label>Select Semister</label>
                                                <select name="notice_year" class="form-control" id="class_year_select">
                                                    <option value="<?php echo $edit_row["notice_year"];?>">
                                                        <?php echo $sub_class_year_name;?></option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="col-md-12 mb-2">
                                    <label for="about">Notice Script</label>
                                    <textarea class="form-control ckeditor" name="about" id="content" rows="3">
                                    <?php echo $edit_row["notice_script"];?>
                                    </textarea>
                                </div>
                            </div>
                            <div class="row mb-3">
                                <div class="col-md-6 mb-2">
                                    <label for="notice">Notice Image</label>
                                    <input type="file" name="notice" id="img" class="form-control"
                                        placeholder="Upload Image">
                                    <input type="hidden" name="noticeOld"
                                        value="<?php echo $edit_row["notice_image"];?>">
                                </div>
                                <div class="col-md-6 mb-2">
                                    <a href="<?php echo $edit_row["notice_image"];?>" target="_blank">
                                        <img src="<?php echo $edit_row["notice_image"];?>" class="img-fluid"
                                            style="height:200px;" alt="">
                                    </a>
                                </div>
                            </div>

                            <button type="submit" class="btn btn-success" name="edit_notice">
                                UPDATE
                            </button>

                            <a href="view-notice.php" class="btn btn-warning"> <i class="fas fa-ban"></i>
                                Cancel
                            </a>
                        </form>
                    </div>
                </div>
                <?php }
                } elseif(isset($_GET["view_id"])){
                    $view_id = $_GET["view_id"];
                    $view_run = mysqli_query($con, "SELECT * FROM notice WHERE admin_ref = '$_SESSION[uref_code]' AND notice_id = '$_GET[view_id]'");
                    
                    if($view_row = mysqli_fetch_assoc($view_run)){

                        $class_sql = mysqli_query($con, "SELECT * FROM class WHERE sid = '$view_row[notice_class]'");
                        if($class_row = mysqli_fetch_assoc($class_sql)){
                            $class_name = $class_row["sclass"];
                        }else{
                            $class_name = "";
                        }
                        $sub_class_sql = mysqli_query($con, "SELECT * FROM sub_class WHERE sc_id = '$view_row[notice_sub_class]'");
                        if($sub_class_row = mysqli_fetch_assoc($sub_class_sql)){
                            $sub_class_name = $sub_class_row["sc_name"];
                        }else{
                            $sub_class_name = "";
                        }
                        $sub_class_year_sql = mysqli_query($con, "SELECT * FROM class_year WHERE cy_id = '$view_row[notice_year]'");
                        if($sub_class_year_row = mysqli_fetch_assoc($sub_class_year_sql)){
                            $sub_class_year_name = $sub_class_year_row["cy_name"];
                        }else{
                            $sub_class_year_name = "";
                        }
                    ?>
                <div class="card mt-3">
                    <h5 class="card-header text-dark  text-center font-weight-bold">
                        <?php echo $view_row["notice_title"];?></h5>
                    <div class="card-body">
                        <div class="notice-image">
                            <img src="<?php echo $view_row["notice_image"];?>" class="img-fluid" alt="">
                        </div>
                        <div class="notice-preiew">
                            <div id="ck-img-preview"><strong>Notice Details :
                                </strong><?php echo $view_row["notice_script"];?>
                            </div>
                            <p><strong>Notice Date : </strong><?php echo $view_row["notice_date"];?></p>
                            <p><strong>Notice Applicable for : </strong><?php echo $view_row["notice_for"];?></p>
                            <?php if($view_row["notice_for"] == "Student"){?>
                            <?php if(!empty($view_row["notice_class"])){?>
                            <p><strong>Notice Class : </strong><?php echo $class_name;?></p>
                            <?php } elseif(!empty($view_row["notice_sub_class"])){?>
                            <p><strong>Notice SubClass : </strong><?php echo $sub_class_name;?></p>
                            <?php } elseif(!empty($view_row["notice_year"])){?>
                            <p><strong>Notice Semister : </strong><?php echo $sub_class_year_name;?></p>
                            <?php } }?>
                            <p><strong>Notice Cteate Date : </strong><?php echo $view_row["notice_createdate"];?></p>
                        </div>

                        <a href="view-notice.php" class="btn btn-warning text-white"> <i class="fas fa-ban"></i>
                            Cancel
                        </a>
                    </div>
                </div>
                <?php }
                } elseif(isset($_GET["add_notice"])){?>
                <div class="card mt-3">
                    <h5 class="card-header text-dark  text-center font-weight-bold">Add Notice</h5>
                    <div class="card-body">
                        <form method="POST" enctype="multipart/form-data">
                            <div class="row mb-3">
                                <div class="col-md-12 mb-2">
                                    <label for="organizationName" class="">Notice Title</label>
                                    <input type="text" class="form-control" name="title"
                                        placeholder="Enter Notice Title" required>
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label for="organizationName" class="">Notice Date</label>
                                    <input type="date" class="form-control" name="notice_date" required>
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label for="notice">Notice Image</label>
                                    <input type="file" name="notice" id="img" class="form-control"
                                        placeholder="Upload Image">
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label for="notice_for">Category</label>
                                    <select name="notice_for" class="form-control mb-2" id="cat-select" required>
                                        <option value="">Select From List</option>
                                        <option value="All">All</option>
                                        <option value="Teacher">Teacher</option>
                                        <option value="Student">Student</option>
                                    </select>
                                </div>
                                <div class="col-md-12 mb-2 d-none" id="select-student">
                                    <div class="row">
                                        <div class="col-md-4 mb-2">
                                            <div class="from-group">
                                                <label>Select Class Name</label>
                                                <select name="notice_class" class="form-control" id="class"
                                                    onchange="fetchSubClasses(this.value)">
                                                    <option value="">Select Class</option>
                                                    <?php
                                                        // Assuming you have an active database connection in $con
                                                        $run = mysqli_query($con, "SELECT sclass FROM class WHERE uploadedby = '$_SESSION[uref_code]'");

                                                        if ($rows = mysqli_fetch_assoc($run)) {
                                                            $class_ids = explode(',', $rows["sclass"]);
    
                                                            foreach ($class_ids as $class_id) {
                                                                $class_id = trim($class_id); // Remove any extra whitespace
                                                                $details_query = mysqli_query($con, "SELECT * FROM class WHERE sid = '$class_id' AND uploadedby = 'fssdf4543frts'");
        
                                                                while ($details_row = mysqli_fetch_assoc($details_query)) {
                                                                    echo "<option value='{$details_row['sid']}'>{$details_row['sclass']}</option>";
                                                                }
                                                            }
                                                        }       
                                                    ?>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-4 mb-2">
                                            <div class="from-group">
                                                <label>Select Sub Class Name</label>
                                                <select name="notice_sub_class" class="form-control"
                                                    id="sub_class_select" onchange="fetchClassYear(this.value)">
                                                    <option value="">Select Sub Class</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-4 mb-2">
                                            <div class="from-group">
                                                <label>Select Semister</label>
                                                <select name="notice_year" class="form-control" id="class_year_select">
                                                    <option value="">Select Selister</option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="col-md-12 mb-2">
                                    <label for="about">Notice Script</label>
                                    <textarea class="form-control ckeditor" name="about" id="content"
                                        rows="3"></textarea>
                                </div>
                            </div>
                            <div class="mt-4">
                                <button type="submit" class="btn btn-success text-sm-center" name="submit">
                                    <i class="fa fa-plus"></i> Add Notice
                                </button>
                                <a href="view-notice.php" class="btn btn-warning text-white">
                                    <i class="fa fa-arrow-left"></i> Back
                                </a>
                            </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="text-gray-800">Notice List</h4>
                            </div>
                            <div class="col-md-6 col-8 d-flex justify-content-end">
                                <!--<div>
                                    <a class="btn btn-primary" href="view-notice.php?add_notice"><i
                                            class="fa fa-bell"></i> Add
                                        Notice</a>
                                </div>-->
                                <div class="d-flex">
                                    <div style="margin-left:18px">
                                        <div class="form-group">
                                            <input type="text" list="First" class="form-control" id="FirstFilterValue">
                                            <datalist id="First">
                                                <option value="">Search Notice</option>
                                                <?php 
                                                    $sql = "SELECT notice_title FROM notice  WHERE notice_recycle = '0' ORDER BY notice_id DESC";
                                                    $res = mysqli_query($con,$sql);
                                                    while ($row = mysqli_fetch_assoc($res)) {
                                                ?>
                                                <option value="<?php echo $row['notice_title']; ?>">
                                                    <?php echo $row['notice_title']; ?></option>
                                                <?php } ?>
                                            </datalist>
                                        </div>
                                        <input type="hidden" class="form-control" value="" id="SecondFilterValue">
                                    </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-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>
    CKEDITOR.replace('content', {
        height: 300,
        filebrowserUploadUrl: "upload.php"
    });
    </script>

    <script>
    document.getElementById('cat-select').addEventListener('change', function() {
        var selectStudentDiv = document.getElementById('select-student');
        if (this.value === 'Student') {
            selectStudentDiv.classList.remove('d-none');
            selectStudentDiv.classList.add('d-block');
        } else {
            selectStudentDiv.classList.remove('d-block');
            selectStudentDiv.classList.add('d-none');
        }
    });
    </script>

    <script>
    function fetchSubClasses(classId) {
        if (classId === "") {
            document.getElementById('sub_class_select').innerHTML = '<option value="">Select Sub Class</option>';
            return;
        }

        const xhr = new XMLHttpRequest();
        xhr.open("POST", "fetch_sub_classes.php", true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4 && xhr.status === 200) {
                const subClasses = JSON.parse(xhr.responseText);
                let options = '<option value="">Select Sub Class</option>';
                subClasses.forEach(subClass => {
                    options += `<option value="${subClass.sc_id}">${subClass.sc_name}</option>`;
                });
                document.getElementById('sub_class_select').innerHTML = options;
            }
            if (xhr.readyState === 4 && xhr.status === 200) {
                const classYears = JSON.parse(xhr.responseText);
                let options = '<option value="">Select Sub Class Year</option>';
                document.getElementById('class_year_select').innerHTML = options;
            }
        };
        xhr.send("class_id=" + classId);
    }

    function fetchClassYear(subClassId) {
        if (subClassId === "") {
            document.getElementById('class_year_select').innerHTML = '<option value="">Select Sub Class Year</option>';
            return;
        }

        const xhr = new XMLHttpRequest();
        xhr.open("POST", "fetch_class_years.php", true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4 && xhr.status === 200) {
                const classYears = JSON.parse(xhr.responseText);
                let options = '<option value="">Select Sub Class Year</option>';
                classYears.forEach(classYear => {
                    options += `<option value="${classYear.cy_id}">${classYear.cy_name}</option>`;
                });
                document.getElementById('class_year_select').innerHTML = options;
            }
        };
        xhr.send("sub_class_id=" + subClassId);
    }

    document.getElementById('sub_class_select').addEventListener('change', function() {
        const subClassValue = this.value;
        if (subClassValue) {
            document.getElementById('class_year_container').style.display = 'block';
            document.getElementById('class_year_select').disabled = false;
        } else {
            document.getElementById('class_year_container').style.display = 'none';
            document.getElementById('class_year_select').disabled = true;
        }
    });
    </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-notice-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-notice-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-notice-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'])) {
    $title = mysqli_real_escape_string($con, strip_tags($_POST['title']));
    $notice_date = mysqli_real_escape_string($con, strip_tags($_POST['notice_date']));
    $notice_for = mysqli_real_escape_string($con, strip_tags($_POST['notice_for']));
    $notice_class = mysqli_real_escape_string($con, strip_tags($_POST['notice_class']));
    $notice_sub_class = mysqli_real_escape_string($con, strip_tags($_POST['notice_sub_class']));
    $notice_year = mysqli_real_escape_string($con, strip_tags($_POST['notice_year']));
    $about = $_POST['about'];

    $admin_ref = $_SESSION['uref_code'];

    if($notice_for == "All"){
        $notice_class = "";
        $notice_sub_class = "";
        $notice_year = "";
    }
    if($notice_for == "Teacher"){
        $notice_class = "";
        $notice_sub_class = "";
        $notice_year = "";
    }

    // Handle file upload
    $noticepath = "";
    if (!empty($_FILES["notice"]["name"])) {
            $target_dir = "../upload/notice/";
            $imageFileType = strtolower(pathinfo($_FILES["notice"]["name"], PATHINFO_EXTENSION));
            
            // Generate a unique file name
            $newFileName = uniqid() . '_' . time() . '.' . $imageFileType;
            $target_file = $target_dir . $newFileName;
            $uploadOk = 1;
        
            // Check if image file is an actual image or fake image
            $check = getimagesize($_FILES["notice"]["tmp_name"]);
            if ($check !== false) {
                $uploadOk = 1;
            } else {
                $uploadOk = 0;
            }
        
            // Check file size (5MB maximum)
            if ($_FILES["notice"]["size"] > 5000000) {
                $uploadOk = 0;
            }
        
            // Allow certain file formats
            if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") {
                $uploadOk = 0;
            }
        
            // Check if $uploadOk is set to 0 by an error
            if ($uploadOk == 0) {
                echo "<script>alert('Sorry, your file was not uploaded.');</script>";
            } else {
                // if everything is ok, try to upload file
                if (move_uploaded_file($_FILES["notice"]["tmp_name"], $target_file)) {
                    $noticepath = $target_file;
                } else {
                    echo "<script>alert('Sorry, there was an error uploading your file.');</script>";
                }
            }
    }        

    $ins_sql = "INSERT INTO notice (notice_title, notice_script, notice_image, notice_for, notice_class, notice_sub_class, notice_year, notice_date, notice_createdate, admin_ref, notice_recycle) VALUES ('$title', '$about', '$noticepath', '$notice_for', '$notice_class', '$notice_sub_class', '$notice_year', '$notice_date', '$currentTime', '$admin_ref', '1')";

    if (mysqli_query($con, $ins_sql)) {
        echo "<script>window.location = 'view-notice.php';</script>";
    } else {
        echo "<script>
            alert('OOPS !!!!');
            setTimeout(() => {
                window.location = 'view-notice.php?add_notice';
            }, 1200);
        </script>";
    }
}
?>


<?php
if(isset($_POST['edit_notice'])){
    $title = mysqli_real_escape_string($con, strip_tags($_POST['title']));
    $notice_date = mysqli_real_escape_string($con, strip_tags($_POST['notice_date']));
    $notice_for = mysqli_real_escape_string($con, strip_tags($_POST['notice_for']));
    $notice_class = mysqli_real_escape_string($con, strip_tags($_POST['notice_class']));
    $notice_sub_class = mysqli_real_escape_string($con, strip_tags($_POST['notice_sub_class']));
    $notice_year = mysqli_real_escape_string($con, strip_tags($_POST['notice_year']));
    $about = $_POST['about'];

    $admin_ref = $_SESSION['uref_code'];

    if($notice_for == "All"){
        $notice_class = "";
        $notice_sub_class = "";
        $notice_year = "";
    }
    if($notice_for == "Teacher"){
        $notice_class = "";
        $notice_sub_class = "";
        $notice_year = "";
    }

    // Handle file upload
    $noticepath = "";
    if (!empty($_FILES["notice"]["name"])) {
        $target_dir = "../upload/notice/";
        $imageFileType = strtolower(pathinfo($_FILES["notice"]["name"], PATHINFO_EXTENSION));
        
        // Generate a unique file name
        $newFileName = uniqid() . '_' . time() . '.' . $imageFileType;
        $target_file = $target_dir . $newFileName;
        $uploadOk = 1;
    
        // Check if image file is an actual image or fake image
        $check = getimagesize($_FILES["notice"]["tmp_name"]);
        if ($check !== false) {
            $uploadOk = 1;
        } else {
            $uploadOk = 0;
        }
    
        // Check file size (5MB maximum)
        if ($_FILES["notice"]["size"] > 5000000) {
            $uploadOk = 0;
        }
    
        // Allow certain file formats
        if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") {
            $uploadOk = 0;
        }
    
        // Check if $uploadOk is set to 0 by an error
        if ($uploadOk == 0) {
            echo "<script>alert('Sorry, your file was not uploaded.');</script>";
        } else {
            // if everything is ok, try to upload file
            if (move_uploaded_file($_FILES["notice"]["tmp_name"], $target_file)) {
                unlink("$_POST[noticeOld]");
                $noticepath = $target_file;
            } else {
                echo "<script>alert('Sorry, there was an error uploading your file.');</script>";
            }
        }
    }  else{
        $noticepath = $_POST["noticeOld"];
    }

    $up_sql = "UPDATE notice SET notice_title = '$title', notice_for = '$notice_for', notice_class = '$notice_class', notice_date = '$notice_date', notice_sub_class = '$notice_sub_class', notice_year = '$notice_year',  notice_script = '$about', notice_image = '$noticepath' WHERE notice_id = '$_GET[edit_id]'";

    if(mysqli_query($con, $up_sql)){
        ?>
<script>
alert('Successfully Updated');
window.location = 'view-notice.php';
</script>
<?php
    }
    else{
        ?>
<script>
alert('OOPS !!!!');
setTimeout(() => {
    window.location = 'view-notice.php?edit_id=<?php echo $_GET["edit_id"]; ?>';
}, 1200);
</script>
<?php
    }
} 
?>

<?php
if ( isset($_GET["del_id"]) ) {
$disable_sql = "UPDATE notice SET notice_recycle = '1' WHERE notice_id = '$_GET[del_id]'";
    if ( mysqli_query($con, $disable_sql) ) {
        ?>
<script>
window.location = "view-notice.php";
</script>
<?php
    } else {
        ?>
<script>
alert('OOPS !!!!');
setTimeout(() => {
    window.location = 'view-notice.php';
}, 1200);
</script>
<?php
    }
}
?>