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

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

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

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

<head>
    <?php include "include/meta.php"; ?>
    <?php include "include/css.php"; ?>
    <?php include "include/php-functions.php"; ?>
    <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">
            <?php if(isset($_GET["college"])){
                $college_id = $_GET["college"];
                $college_sql = mysqli_query($con, "SELECT * FROM users where utype = 'College' AND uid = '$college_id'");
                if($college_row = mysqli_fetch_assoc($college_sql)){
                    $college_name = $college_row["uname"];
                }
                ?>
            <div class="container-fluid">
                <div class="card">
                    <div class="card-header">
                        <h5 class="m-0">Entrance For <?php echo $college_name;?></h5>
                    </div>
                    <div class="card-body">
                        <?php
                        $Entrance_sql = mysqli_query($con, "SELECT * FROM data WHERE data_catagory = 'cEntrance' AND data_up_for = '$college_id' ");
                        if(mysqli_num_rows($Entrance_sql)>0){
                            $Entrance_row = mysqli_fetch_assoc($Entrance_sql);
                            ?>
                        <form action="" method="POST">
                            <label for="Entrance">Edit College Entrance:</label>
                            <textarea class="form-control ckeditor" name="Entrance" id="content"
                                rows="3"><?php echo $Entrance_row["data_long_des"];?></textarea>
                            <button type="submit" class="btn btn-success btn-user m-2" name="edit"><i
                                    class="fa fa-edit"></i> UPDATE DETAILS
                            </button>
                        </form>
                        <?php
                        } else{
                            ?>
                        <form action="" method="POST">
                            <label for="Entrance">Enter College Entrance:</label>
                            <textarea class="form-control ckeditor" name="Entrance" id="content"
                                placeholder="Enter Entrance Details.." rows="3"></textarea>
                            <button type="submit" class="btn btn-success btn-user m-2" name="submit"><i
                                    class="fa fa-edit"></i> Submit DETAILS
                            </button>
                        </form>
                        <?php
                        }
                        ?>
                    </div>
                    <div class="card-header mt-3">
                        <h5 class="m-0">Entrance List</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <?php 
                            // Fetch already selected values
                            $selected_sql = mysqli_query($con, "SELECT data_seo_title FROM data WHERE data_catagory = 'cEntrance' AND data_up_for = '$college_id'");
                            $selected_row = mysqli_fetch_assoc($selected_sql);
                            $selected_list = !empty($selected_row['data_seo_title']) ? explode(',', $selected_row['data_seo_title']) : []; // Convert to array or empty array if null

                            $entList_sql = mysqli_query($con, "SELECT * FROM data WHERE data_catagory = 'entrance' AND data_recycle = '1' ORDER BY data_sl_no DESC");
                            
                            while($entList_row = mysqli_fetch_assoc($entList_sql)){
                                $data_sl_no = $entList_row["data_sl_no"];
                                $checked = in_array($data_sl_no, $selected_list) ? "checked" : ""; // Check if already selected
                            ?>
                            <div class="col-md-3 m-2">
                                <div class="card p-2 d-flex">
                                    <input type="checkbox" class="data-checkbox" value="<?php echo $data_sl_no; ?>"
                                        <?php echo $checked; ?>>
                                    <?php echo $entList_row["data_title"];?>
                                </div>
                            </div>
                            <?php } ?>
                        </div>

                        <!-- Update Button -->
                        <button id="update-btn" class="btn btn-primary mt-3">Update</button>
                    </div>
                </div>
            </div>
            <?php } else {echo "Enter a valid college.";}?>
        </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).ready(function() {
        $('#update-btn').on('click', function() {
            var selectedValues = [];

            $('.data-checkbox:checked').each(function() {
                selectedValues.push($(this).val());
            });

            var list = selectedValues.length > 0 ? selectedValues.join(',') :
                ''; // Join values or empty if none selected

            $.ajax({
                url: 'update-data.php',
                type: 'POST',
                data: {
                    list: list,
                    college_id: '<?php echo $college_id; ?>'
                },
                success: function(response) {
                    alert('Update successful: ' + response);
                },
                error: function(xhr, status, error) {
                    console.error(xhr.responseText); // Log server response
                    alert('Error updating data: ' + xhr.responseText);
                }
            });
        });
    });
    </script>

</body>

</html>

<?php 
if(isset($_POST["submit"])){
    $Entrance = $_POST["Entrance"];

    $ins_sql = mysqli_query($con, "INSERT INTO data (data_catagory, data_long_des, data_up_for, data_up_date, data_recycle) VALUES ('cEntrance', '$Entrance', '$college_id', '$currentTime', '1')");
    if($ins_sql){
        echo "<script>window.location = 'c-entrance.php?college=" . $_GET["college"] . "';</script>";
    } else {
        echo "<script>alert('OOPS !!!!'); setTimeout(() => { window.location = 'c-entrance.php?college=" . $_GET["college"] . "'; }, 1200);</script>";
    }
}
?>
<?php
if(isset($_POST["edit"])){
    $Entrance = $_POST["Entrance"];

    $up_sql = mysqli_query($con, "UPDATE data SET data_long_des = '$Entrance' WHERE data_catagory = 'cEntrance' AND data_up_for = '$college_id' ");
    if($up_sql){
        echo "<script>window.location = 'c-entrance.php?college=" . $_GET["college"] . "';</script>";
    } else {
        echo "<script>alert('OOPS !!!!'); setTimeout(() => { window.location = 'c-entrance.php?college=" . $_GET["college"] . "'; }, 1200);</script>";
    }
}
?>