<?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"];
    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"];
                        $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"];
                        }
                        $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-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="studentName">Student Name</label>
                                    <input type="text" class="form-control" value="<?php echo $client_name;?>" readonly>
                                    <input type="hidden" class="form-control" name="uname"
                                        value="<?php echo $client_id;?>">
                                </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>
                            </div>
                            <div>
                                <button type="submit" class="btn btn-success btn-user m-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"> <i class="fa fa-ban"></i> Cancel </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"];
                        }
                        $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 Client Details</h5>
                    <div class="card-body">
                        <p class="m-0"><strong>College :</strong> <?php echo $clg_name;?></p>
                        <p><strong>Course :</strong> <?php echo $course_name . ' (' . $pCat . ')'?></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"> <i class="fa fa-ban"></i>
                            Cancel </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 Service Details For
                        <span style="color:orange;"><?php echo $client_name;?></span>
                    </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="">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="studentName">Student Name</label>
                                    <input type="text" class="form-control" value="<?php echo $client_name;?>" readonly>
                                    <input type="hidden" class="form-control" name="uname"
                                        value="<?php echo $client_id;?>">
                                </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 m-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"> <i class="fa fa-ban"></i> Cancel </a>
                            </div>
                        </form>
                    </div>
                </div>
                <?php
                } else{?>
                <div class="card mt-3 mb-3">
                    <div class="card-header">
                        <div class="row align-items-center">
                            <div class="col-md-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 Service 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>
                                        <!--<a href="view-product.php?client_id=<?php echo $client_id;?>&add_id"
                                            class="btn btn-primary btn-sm m-0"><i class="fa fa-plus"></i>&nbsp;
                                            Product</a>-->
                                    </div>
                                </div>
                            </div>
                            <!--<div class="col-md-3 col-12 mt-2 mb-2 d-flex justify-content-center">
                                <div class="form-group w-100">
                                    <input type="text" list="First" class="form-control form-control-sm"
                                        id="FirstFilterValue" placeholder="Search By Name">
                                    <datalist id="First">
                                        <?php 
                                            $sql = "SELECT DISTINCT product FROM product WHERE pClient = '{$_GET["client_id"]}' ORDER BY pid DESC";
                                            $res = mysqli_query($con,$sql);
                                            while ($row = mysqli_fetch_assoc($res)) {
                                                // Fetching product details
                                                $service2_sql = mysqli_query($con, "SELECT * FROM data WHERE data_sl_no = '{$row["product"]}'");
                                                if($service2_row = mysqli_fetch_assoc($service2_sql)){
                                                    $productId = $service2_row["data_sl_no"];
                                                    $productName = $service2_row["data_title"];
                                                }
                                        ?>
                            <option value="<?php echo $productName; ?>" data-id="<?php echo $productId; ?>">
                                <?php echo $productName; ?>
                            </option>
                            <?php } ?>
                            </datalist>
                        </div>

                        <div class="#">
                            <button type="button" id="filter" class="btn btn-primary btn-sm">Search</button>
                        </div>

                    </div>-->
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <!--loader -->
                            <div class="col-12" id='loader'>
                                <ul style="list-style: none; padding-left: 0;">
                                    <?php 
                                        for ($count = 0; $count < 4; $count++) {
                                            echo '<li>
                                            <div class="ph-item">
                                            <div cl ass="ph-test">
                                            <div class="ph-row">
                                            <div class="ph-col-12 big"></div>
                                            <div class="ph-col-12"></div>
                                            <div class="ph-col-12"></div>
                                            <div class="ph-col-12"></div>
                                            <div class="ph-col-12"></div>
                                            <div class="ph-col-12"></div>
                                            </div></div>
                                            </div>
                                            </li>';
                                        }
                                    ?>
                                </ul>
                            </div>
                            <!-- loader -->

                            <div class="col-12" id="full-table">
                                <ul class="timeline" id="full-table-data" style="list-style: none; padding-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>
    $(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>');
                    }
                });
            } else {
                $('#department').html('<option value="">Select College First</option>');
                $('#course').html('<option value="">Select Department 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);
                    }
                });
            } else {
                $('#course').html('<option value="">Select Department First</option>');
            }
        });
    });
    </script>

    <script>
    $(document).ready(function() {
        var load_filter_flag = '';
        var FirstFilterValue = '';
        var SecondFilterValue = '';
        var ThirdFilterValue = '';
        var clientId = '<?php echo $_GET["client_id"]?>';

        $("#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');

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

            load_filter_flag = 0;

            if (FirstFilterValue != '' || SecondFilterValue != '' || ThirdFilterValue != '') {
                $.ajax({
                    url: 'view-product-Ajax.php',
                    type: 'post',
                    data: {
                        FirstFilterValue: FirstFilterValue, // Using data-id
                        SecondFilterValue: SecondFilterValue,
                        ThirdFilterValue: ThirdFilterValue,
                        clientId: clientId,
                        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,
                        clientId: clientId,
                        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: {
                    clientId: clientId,
                    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']));
    $department = mysqli_real_escape_string($con, strip_tags($_POST['department']));
    $uname = mysqli_real_escape_string($con, strip_tags($_POST['uname']));
    $content = $_POST["content"];
    $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"] == "Sub Associate"){
        $pSubFranchiee = $_SESSION["uid"];
        $pEmployee = 0; // No employee reference in this case

        // Fetch franchisee information from the database
        $fran_sql = mysqli_query($con, "SELECT * FROM users WHERE uref_code = '{$_SESSION["admin_ref"]}'");
        if($fran_row = mysqli_fetch_assoc($fran_sql)){
            $pFranchiee = $fran_row["uid"]; // Assign franchisee UID
        }
    } else {
        $pSubFranchiee = 0;  // Set to 0 if not a subFranchisee
        $pEmployee = $_SESSION['uid']; // Assuming session uid is for employee
        $pFranchiee = 0;  // 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) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

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

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

    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']));
        $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' ";

        $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
    }
}
?>