<?php
    // session_start();
    include "../db.php";
    require '../auth.php';
    restrictAccess(['Associate']);
    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"];
    $adminRef_sql = mysqli_query($con, "SELECT admin_ref FROM users WHERE uid = '$_SESSION[uid]'");
    if($adminRef_row = mysqli_fetch_assoc($adminRef_sql)){
        $pEmployee_uref_code = $adminRef_row["admin_ref"];
    }
    $emp_sql = mysqli_query($con, "SELECT * FROM users WHERE uref = '$pEmployee_uref_code'");
    if($emp_row = mysqli_fetch_assoc($emp_sql)){
        $pEmployee = $emp_row["uid"];
    }
    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($_GET["client_id"])){
        $client_id = $_GET["client_id"];
        $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"];
        ?>

    <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_id = $edit_row["pCollege"] ;
                        $course_id = $edit_row["product"];
                        $batch_id = $edit_row["pBatch"];
                        $dept_id = $edit_row["pCat"];
                        
                        $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 Service Details</h5>
                    <div class="card-body">
                        <form class="user" method="post" enctype="multipart/form-data">
                            <div class="row">
                                <div class="col-md-4 mb-2">
                                    <label for="student_name">Student Name</label>
                                    <input type="text" class="form-control" value="<?= $client_name?>" readonly>
                                    <input type="hidden" class="form-control" name="uname"
                                        value="<?php echo $client_id;?>">
                                </div>
                                <div class="col-md-4 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-4 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-4 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-4 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-4 mb-2">
                                    <label for="studentName">Course Fees</label>
                                    <input type="text" class="form-control" name="amount"
                                        value="<?php echo $edit_row["pAmount"];?>">
                                </div>

                                <div class="col-md-12 mb-3">
                                    <label for="content" class="form-label">News
                                        Description</label>
                                    <textarea class="form-control" name="content"
                                        rows="3"><?php echo $edit_row["pDescription"];?></textarea>
                                </div>
                            </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_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><strong>Course Fees :</strong> <?php echo $edit_row["pAmount"];?></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 mt-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 Courses List For <span
                                                style="color:orange;"><?php echo $client_name;?></span></h4>
                                    </div>
                                    <div class="col-md-4 col-12 text-end">
                                        <a href="view-client.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;">
                                    <form class="user" method="post" enctype="multipart/form-data">
                                        <div class="row">
                                            <div class="col-md-4 mb-2">
                                                <label for="student_name">Student Name</label>
                                                <input type="text" class="form-control" value="<?= $client_name?>"
                                                    readonly>
                                                <input type="hidden" class="form-control" name="uname"
                                                    value="<?php echo $client_id;?>">
                                            </div>
                                            <div class="col-md-4 mb-2">
                                                <label for="college">Select College <span
                                                        class="text-danger">*</span></label>
                                                <select name="college" class="form-control" id="college" required>
                                                    <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-4 mb-2">
                                                <label for="department">Select Department <span
                                                        class="text-danger">*</span></label>
                                                <select name="department" class="form-control" id="department" required>
                                                    <option value="">Select College First</option>
                                                </select>
                                            </div>

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

                                            <div class="col-md-4 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>

                                            <div class="col-md-4 mb-2">
                                                <label for="studentName">Course Fees <span
                                                        class="text-danger">*</span></label>
                                                <input type="text" class="form-control" name="amount"
                                                    placeholder="Enter Course fees.">
                                            </div>

                                            <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>
                    </div>
                </div>
                <?php }?>
            </div>
        </div>

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

    <?php } }?>

    <!-- JavaScript Libraries -->

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

    <script>
    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';
        }
    }
    $(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() {
        var load_filter_flag = 0;
        var FirstFilterValue = '';
        var SecondFilterValue = '';
        var ThirdFilterValue = '';
        var clientValue =
            <?php echo json_encode($client_id); ?>; // Use json_encode for safer handling of PHP variable in JavaScript

        $("#filter").click(function() {
            // Get the selected option's value from datalist and fetch its data-id
            var selectedOption = $('#FirstFilterValue').val();
            var selectedDataId = $("#First option[value='" + selectedOption + "']").attr('data-id');

            // Use data-id if present, otherwise use the selectedOption directly
            FirstFilterValue = selectedDataId ? selectedDataId : selectedOption;
            SecondFilterValue = $('#SecondFilterValue').val();
            ThirdFilterValue = $('#ThirdFilterValue').val();
            clientValue = $('#clientValue').val() ||
                clientValue; // Ensure clientValue is updated from input or use default

            load_filter_flag = 0;

            if (FirstFilterValue !== '' || SecondFilterValue !== '' || clientValue !== '') {
                $.ajax({
                    url: 'view-product-Ajax.php',
                    type: 'post',
                    data: {
                        FirstFilterValue: FirstFilterValue, // Using data-id or selected value
                        SecondFilterValue: SecondFilterValue,
                        ThirdFilterValue: ThirdFilterValue,
                        client: clientValue,
                        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) {
                        $("#loader").hide();
                    }
                });
            } else {
                alert('Please select an option');
                $('#full-table').show();
                $('#filter-table').hide();
            }
        });

        function loadMoreFilter(start) {
            if (load_filter_flag > 0) {
                $.ajax({
                    url: 'view-product-Ajax.php',
                    type: 'post',
                    data: {
                        FirstFilterValue: FirstFilterValue,
                        SecondFilterValue: SecondFilterValue,
                        ThirdFilterValue: ThirdFilterValue,
                        client: clientValue,
                        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) {
            $.ajax({
                url: 'view-product-Ajax.php',
                type: 'post',
                data: {
                    client: clientValue,
                    start: start
                },
                success: function(result) {
                    $('#full-table-data').append(result);
                    load_flag += 10;
                },
                complete: function(data) {
                    $("#loader").hide();
                }
            });
        }

        $('#inner-body').scroll(function() {
            if ($('#inner-body').scrollTop() >= $(document).height() - $('#inner-body').height()) {
                if (load_filter_flag > 0) {
                    loadMoreFilter(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']));
    $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']));
    $amount = mysqli_real_escape_string($con, strip_tags($_POST['amount']));
    $content = $_POST["content"];
    date_default_timezone_set('Asia/Kolkata');
    $currentTime = date('Y-m-d');
    $recycle = 0;  // Assuming recycle flag is set to 0 by default

    // Retrieve admin reference from session
    $admin_ref = $_SESSION['uref_code'];

    // Logic for subFranchisee
    if($_SESSION["utype"] == "Associate"){
        $pSubFranchiee = 0;  // Set to 0 if not a subFranchisee
        $pFranchiee = $_SESSION['uid'];  // No franchisee in this case
    }

    $pStatus = 0;  // Default status

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

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

    // Bind parameters (sssssiiii) string and integer types
    $stmt->bind_param('sssssssssssss', $college, $department, $course, $content, $uname, $pEmployee, $pSubFranchiee, $pFranchiee, $pStatus, $currentTime, $recycle, $amount, $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']));
        $amount = mysqli_real_escape_string($con, strip_tags($_POST['amount']));
        $content = $_POST["content"];

        $up_sql = "UPDATE product SET pCollege = '$college', pCat = '$department', product = '$course', pDescription = '$content', pAmount = '$amount', 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
    }
}
?>