<?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['uref_code']) && !isset($_SESSION['uname']) && !isset($_SESSION['utype']) ) {
        header("Location: logout.php");
        exit();
    }
    // echo $_SESSION["otp"];
    // echo $_SESSION["uref_code"];
?>

<!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">
            <div class="container-fluid">
                <?php if (isset($_GET["edit_id"])) {
                $edit_id = mysqli_real_escape_string($con, $_GET["edit_id"]);
                $details_sql = mysqli_query($con, "SELECT * FROM branch WHERE b_id = '$edit_id'");

                if ($details_row = mysqli_fetch_assoc($details_sql)) {
                    $class_sql = mysqli_query($con, "SELECT * FROM clg_course WHERE sl_no = '" . $details_row['b_class'] . "'");
                    if ($class_row = mysqli_fetch_assoc($class_sql)) {
                            $class_name = $class_row["course_name"];
                    }
                    ?>
                <div class="card mt-3">
                    <h5 class="card-header text-dark text-center font-weight-bold">Edit Department</h5>
                    <div class="card-body">
                        <form method="POST">
                            <div class="row">
                                <div class="col-md-4 mb-2">
                                    <div class="form-group">
                                        <label>Selected Course Name</label>

                                        <!-- User-visible input -->
                                        <input type="text" list="classV" class="form-control" id="course_search"
                                            placeholder="<?php echo htmlspecialchars($class_name); ?>"
                                            autocomplete="off">

                                        <!-- Hidden input for old value -->
                                        <input type="hidden" name="oldClass"
                                            value="<?php echo htmlspecialchars($details_row['b_class']); ?>">

                                        <!-- Hidden input to store selected sl_no -->
                                        <input type="hidden" id="class" name="class_id"
                                            value="<?php echo htmlspecialchars($details_row['b_class']); ?>">

                                        <!-- Datalist for course names -->
                                        <datalist id="classV">
                                            <?php
                                            $coursePidMap = [];
                                            $run = mysqli_query($con, "SELECT DISTINCT course_name, sl_no FROM clg_course WHERE recycle = '1' ORDER BY course_name ASC");
                                            while ($row = mysqli_fetch_assoc($run)) {
                                                $course_name = htmlspecialchars($row["course_name"]);
                                                $sl_no = htmlspecialchars($row["sl_no"]);
                                                $coursePidMap[$course_name] = $sl_no;
                                                echo "<option value='{$course_name}'></option>";
                                            }
                                            ?>
                                        </datalist>
                                    </div>
                                </div>

                                <div class="col-md-8 mb-2">
                                    <div class="from-group">
                                        <label>Batch Name</label>
                                        <input type="text" class="form-control" id="sub_class"
                                            value="<?php echo $details_row["batch_title"];?>" name="batch_title"
                                            required>
                                    </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-upload"></i> Edit Batch
                                </button>
                                <a href="view-batch.php" class="btn btn-warning text-white mt-4"><i
                                        class="fa fa-arrow-left"></i>&nbsp;Back </a>
                            </div>
                        </form>
                    </div>
                </div>
                <?php
                    }
                } elseif (isset($_GET["view_id"])) {
                    $view_id = mysqli_real_escape_string($con, $_GET["view_id"]);
                    $details_sql = mysqli_query($con, "SELECT * FROM branch WHERE b_id = '$view_id'");
    
                    if ($details_row = mysqli_fetch_assoc($details_sql)) {
                        $class_sql = mysqli_query($con, "SELECT * FROM clg_course WHERE sl_no = '" . $details_row['b_class'] . "'");
                        if ($class_row = mysqli_fetch_assoc($class_sql)) {
                            $class_name = $class_row["course_name"];
                        }
                        
                        ?>
                <div class="card mt-3">
                    <h5 class="card-header text-dark text-center font-weight-bold">
                        <?php echo $details_row["batch_title"];?>
                        Batch</h5>
                    <div class="card-body">
                        <div class="row">
                            <p><strong>Batch Title : </strong><?php echo $details_row["batch_title"];?></p>
                            <p><strong>Course Name : </strong><?php echo $class_name;?></p>
                        </div>
                        <div class="form-group">
                            <a href="view-batch.php" class="btn btn-warning text-white mt-4"><i
                                    class="fa fa-arrow-left"></i>&nbsp;Back </a>
                        </div>
                    </div>
                </div>
                <?php
                        }
                    } else{?>
                <div class="card mt-3">
                    <h5 class="card-header text-dark  text-center font-weight-bold">Add Batch</h5>
                    <div class="card-body">
                        <!-- Toggle Buttons -->
                        <button class="btn btn-sm btn-secondary mb-3" id="form-view">Add New Batch</button>
                        <button class="btn btn-sm btn-secondary mb-3" id="form-hide" style="display:none;">Hide
                            Form</button>

                        <!-- Form -->
                        <form method="POST" style="display:none;" id="submit-form">
                            <div class="row">
                                <div class="col-md-4 mb-2">
                                    <label>Select Course</label>
                                    <!-- Course Name Search -->
                                    <input type="text" list="third" id="course_search" class="form-control"
                                        placeholder="Search by Course Name" autocomplete="off">
                                    <input type="hidden" name="class" id="class"> <!-- Hidden field to store sl_no -->

                                    <datalist id="third">
                                        <?php
                                            $res = mysqli_query($con, "
                                                SELECT DISTINCT course_name, sl_no 
                                                FROM clg_course WHERE recycle ='1'
                                                ORDER BY course_name ASC
                                            ");
                                            $coursePidMap = [];
                                            while ($row = mysqli_fetch_assoc($res)) {
                                                $course_name = htmlspecialchars($row['course_name']);
                                                $sl_no = htmlspecialchars($row['sl_no']);
                                                $coursePidMap[$course_name] = $sl_no;
                                                echo "<option data-id='$sl_no' value='$course_name'></option>";
                                            }
                                        ?>
                                    </datalist>

                                </div>
                                <div class="col-md-8 mb-2">
                                    <div class="form-group">
                                        <label>Enter Batch Name</label>
                                        <input type="text" class="form-control" placeholder="Enter Class Name"
                                            name="batch_title" required>
                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <button type="submit" class="btn btn-success text-sm-center mt-4" name="submit">
                                    <i class="fa fa-plus"></i> Add Batch
                                </button>
                            </div>
                        </form>
                    </div>

                </div>
                <?php }?>
                <?php if(!isset($_GET["edit_id"]) AND !isset($_GET["view_id"])){?>
                <div class="card mt-3 mb-3">
                    <div class="card-header">
                        <div class="row align-items-center">
                            <div class="col-md-8 mb-2">
                                <h4 class="m-0 text-dark font-weight-bold">Batch List</h4>
                            </div>
                            <div class="col-md-4">
                                <div class="d-flex justify-content-end">
                                    <div class="filter-input w-100">
                                        <div class="form-group">
                                            <input type="text" list="second" placeholder="Search Batch Name"
                                                class="form-control form-control-sm" id="SecondFilterValue"
                                                autocomplete="off">
                                            <datalist id="second">
                                                <?php 
                                                    $search_sql = "SELECT * FROM branch WHERE b_upBy = '$_SESSION[uref_code]' AND b_recycle !='0' ORDER BY b_id ASC";
                                                    $search_res = mysqli_query($con,$search_sql);
                                                    while ($search_row = mysqli_fetch_assoc($search_res)) {
                                                ?>
                                                <option value="<?php echo $search_row['batch_title']; ?>">
                                                    <?php echo $search_row['batch_title']; ?></option>
                                                <?php } ?>
                                            </datalist>
                                        </div>
                                    </div>
                                    <div class="#">
                                        <button type="button" id="filter" class="btn btn-sm 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 class="text-center mt-3" id="load-more-container">
                                <button id="loadMoreBtn" class="btn btn-info btn-sm text-white">Load More</button>
                                <div id="endMessage" class="text-muted mt-2" style="display: none;">End of result</div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php }?>
            </div>
        </div>

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

    <!-- JavaScript Libraries -->

    <?php include "include/js.php"; ?>
    <!-- Toggle Script -->
    <script>
    document.addEventListener("DOMContentLoaded", function() {
        const formViewBtn = document.getElementById('form-view');
        const formHideBtn = document.getElementById('form-hide');
        const submitForm = document.getElementById('submit-form');

        formViewBtn.addEventListener('click', () => {
            submitForm.style.display = 'block';
            formHideBtn.style.display = 'inline-block';
            formViewBtn.style.display = 'none';
        });

        formHideBtn.addEventListener('click', () => {
            submitForm.style.display = 'none';
            formHideBtn.style.display = 'none';
            formViewBtn.style.display = 'inline-block';
        });
    });
    </script>
    <script>
    document.addEventListener("DOMContentLoaded", function() {
        const courseMap = {
            <?php
        foreach ($coursePidMap as $name => $sl_no) {
            echo "'" . addslashes($name) . "': '$sl_no',";
        }
        ?>
        };

        const courseSearchInput = document.getElementById('course_search');
        const hiddenClassInput = document.getElementById('class');

        courseSearchInput.addEventListener('input', function() {
            const selectedCourse = this.value;
            if (courseMap[selectedCourse]) {
                hiddenClassInput.value = courseMap[selectedCourse];
            } else {
                hiddenClassInput.value = '';
            }
        });
    });
    </script>

    <script>
    $(document).ready(function() {
        let load_filter_flag = 0;
        let load_flag = 0;

        let SecondFilterValue = '';

        // Filter button click
        $("#filter").click(function() {
            SecondFilterValue = $('#SecondFilterValue').val();
            load_filter_flag = 0;
            load_flag = 0;

            if (SecondFilterValue) {
                $.ajax({
                    url: 'view-batch-Ajax.php',
                    type: 'POST',
                    data: {
                        SecondFilterValue,
                        start: load_filter_flag
                    },
                    beforeSend: function() {
                        $("#loader").show();
                        $("#loadMoreBtn").hide();
                    },
                    success: function(result) {
                        $('#full-table').hide();
                        $('#filter-table').show();
                        $('#filter-table-data').html(result);

                        const tempDiv = $('<div>').html(result);
                        const items = tempDiv.find('li');
                        load_filter_flag += items.length;

                        if (items.length < 10) {
                            $('#loadMoreBtn').hide();
                            $('#endMessage').show();
                        } else {
                            $('#loadMoreBtn').show();
                            $('#endMessage').hide();
                        }
                    },
                    complete: function() {
                        $("#loader").hide();
                    }
                });
            } else {
                alert('Please select at least one filter option.');
                $('#full-table').show();
                $('#filter-table').hide();
                $('#loadMoreBtn').show();
                $('#endMessage').hide();
            }
        });

        // Initial load for unfiltered data
        loadMore(load_flag);

        function loadMore(start) {
            $.ajax({
                url: 'view-batch-Ajax.php',
                type: 'POST',
                data: {
                    start: start
                },
                beforeSend: function() {
                    $("#loader").show();
                    $("#loadMoreBtn").hide();
                },
                success: function(result) {
                    $('#full-table-data').append(result);


                    const tempDiv = $('<div>').html(result);
                    const items = tempDiv.find('li');
                    load_flag += items.length;

                    if (items.length < 10) {
                        $('#loadMoreBtn').hide();
                        $('#endMessage').show();
                    } else {
                        $('#loadMoreBtn').show();
                        $('#endMessage').hide();
                    }
                },
                complete: function() {
                    $("#loader").hide();
                }
            });
        }

        function loadMoreFilter(start) {
            $.ajax({
                url: 'view-batch-Ajax.php',
                type: 'POST',
                data: {
                    SecondFilterValue,
                    start: start
                },
                beforeSend: function() {
                    $("#loader").show();
                    $("#loadMoreBtn").hide();
                },
                success: function(result) {
                    $('#filter-table-data').append(result);

                    const tempDiv = $('<div>').html(result);
                    const items = tempDiv.find('li');
                    load_filter_flag += items.length;

                    if (items.length < 10) {
                        $('#loadMoreBtn').hide();
                        $('#endMessage').show();
                    } else {
                        $('#loadMoreBtn').show();
                        $('#endMessage').hide();
                    }
                },
                complete: function() {
                    $("#loader").hide();
                }
            });
        }

        // Load More button click
        $("#loadMoreBtn").click(function() {
            if ($('#filter-table').is(":visible")) {
                loadMoreFilter(load_filter_flag);
            } else {
                loadMore(load_flag);
            }
        });
    });
    </script>

</body>

</html>

<?php
if (isset($_POST['submit'])) {
    $class = mysqli_real_escape_string($con, strip_tags($_POST['class'])); // This is sl_no
    $batch_title = mysqli_real_escape_string($con, strip_tags($_POST['batch_title']));

    $ins_sql = "INSERT INTO branch (b_class, batch_title, b_upBy, b_created, b_recycle) 
                VALUES ('$class', '$batch_title', '$_SESSION[uref_code]', '$currentTime', '1')";

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

?>

<?php
if (isset($_POST['edit_submit']) && isset($_GET["edit_id"])) {
    $edit_id = mysqli_real_escape_string($con, $_GET["edit_id"]);

    // Sanitize new values
    $new_class = isset($_POST['class_id']) ? mysqli_real_escape_string($con, strip_tags($_POST['class_id'])) : '';
    $batch_title = isset($_POST['batch_title']) ? mysqli_real_escape_string($con, strip_tags($_POST['batch_title'])) : '';
    
    // Fallback to old class if new class is empty
    $old_class = isset($_POST['oldClass']) ? mysqli_real_escape_string($con, strip_tags($_POST['oldClass'])) : '';
    $sc_for = !empty($new_class) ? $new_class : $old_class;

    // Only update if batch_title is not empty (optional validation)
    if (!empty($batch_title)) {
        $update_sql = "UPDATE branch SET b_class = '$sc_for', batch_title = '$batch_title' WHERE b_id = '$edit_id'";

        if (mysqli_query($con, $update_sql)) {
            echo "<script>window.location = 'view-batch.php';</script>";
        } else {
            echo "<script>alert('OOPS !!!!'); setTimeout(() => { window.location = 'view-batch.php'; }, 1200);</script>";
        }
    } else {
        echo "<script>alert('Batch title cannot be empty');</script>";
    }
}
?>


<?php
if(isset($_GET['del_id'])){
    $del_id = $_GET["del_id"];
    $delete_sql = "UPDATE sub_class SET sc_display = 'disable' WHERE sc_id = '$del_id'";

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