<?php
include '../../quiklrn_app/config.php';
//include '../quiklrn_app/config.php';

?>

<!DOCTYPE html>
<html>

<head>


<style>


#master_data_table tr:nth-child(even),
#dashboard_subpage_detailed_course_record tr:nth-child(even),
#dashboard_subpage_detailed_section_record tr:nth-child(even),
#dashboard_subpage_detailed_enrolment_record tr:nth-child(even),
#dashboard_subpage_detailed_instructor_record tr:nth-child(even),
#dashboard_subpage_detailed_learner_record tr:nth-child(even)
{
   /* background: lightgrey !important; */
   background: #f2f2f2 !important;
}

#master_data_table tr,
#master_data_table th,
#master_data_table td,
#dashboard_subpage_detailed_course_record tr,
#dashboard_subpage_detailed_course_record th,
#dashboard_subpage_detailed_course_record td,
#dashboard_subpage_detailed_section_record tr,
#dashboard_subpage_detailed_section_record th,
#dashboard_subpage_detailed_section_record td,
#dashboard_subpage_detailed_enrolment_record tr,
#dashboard_subpage_detailed_enrolment_record th,
#dashboard_subpage_detailed_enrolment_record td,
#dashboard_subpage_detailed_instructor_record tr,
#dashboard_subpage_detailed_instructor_record th,
#dashboard_subpage_detailed_instructor_record td,
#dashboard_subpage_detailed_learner_record tr,
#dashboard_subpage_detailed_learner_record th,
#dashboard_subpage_detailed_learner_record td
{
   border: 1px dotted black !important;
}

/* #master_data_table tr {
   border: 1px solid gray;
} */

.dashboard_grid_table,
.dashboard_grid_table_td, .dashboard_grid_table_th {
   border: 1px solid black;
   border-collapse: collapse;
   padding-left: 8px;
}

.dashboard_grid_table_td:nth-child(even) {
   text-align: left;
}

.dashboard_grid_table_td:nth-child(odd) {
   text-align: left;
}

th {
   background-color: #7A319F;
   color: white;
}

.loader-div {
   text-align: center;
   /* position: relative; */
   padding-top: 100px;
}

.fa{
   color: white;
}

.subTr{
   width: 80%;
}

#learners_headers_from_user_master{
   width:80%;
}
</style>
<style>
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th, td {
            padding: 8px;
            border: 1px solid #ddd;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
        }
        td a {
            color: blue;
            text-decoration: none;
        }
    </style>
    <style>
        #customers {
            font-family: Arial, Helvetica, sans-serif;
            border-collapse: collapse;
            width: 100%;
        }

        #customers td,
        #customers th {
            border: 1px solid #ddd;
            padding: 8px;
        }

        #customers tr:nth-child(even) {
            background-color: #f2f2f2;
        }

        #customers tr:hover {
            background-color: #ddd;
        }

        #customers th {
            padding-top: 12px;
            padding-bottom: 12px;
            text-align: left;
            background-color: #04AA6D;
            color: white;
        }
    </style>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-sca`le=1.0">
    <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3"
        crossorigin="anonymous"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/js/standalone/selectize.min.js"
        integrity="sha256-+C0A5Ilqmu4QcSPxrlGpaZxJ04VjsRjKu+G82kl5UJk=" crossorigin="anonymous" defer></script>
    <link rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/css/selectize.bootstrap3.min.css"
        integrity="sha256-ze/OEYGcFbPRmvCnrSeKbRTtjG4vGLHXgOqsyLFTRjg=" crossorigin="anonymous">
    <!-- DataTables -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.3/css/jquery.dataTables.min.css">
    <script src="https://cdn.datatables.net/1.13.3/js/jquery.dataTables.min.js"></script>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

</head>

<body>

    <h1>Course List</h1>

    <div class="modal-body">
					<div class="container-fluid p-0 w-100 overflow-auto">
						<div class="modal-body-container">
						</div>
					</div>
				</div>

        <!-- <table id="customers">
        <tr>
            <th>Sr. No</th>
            <th>Course Name</th>
            <th>Section Name</th>
            <th>Action</th>
        </tr>
        <tr>
            <td>Alfreds Futterkiste</td>
            <td>Maria Anders</td>
            <td>Germany</td>
        </tr>
        <tr>
            <td>Berglunds snabbköp</td>
            <td>Christina Berglund</td>
            <td>Sweden</td>
        </tr>
        <tr>
            <td>Centro comercial Moctezuma</td>
            <td>Francisco Chang</td>
            <td>Mexico</td>
        </tr>
        <tr>
            <td>Ernst Handel</td>
            <td>Roland Mendel</td>
            <td>Austria</td>
        </tr>
        <tr>
            <td>Island Trading</td>
            <td>Helen Bennett</td>
            <td>UK</td>
        </tr>
        <tr>
            <td>Königlich Essen</td>
            <td>Philip Cramer</td>
            <td>Germany</td>
        </tr>
        <tr>
            <td>Laughing Bacchus Winecellars</td>
            <td>Yoshi Tannamuri</td>
            <td>Canada</td>
        </tr>
        <tr>
            <td>Magazzini Alimentari Riuniti</td>
            <td>Giovanni Rovelli</td>
            <td>Italy</td>
        </tr>
        <tr>
            <td>North/South</td>
            <td>Simon Crowther</td>
            <td>UK</td>
        </tr>
        <tr>
            <td>Paris spécialités</td>
            <td>Marie Bertrand</td>
            <td>France</td>
        </tr>
    </table> -->
        <!-- Modal -->

       
        <div class="modal fade" id="uploadCourseModal" tabindex="-1" aria-labelledby="uploadCourseModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="uploadCourseModalLabel">Upload Course</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <!-- Course Upload Form -->
                        <form id="uploadCourseForm">
                            <div class="mb-3">
                                <label for="courseName" class="form-label">Course Name</label>
                                <input type="text" class="form-control" id="courseName" disabled>
                            </div>
                            <div class="mb-3">
                                <label for="sectionName" class="form-label">Section Name</label>
                                <input type="text" class="form-control" id="sectionName" disabled>
                            </div>
                            <!-- <div class="mb-3">
                                <label for="sectionId" class="form-label">Section Name</label>
                            </div>
                            <div class="mb-3">
                                <label for="courseId" class="form-label">Section Name</label>
                            </div>
                            <div class="mb-3">
                                <label for="clgId" class="form-label">College Id</label>
                            </div>
                            <div class="mb-3">
                                <label for="uId" class="form-label">User Id</label>
                            </div>
                            <div class="mb-3">
                                <label for="authCode" class="form-label">Auth Code</label>
                            </div> -->
                            <input type="hidden" class="form-control" id="sectionId" disabled>
                            <input type="hidden" class="form-control" id="courseId" disabled>
                            <input type="hidden" class="form-control" id="clgId" disabled>
                            <input type="hidden" class="form-control" id="uId" disabled>
                            <input type="hidden" class="form-control" id="authCode" disabled>
                            
                            <div class="mb-3">
                                <label for="uploadFile" class="form-label">Upload File</label>
                                <input type="file" class="form-control" id="uploadFile">
                            </div>
                            <div class="mb-3">
                                <button type="submit" class="btn btn-primary">Upload</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <div class="modal fade" id="listCourseModal" tabindex="-1" aria-labelledby="listCourseModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <!-- <h5 class="modal-title" id="listCourseModalLabel">Upload Course</h5> -->
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <!-- Course Upload Form -->
                        <h2>File List</h2>
                        <table id="fileTable">
                            <thead>
                                <tr>
                                    <th>File Name</th>
                                    <th>Download Link</th>
                                </tr>
                            </thead>
                            <tbody>
                                <!-- Table rows will be populated here by jQuery -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

    <script>
        console.log('In');
        var internal_api_url = <?php echo json_encode(INTERNAL_API_URL); ?>;
        var external_api_url = <?php echo json_encode(QUIKLRN_API_URL); ?>;

        var base_url = <?php echo json_encode(BASE_URL); ?>;
        var int_url = <?php echo json_encode(INT_URL); ?>;
        var int_view_url = <?php echo json_encode(INTERNAL_VIEW_URL); ?>;
        var query = window.location.search;
        var paramters = new URLSearchParams(query);
        var auth_code = paramters.get('auth_code');
        $(document).ready(function () {
            get_user_id(function (resp) {
                console.log('resp',resp)
                if (resp) {
                    // get_college_id(function (resp2) {
                    //     get_department(function (resp3) {

                    //     });
                    // });
                    get_college_dept_id(function (resp2) {
                        getSemesterCourseSectionDetailByUser();
                        // alert('INNN');
                    });
                }

            });
                
        });

        function get_user_id(callback) {
            var query = window.location.search;
            var paramters = new URLSearchParams(query);
            var auth_code = paramters.get('auth_code');
            $.ajax({
                type: "GET",
                url: int_url + '?method=auth_function',
                data: { auth_code: auth_code },
                success: function (resp) {
                    let data1 = resp.data;
                    if (data1.length == 0 && !(auth_code == 'xyz')) {
                        alert("Invalid Auth Code!");
                        return false;
                    }

                    if (auth_code == 'xyz') {
                        additional_reports('25');
                        return;
                    }

                    let dta = { user_id: data1[0].user_id, user_type: data1[0].user_type, user_email: data1[0].email }
                    localStorage.setItem("ReqData", JSON.stringify(dta));

                    if (data1[0].user_type == '1') {
                        // get_students_record(data1[0].user_id);
                    }

                    if (callback) {
                        //  get_college_id(auth_code);
                        window.auth = auth_code;
                        return callback(true);
                    } else {
                        alert('callback failed in get_user_id method! ');
                    }
                },
                error: function (xhr, status, error) {
                    console.error(xhr);
                }
            });
        }

        function get_college_dept_id(callback){
			$.ajax({
				type: "GET",
				url: int_url+'?method=get_college_dept_id',
				data: { u_id: JSON.parse(localStorage.getItem("ReqData")).user_id, auth: auth_code},
				success: function(data)
				{
					
					let data1 = data.data;
					if(!(data.status))
					{
						alert('Failed to get college and department id!');
						return false;
					}
					if (data1.clg_details[0])
					{
						let localData = JSON.parse(localStorage.getItem("ReqData"));
						localData.clg_id = data1.clg_details[0].college_id;
						localData.clg_name = data1.clg_details[0].college_name;
						localStorage.setItem("ReqData", JSON.stringify(localData));
					}

					if (data1.dept_details[0])
					{
						let localData = JSON.parse(localStorage.getItem("ReqData"));
						localData.dept_id = data1.dept_details[0].dept_id;
						localData.dept_name = data1.dept_details[0].dept_name;
						localStorage.setItem("ReqData", JSON.stringify(localData));
					}
					let u_type= JSON.parse(localStorage.getItem("ReqData")).user_type;

				
					
					if(callback){
						callback(true, data1.clg_details[0].college_id);

					}else{
						alert('callback failed in get_college_dept_id method! ');
					}
				},
				error: function(xhr, status, error){
				console.error(xhr);
				}
			});
		}
	
        function get_college_id(callback) {
            $.ajax({
                type: "GET",
                url: int_url + '?method=get_college_id',
                data: { u_id: JSON.parse(localStorage.getItem("ReqData")).user_id },
                success: function (data) {
                    let data1 = data.data;
                    if (!(data.status)) {
                        alert('Failed');
                        return false;
                    }

                    if (data1[0]) {
                        $("#college_id").val(data1[0].college_id);
                        $("#college_name").val(data1[0].college_name);
                        let localData = JSON.parse(localStorage.getItem("ReqData"));
                        localData.clg_id = data1[0].college_id;
                        localData.clgName = data1[0].college_name;
                        localStorage.setItem("clgData", JSON.stringify(localData));
                    }

                    if (callback) {
                        callback(true);
                    } else {
                        alert('callback failed in get_college_id method! ');
                    }
                },
                error: function (xhr, status, error) {
                    console.error(xhr);
                }
            });
        }

        function get_department(callback) {
            var user_type = JSON.parse(localStorage.getItem("ReqData")).user_type;
            // alert(user_type);
            if (user_type == 6 || user_type == 9 || user_type == 1) {
                if (callback) {
                    return callback(true);
                } else {
                    alert('callback failed in get_department method! ');
                }
            }

            $.ajax({
                type: "GET",
                url: int_url + '?method=get_department',
                data: {
                    user_type: JSON.parse(localStorage.getItem("ReqData")).user_type,
                    clg_id: JSON.parse(localStorage.getItem("clgData")).clg_id,
                    user_id: JSON.parse(localStorage.getItem("ReqData")).user_id
                },
                success: function (data) {
                    let data1 = data.data;
                    if (!(data.status)) {
                        alert('Failed');
                        return false;
                    }
                    if (JSON.parse(localStorage.getItem("ReqData")).user_type != 5) {

                        let localData = JSON.parse(localStorage.getItem("ReqData"));
                        localData.dept_id = data1[0].dept_id;
                        localData.dept_name = data1[0].dept_name;
                        localStorage.setItem("dept_data", JSON.stringify(localData));
                    }

                    if (callback) {
                        return callback(true);
                    } else {
                        alert('callback failed in get_department method! ');
                    }
                },
                error: function (xhr, status, error) {
                    console.error(xhr);
                }
            });
        }

        function getSemesterCourseSectionDetailByUser()
        {   

            let clg_id= JSON.parse(localStorage.getItem("ReqData")).clg_id
            let auth_code = auth
            let u_id = JSON.parse(localStorage.getItem("ReqData")).user_id 
          
            $.ajax({
                type: "GET",
                url: int_url+'?method=getSemesterCourseSectionDetailByUser',
                data: {clg_id : clg_id, auth_code: auth_code, u_id: u_id},
                success: function(data)
                {
                    let data1 = data.data;
                    let getSemesterCourseSectionDetailByUser = data1.getSemesterCourseSectionDetailByUser;
                    $(".modal-body-container").html('');
                    $(".modal-body-container").html('<table id="dashboard_subpage_detailed_course_record" style="width:100%"></table>');
                    $("#dashboard_subpage_detailed_course_record").html("<thead><tr><th>Course Name</th><th>Course Code</th><th>#Semester</th><th>#Sections</th><th>Action</th></tr></thead>");
						
                    var table = $('#dashboard_subpage_detailed_course_record').DataTable();
                    table.clear().destroy();
                    $('#dashboard_subpage_detailed_course_record').DataTable({
                        data: getSemesterCourseSectionDetailByUser,
                        columns: [
                            { data: "course_name" },
                            { data: "course_code" },
                            { data: "term_batch_sem_no" },
                            { data: "section_name" },
                            {
                                data: null,
                                className: 'action-buttons',
                                defaultContent: '<button class="btn btn-primary btn-sm edit-btn">Upload</button>' +
                                                '<button class="btn btn-warning btn-sm view-btn">List</button>' 
                                                // '<button class="btn btn-danger btn-sm delete-btn">Delete</button>'
                            },
                             // Hidden column for course_id
                            { data: "course_id", visible: false },
                            // Hidden column for section_id
                            { data: "section_id", visible: false }
                        ],
                        createdRow: function(row, data, dataIndex) 
                        {
                            // Add the onclick functionality for the buttons
                            $(row).find('.edit-btn').click(function() {
                                // Call the function for edit button
                                uploadCourse(data, dataIndex);
                            });
                            $(row).find('.view-btn').click(function() {
                                // Call the function for view button
                                listCourse(data, dataIndex);
                            });
                            $(row).find('.delete-btn').click(function() {
                                // Call the function for delete button
                                deleteCourse(data, dataIndex);
                            });
                        }
                    });
                    
                },
                error: function(xhr, status, error){
                    console.error(xhr);
                }
            });
        }

        function uploadCourse(data, index) 
        {
            let clgId= JSON.parse(localStorage.getItem("ReqData")).clg_id
            let authCode = auth
            let uId = JSON.parse(localStorage.getItem("ReqData")).user_id 
            // Handle the edit button click event
            console.log('Edit clicked for course:', data.course_name, 'at index', index);
            // Add your edit logic here, such as opening a modal with course details to edit
            console.log('Upload clicked for course:', data.course_name, 'at index', index);
            // Populate the modal with course data
            $('#courseName').val(data.course_name);  // Set the course name in the modal input
            $('#sectionName').val(data.section_name); // Set the section name in the modal input
            $('#courseId').val(data.course_id);  // Set the course name in the modal input
            $('#sectionId').val(data.section_id); // Set the section name in the modal input
            $('#clgId').val(clgId);  // Set the course name in the modal input
            $('#uId').val(uId); // Set the section name in the modal input
            $('#authCode').val(authCode); // Set the section name in the modal input
            // Optionally store the course_id and section_id for later use (e.g., for uploading)
            $('#uploadCourseModal').data('course_id', data.course_id);
            $('#uploadCourseModal').data('section_id', data.section_id);
            // Show the modal
            $('#uploadCourseModal').modal('show');
        }

        function listCourse(data, index) {

            let clgId= JSON.parse(localStorage.getItem("ReqData")).clg_id
            let authCode = auth
            let uId = JSON.parse(localStorage.getItem("ReqData")).user_id 
            // Populate the modal with course data
            $('#courseName').val(data.course_name);  // Set the course name in the modal input
            $('#sectionName').val(data.section_name); // Set the section name in the modal input
            
            $('#courseId').val(data.course_id);  // Set the course name in the modal input
            $('#sectionId').val(data.section_id); // Set the section name in the modal input
            
            $('#clgId').val(clgId);  // Set the course name in the modal input
            $('#uId').val(uId); // Set the section name in the modal input
            $('#authCode').val(authCode); // Set the section name in the modal input            

            // Handle the view button click event
            console.log('View clicked for course:', data.course_name, 'at index', index);
            // Add your view logic here, such as opening a modal with course details to view
            var formData = new FormData();
            // Add other parameters (clgId, courseId, sectionId, userId) to the FormData
            let getClgId = $("#clgId").val()
            let courseId = $("#courseId").val()
            let sectionId = $("#sectionId").val()
            let getUId = $("#uId").val()
            let activityId = $("#activityId").val() ?  $("#activityId").val() : 0; 

            // formData.append('clgId', $("#clgId").val()  );
            // formData.append('courseId',  $("#courseId").val());
            // formData.append('sectionId', $("#sectionId").val());
            // formData.append('userId', $("#uId").val());
            // let activityId =  $("#activityId").val() ?  $("#activityId").val() : 0; 
            // formData.append('activityId',activityId);

            // Send the form data using AJAX to the PHP backend
            $.ajax({
                url:  `https://liveconf-dev.quiklrn.net/liveconf/s3Reports/public_html/index.php?method=getListOffiles&clgId=${getClgId}&courseId=${courseId}&sectionId=${sectionId}&uId=${getUId}&activityId=${activityId}`,  // Replace with the correct PHP script path
                type: 'GET',
                data: formData,
                dataType: 'json',
                processData: false,  // Don't process the data
                contentType: false,  // Don't set content type (form-data will set it automatically)
                success: function(response)
                {
                    console.log(response);  // You can use the data directly here
                    // Example: Loop through the JSON data and add it to the table
                    if(response.length > 0) {
                        var tableRows = '';
                        $.each(response, function(index, file) {
                            tableRows += '<tr>';
                            tableRows += '<td>' + file.file_name + '</td>';
                            tableRows += '<td><a href="' + file.uri + '" target="_blank">Download</a></td>';
                            tableRows += '</tr>';
                        });
                        // Append the rows to the table body
                        $('#fileTable tbody').html(tableRows);
                        $('#listCourseModal').modal('show');
                    }else {
                        $('#fileTable tbody').html('<tr><td colspan="2">No files found.</td></tr>');
                    }
                    
                },
                error: function(xhr, status, error) {
                    // Handle any errors from the AJAX request
                    console.error(xhr.responseText);
                    alert("There was an error uploading the file.");
                }
            });
        }

        function deleteCourse(data, index) {
            // Handle the delete button click event
            console.log('Delete clicked for course:', data.course_name, 'at index', index);
            // Add your delete logic here, such as showing a confirmation dialog
        }

       
        $('#uploadFile').on('change', function(event) 
            {
                var fileInput = $('#uploadFile')[0];  // Get the file input element
                var file = fileInput.files[0];  // Get the selected file
                if (file) {
                    var formData = new FormData();
                    formData.append('uploadFile', file);  // Append the selected file to the form data
                    // Add other parameters (clgId, courseId, sectionId, userId) to the FormData
                    formData.append('clgId', $("#clgId").val()  );
                    formData.append('courseId',  $("#courseId").val());
                    formData.append('sectionId', $("#sectionId").val());
                    formData.append('userId', $("#uId").val());

                    let activityId =  $("#activityId").val() ?  $("#activityId").val() : 0; 
                  
                    formData.append('activityId',activityId);
                   
                    // Send the form data using AJAX to the PHP backend
                    $.ajax({
                        url:  'https://liveconf-dev.quiklrn.net/liveconf/s3Reports/public_html/index.php?method=s3AccessUpload',  // Replace with the correct PHP script path
                        type: 'POST',
                        data: formData,
                        processData: false,  // Don't process the data
                        contentType: false,  // Don't set content type (form-data will set it automatically)
                        success: function(response)
                        {
                            console.log(response);
                            alert("File uploaded successfully.");
                        },
                        error: function(xhr, status, error) {
                            // Handle any errors from the AJAX request
                            console.error(xhr.responseText);
                            alert("There was an error uploading the file.");
                        }
                    });
                } else {
                    alert("Please select a file to upload.");
                }
            });
    </script>




</body>

</html>