<?php
    // session_start();
    include "../db.php";
    require '../auth.php';
    restrictAccess(['Student']);
    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"];
    if(isset($_GET["client_id"])){}
?>

<!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 -->
    <?php if(isset($_SESSION["uid"])){
        $client_id = $_SESSION["uid"];
        $client_sql = mysqli_query($con, "SELECT * FROM users WHERE uid = '$client_id' ");
        if($client_row = mysqli_fetch_assoc($client_sql)){
            $client_name = $client_row["uname"];
            $referBy = $client_row["admin_ref"];
            $refer_sql = mysqli_query($con, "SELECT * FROM users WHERE uref_code = '$referBy' ");
            if($refer_row = mysqli_fetch_assoc($refer_sql)){
                $referType = $refer_row["utype"];
                $referById = $refer_row["uid"];
                if($referType == "Sub Associate"){
                    $franSql = mysqli_query($con, "SELECT * FROM users WHERE uref_code = '$refer_row[admin_ref]'");
                    if($franRow = mysqli_fetch_assoc($franSql)){
                        $franid = $franRow["uid"];
                        $subfranid = $referById;
                    }
                }elseif($referType == "Associate"){
                    $subfranid = 0;
                    $franid = $referById;
                }elseif($referby == "1"){
                    $subfranid = 0;
                    $franid = 0;
                }
            }
        ?>

    <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 product WHERE pid = '$_GET[edit_id]'");
                    if($edit_row = mysqli_fetch_assoc($edit_run)){

                        $clg_sql = mysqli_query($con, "SELECT * FROM users WHERE uid = '{$edit_row["pCollege"]}'");
                        if($clg_row = mysqli_fetch_assoc($clg_sql)){
                            $clg_name = $clg_row["uname"];
                        }

                        $course_sql = mysqli_query($con, "SELECT * FROM clg_course WHERE sl_no = '{$edit_row["product"]}' ");
                        while($course_row = mysqli_fetch_assoc($course_sql)){
                            $course_name = $course_row["course_name"];
                        }
                        $cat_sql = mysqli_query($con, "SELECT * FROM clg_course_cat WHERE sl_no = '{$edit_row["pCat"]}' ");
                        while($cat_row = mysqli_fetch_assoc($cat_sql)){
                            $pCat = $cat_row["cat_name"];
                        }
                        
                        $batch_name = "";
                        $batch_sql = mysqli_query($con, "SELECT * FROM branch WHERE b_id = '{$edit_row["pBatch"]}' ");
                        while($batch_row = mysqli_fetch_assoc($batch_sql)){
                            $batch_name = $batch_row["batch_title"];
                        }
                    ?>
                <div class="card mt-3">
                    <h5 class="card-header text-dark  text-center font-weight-bold">Edit Course Details</h5>
                    <div class="card-body">
                        <form class="user" method="post" enctype="multipart/form-data">
                            <div class="row">
                                <div class="col-md-3 mb-2">
                                    <label for="college">Select College:</label>
                                    <select name="college" class="form-control" id="college">
                                        <option value="<?php echo $clg_id;?>"><?php echo $clg_name;?></option>
                                        <?php 
                                            $clg_sql = mysqli_query($con, "SELECT * FROM users WHERE utype = 'College' AND uStatus = '1' AND udisplay != 'disable' ORDER BY uname ASC");
                                            while($clg_row = mysqli_fetch_assoc($clg_sql)){
                                        ?>
                                        <option value="<?php echo $clg_row["uid"]; ?>"><?php echo $clg_row["uname"]; ?>
                                        </option>
                                        <?php } ?>
                                    </select>
                                </div>
                                <div class="col-md-3 mb-2">
                                    <label for="department">Select Department</label>
                                    <select name="department" class="form-control" id="department">

                                        <option value="<?php echo $dept_id;?>">
                                            <?php echo $pCat;?></option>
                                    </select>
                                </div>

                                <div class="col-md-3 mb-2">
                                    <label for="course">Select Course</label>
                                    <select name="course" class="form-control" id="course">
                                        <option value="<?php echo $course_id;?>">
                                            <?php echo $course_name ;?></option>
                                    </select>
                                </div>

                                <div class="col-md-3 mb-2">
                                    <label for="batch">Select Batch</label>
                                    <select name="batch" class="form-control" id="batch">
                                        <option value="<?php echo $batch_id;?>">
                                            <?php echo $batch_name ;?></option>
                                    </select>
                                </div>

                                <div class="col-md-12 mb-3">
                                    <label for="content" class="form-label">Description</label>
                                    <textarea class="form-control" name="content"
                                        rows="3"><?php echo $edit_row["pDescription"];?></textarea>
                                </div>

                                <input type="hidden" class="form-control" name="uname" value="<?php echo $client_id;?>">
                            </div>
                            <div>
                                <button type="submit" class="btn btn-success btn-user my-2" name="edit_users"><i
                                        class="fa fa-edit"></i> UPDATE DETAILS
                                </button>
                                <a href="view-product.php?client_id=<?php echo $client_id;?>"
                                    class="btn btn-warning btn-user m-2 text-white"> <i class="fa fa-arrow-left"></i>
                                    Back </a>
                            </div>
                        </form>
                    </div>
                </div>
                <?php }
                } elseif(isset($_GET["view_id"])){
                    $edit_id = $_GET["view_id"];
                    $edit_run = mysqli_query($con, "SELECT * FROM product WHERE pid = '$_GET[view_id]'");
                    if($edit_row = mysqli_fetch_assoc($edit_run)){

                        $clg_sql = mysqli_query($con, "SELECT * FROM users WHERE uid = '{$edit_row["pCollege"]}'");
                        if($clg_row = mysqli_fetch_assoc($clg_sql)){
                            $clg_name = $clg_row["uname"];
                        }

                        $course_sql = mysqli_query($con, "SELECT * FROM clg_course WHERE sl_no = '{$edit_row["product"]}' ");
                        while($course_row = mysqli_fetch_assoc($course_sql)){
                            $course_name = $course_row["course_name"];
                        }
                        
                        $batch_name = "";
                        $batch_sql = mysqli_query($con, "SELECT * FROM branch WHERE b_id = '{$edit_row["pBatch"]}' ");
                        while($batch_row = mysqli_fetch_assoc($batch_sql)){
                            $batch_name = $batch_row["batch_title"];
                        }
                        
                        $cat_sql = mysqli_query($con, "SELECT * FROM clg_course_cat WHERE sl_no = '{$edit_row["pCat"]}' ");
                        while($cat_row = mysqli_fetch_assoc($cat_sql)){
                            $pCat = $cat_row["cat_name"];
                        }
                    ?>
                <div class="card mt-3">
                    <h5 class="card-header text-dark  text-center font-weight-bold">Edit Course Details</h5>
                    <div class="card-body">
                        <p class="m-0"><strong>College :</strong> <?php echo $clg_name;?></p>
                        <p class="m-0"><strong>Course :</strong> <?php echo $course_name . ' (' . $pCat . ')'?></p>
                        <p class="m-0"><strong>Batch :</strong> <?php echo $batch_name?></p>
                        <p class="m-0"><strong>Description:</strong></p>
                        <div id="ck-img-preview" class="p-0 m-0">
                            <p><?php echo $edit_row["pDescription"];?></p>
                        </div>
                        <a href="view-product.php?client_id=<?php echo $client_id;?>"
                            class="btn btn-warning btn-user my-2 text-white"> <i class="fa fa-arrow-left"></i>
                            Back </a>
                    </div>
                </div>
                <?php }
                } elseif(isset($_GET["add_id"])){?>
                <div class="card mt-3">
                    <h5 class="card-header text-dark  text-center font-weight-bold">Add Course Details For
                        <span style="color:orange;"><?php echo $client_name;?></span>
                    </h5>
                    <div class="card-body">

                    </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-12 col-12 mt-2 mb-2">
                                <div class="row justify-content-between align-items-center">
                                    <div class="col-md-8 col-12 mb-2">
                                        <h4 class="text-gray-800 m-0">Selected Course List For <span
                                                style="color:orange;"><?php echo $client_name;?></span></h4>
                                    </div>
                                    <div class="col-md-4 col-12 text-end">
                                        <a href="index.php" class="btn btn-warning text-white btn-sm"><i
                                                class="fa fa-arrow-left"></i> Back</a>
                                        <button id="toggleButton" class="btn btn-primary btn-sm"
                                            onclick="toggleDiv()">Add Course
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-12 mb-2">
                                <div id="toggleDiv"
                                    style="display: none; padding: 10px; border: 1px solid #ddd; margin-top: 10px;">
                                    <h6>Add New Course:</h6>
                                    <form class="user" method="post" enctype="multipart/form-data">
                                        <div class="row">
                                            <div class="col-md-3 mb-2">
                                                <label for="college">Select College:</label>
                                                <select name="college" class="form-control" id="college">
                                                    <option value="">Select From The List</option>
                                                    <?php 
                                                        $clg_sql = mysqli_query($con, "SELECT * FROM users WHERE utype = 'College' AND uStatus = '1' AND udisplay != 'disable' ORDER BY uname ASC");
                                                        while($clg_row = mysqli_fetch_assoc($clg_sql)){
                                                    ?>
                                                    <option value="<?php echo $clg_row["uid"]; ?>">
                                                        <?php echo $clg_row["uname"]; ?>
                                                    </option>
                                                    <?php } ?>
                                                </select>
                                            </div>

                                            <div class="col-md-3 mb-2">
                                                <label for="department">Select Department</label>
                                                <select name="department" class="form-control" id="department">
                                                    <option value="">Select College First</option>
                                                </select>
                                            </div>

                                            <div class="col-md-3 mb-2">
                                                <label for="course">Select Course</label>
                                                <select name="course" class="form-control" id="course">
                                                    <option value="">Select Department First</option>
                                                </select>
                                            </div>

                                            <div class="col-md-3 mb-2">
                                                <label for="batch">Select Batch <span
                                                        class="text-danger">*</span></label>
                                                <select name="batch" class="form-control" id="batch" required>
                                                    <option value="">Select Course First</option>
                                                </select>
                                            </div>

                                            <input type="hidden" class="form-control" name="uname"
                                                value="<?php echo $client_id;?>">

                                            <div class="col-md-12 mb-3">
                                                <label for="content" class="form-label">Description</label>
                                                <textarea class="form-control" name="content" rows="3"></textarea>
                                            </div>
                                        </div>
                                        <div>
                                            <button type="submit" class="btn btn-success btn-user my-2" name="submit"><i
                                                    class="fa fa-plus"></i> Add Service
                                            </button>
                                            <a href="view-product.php?client_id=<?php echo $client_id;?>"
                                                class="btn btn-warning btn-user m-2 text-white"> <i
                                                    class="fa fa-arrow-left"></i>
                                                Back
                                            </a>
                                        </div>
                                    </form>
                                </div>
                            </div>
                            <!--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-left: 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-left: 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>

    <?php } }?>

    <!-- JavaScript Libraries -->

    <?php include "include/js.php"; ?>

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

    function toggleDiv() {
        const div = document.getElementById('toggleDiv');
        const button = document.getElementById('toggleButton');

        if (div.style.display === 'none' || div.style.display === '') {
            div.style.display = 'block';
            button.textContent = 'Hide';
        } else {
            div.style.display = 'none';
            button.textContent = 'Add Course';
        }
    }
    </script>

    <script>
    $(document).ready(function() {
        // Fetch departments when a college is selected
        $('#college').change(function() {
            var college_id = $(this).val();

            if (college_id !== '') {
                $.ajax({
                    url: 'fetch_departments.php',
                    type: 'POST',
                    data: {
                        college_id: college_id
                    },
                    success: function(response) {
                        $('#department').html(response);
                        $('#course').html(
                            '<option value="">Select Department First</option>');
                        $('#batch').html('<option value="">Select Course First</option>');
                    }
                });
            } else {
                $('#department').html('<option value="">Select College First</option>');
                $('#course').html('<option value="">Select Department First</option>');
                $('#batch').html('<option value="">Select Course First</option>');
            }
        });

        // Fetch courses when a department is selected
        $('#department').change(function() {
            var department_id = $(this).val();

            if (department_id !== '') {
                $.ajax({
                    url: 'fetch_courses.php',
                    type: 'POST',
                    data: {
                        department_id: department_id
                    },
                    success: function(response) {
                        $('#course').html(response);
                        $('#batch').html('<option value="">Select Course First</option>');
                    }
                });
            } else {
                $('#course').html('<option value="">Select Department First</option>');
                $('#batch').html('<option value="">Select Course First</option>');
            }
        });

        // Fetch batches when a course is selected
        $('#course').change(function() {
            var course_id = $(this).val();

            if (course_id !== '') {
                $.ajax({
                    url: 'fetch_batch.php',
                    type: 'POST',
                    data: {
                        course_id: course_id
                    },
                    success: function(response) {
                        $('#batch').html(response);
                    }
                });
            } else {
                $('#batch').html('<option value="">Select Course First</option>');
            }
        });
    });
    </script>

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

        let FirstFilterValue = '';
        let SecondFilterValue = '';
        let ThirdFilterValue = '';
        let clientValue = <?php echo json_encode($client_id); ?>;

        // Load filtered data
        function loadFilteredData(start) {
            $.ajax({
                url: 'view-product-Ajax.php',
                type: 'POST',
                data: {
                    FirstFilterValue,
                    SecondFilterValue,
                    ThirdFilterValue,
                    client: clientValue,
                    start: start
                },
                beforeSend: function() {
                    $("#loader").show();
                },
                success: function(result) {
                    result = result.trim();
                    const tempDiv = $('<div>').html(result);
                    const newItems = tempDiv.find('li');

                    if (start === 0) {
                        if (result === '__NO_MORE_DATA__' || newItems.length === 0) {
                            $('#filter-table-data').html(`
                            <li class="text-center text-muted py-3">
                                <i class="fa fa-info-circle"></i> No results match your filters.
                            </li>`);
                            $('#full-table').hide();
                            $('#filter-table').show();
                            $('#loadMoreBtn').hide();
                            $('#endMessage').hide();
                            return;
                        }

                        $('#full-table').hide();
                        $('#filter-table').show();
                        $('#filter-table-data').html(newItems);
                    } else {
                        $('#filter-table-data').append(newItems);
                    }

                    load_filter_flag += newItems.length;

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

        // Load unfiltered data
        function loadMore(start) {
            $.ajax({
                url: 'view-product-Ajax.php',
                type: 'POST',
                data: {
                    client: clientValue,
                    start: start
                },
                beforeSend: function() {
                    $("#loader").show();
                },
                success: function(result) {
                    result = result.trim();
                    const tempDiv = $('<div>').html(result);
                    const newItems = tempDiv.find('li');

                    if (result === '__NO_MORE_DATA__' || newItems.length === 0) {
                        $('#loadMoreBtn').hide();
                        $('#endMessage').show();
                        return;
                    }

                    $('#full-table-data').append(newItems);
                    load_flag += newItems.length;

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

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

        // Filter button click
        $("#filter").click(function() {
            const selectedOption = $('#FirstFilterValue').val().trim();
            const selectedDataId = $("#First option[value='" + selectedOption + "']").attr('data-id');

            FirstFilterValue = selectedDataId ? selectedDataId : selectedOption;
            SecondFilterValue = $('#SecondFilterValue').val().trim();
            ThirdFilterValue = $('#ThirdFilterValue').val().trim();
            const inputClient = $('#clientValue').val();
            clientValue = inputClient ? inputClient.trim() : clientValue;

            load_filter_flag = 0;

            if (FirstFilterValue || SecondFilterValue || ThirdFilterValue || clientValue) {
                loadFilteredData(load_filter_flag);
            } else {
                alert('Please select at least one filter option.');
                $('#full-table').show();
                $('#filter-table').hide();
                $('#loadMoreBtn').show();
                $('#endMessage').hide();
            }
        });

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


</body>

</html>

<?php
if (isset($_POST['submit'])) {
    $college = mysqli_real_escape_string($con, strip_tags($_POST['college']));
    $course = mysqli_real_escape_string($con, strip_tags($_POST['course']));
    $department = mysqli_real_escape_string($con, strip_tags($_POST['department']));
    $uname = mysqli_real_escape_string($con, strip_tags($_POST['uname']));
    $batch = mysqli_real_escape_string($con, strip_tags($_POST['batch']));
    $content = $_POST["content"];
    $recycle = 0;  // Recycle flag is set to 0 by default

    $currentTime = date('Y-m-d');

    $pSubFranchiee = $subfranid; 
    $pEmployee = 0; 
    $pFranchiee = $franid; 

    $pStatus = 0;  // Default status

    // Prepare the SQL statement
    $sql = "INSERT INTO product (pCollege, pCat, product, pDescription, pClient, pEmployee, pSubFranchiee, pFranchiee, pStatus, pCreateDate, pRecycle, pBatch) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    $stmt = $con->prepare($sql);

    // Bind parameters (sssssiiii) string and integer types
    $stmt->bind_param('ssssssssssss', $college, $department, $course, $content, $uname, $pEmployee, $pSubFranchiee, $pFranchiee, $pStatus, $currentTime, $recycle, $batch);

    if ($stmt->execute()) {
        // Get the last inserted user ID
        $last_inserted_id = $con->insert_id;
        echo '<script>window.location.href = "view-product.php?client_id=' . $uname . '";</script>';
    } else {
         echo '<script>alert("Error during registration. Please try again later.");</script>';
    }
}
?>


<?php
    if(isset($_POST['edit_users'])){
        $college = mysqli_real_escape_string($con, strip_tags($_POST['college']));
        $course = mysqli_real_escape_string($con, strip_tags($_POST['course']));
        $batch = mysqli_real_escape_string($con, strip_tags($_POST['batch']));
        $department = mysqli_real_escape_string($con, strip_tags($_POST['department']));
        $uname = mysqli_real_escape_string($con, strip_tags($_POST['uname']));
        $content = $_POST["content"];

        $up_sql = "UPDATE product SET pCollege = '$college', pCat = '$department', product = '$course', pDescription = '$content', pBatch = '$batch' ";

        $up_sql .= " WHERE pid = '$_GET[edit_id]' ";

        if(mysqli_query($con, $up_sql)){
        ?>

<script>
window.location = 'view-product.php?client_id=<?php echo $uname;?>';
</script>
<?php
        }
        else{
        ?>
<script>
alert('OOPS !!!!');
setTimeout(() => {
    window.location = 'view-product.php?client_id=<?php echo $uname;?>&edit_id=<?php echo $_GET["edit_id"]; ?>';
}, 1200);
</script>
<?php
    }
} 
?>

<?php
if ( isset($_GET["del_id"]) ) {
$disable_sql = "DELETE FROM product WHERE pid = '$_GET[del_id]'";
    if ( mysqli_query($con, $disable_sql) ) {
        ?>
<script>
window.location = "view-product.php?client_id=<?php echo $_GET["client_id"];?>";
</script>
<?php
    } else {
        ?>
<script>
alert('OOPS !!!!');
setTimeout(() => {
    window.location = 'view-product.php?client_id=<?php echo $_GET["client_id"];?>';
}, 1200);
</script>
<?php
    }
}
?>