<?php
session_start();
if(isset($_SESSION['username'])){
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">


    <?php
    include 'includes/styles.php';
    global $school_name;
    ?>
    <title> Asset Template Manager |  <?php echo $school_name; ?> </title>
    <?php
    $module_name = 'Mark Setting';
    include "check-admin-privilege.php";
    ?>

    <style>
        .fa-edit, .fa-trash{
            background-color: transparent;
        }
    </style>

</head>
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">

    <!-- Navbar -->
    <?php include 'includes/notifications.php'; ?>
    <!-- /.navbar -->

    <!-- Main Sidebar Container -->
    <?php include "includes/sidebar.php";?>

    <!-- Content Wrapper. Contains page content -->
    <div class="content-wrapper">
        <!-- Content Header (Page header) -->
        <div class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1 class="m-0">Asset Template Manager</h1>
                    </div><!-- /.col -->
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="<?php echo $conn->base_url();?>">Home</a></li>
                            <li class="breadcrumb-item active">Assessment Templates</li>
                        </ol>
                    </div><!-- /.col -->
                </div><!-- /.row -->
            </div><!-- /.container-fluid -->
        </div>
        <!-- /.content-header -->
        <!-- Main content -->
        <section class="content">
            <div class="container-fluid">

                <!-- Create Template Card -->
                <div class="card card-primary collapsed-card">
                    <div class="card-header">
                        <h3 class="card-title">Create New Assessment Template(<span class="text-dark">Click the <i class="fas fa-plus" style="color: white;"></i> icon</span>)</h3>
                        <div class="card-tools">
                            <button type="button" class="btn btn-tool" data-card-widget="collapse">
                                <i class="fas fa-plus" style="color: white;"></i>
                            </button>
                        </div>
                    </div>
                    <div class="card-body" style="display: none;">
                        <form id="templateForm">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>Template Name <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="templateName" name="template_name" required>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label>Class <span class="text-danger">*</span></label>
                                        <select class="form-control" id="templateClass" name="class" required>
                                            <option value="">Select Class</option>
                                            <!-- Populate from database -->
                                            <?php
                                              $sql = "SELECT * FROM classes";
                                              $conn->query($sql);
                                              $result = $conn->fetchMultiple();
                                              if(count($result) > 0):
                                                  foreach ($result as $row):
                                            ?>
                                            <option value="<?php echo $row->name;?>"><?php echo $row->name;?></option>
                                            <?php
                                                endforeach;
                                             else:
                                            ?>
                                            <option value="">No Classes Found</option>
                                            <?php
                                             endif;
                                            ?>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label>Term <span class="text-danger">*</span></label>
                                        <select class="form-control" id="templateTerm" name="term" required>
                                            <option value="">Select Term</option>
                                            <option value="1st term">1st Term</option>
                                            <option value="2nd term">2nd Term</option>
                                            <option value="3rd term">3rd Term</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label>Description</label>
                                        <textarea class="form-control" id="templateDescription" name="description" rows="2"></textarea>
                                    </div>
                                </div>
                            </div>

                            <!-- Assessment Components Section -->
                            <div class="card card-secondary">
                                <div class="card-header">
                                    <h3 class="card-title">Assessment Components</h3>
                                    <button type="button" class="btn btn-sm btn-success float-right" id="addComponent">
                                        <i class="fas fa-plus"></i> Add Component
                                    </button>
                                </div>
                                <div class="card-body">
                                    <div id="componentsContainer">
                                        <!-- Dynamic components will be added here -->
                                    </div>
                                    <div class="row mt-3">
                                        <div class="col-md-12">
                                            <div class="alert alert-info">
                                                <strong>Total Marks: <span id="totalMarks">0</span>/100</strong>
                                                <div id="marksValidation" class="text-danger" style="display: none;"></div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-12">
                                    <button type="submit" class="btn btn-primary" id="saveTemplate">
                                        <i class="fas fa-save"></i> Save Template
                                    </button>
                                    <button type="button" class="btn btn-secondary ml-2" id="resetForm">
                                        <i class="fas fa-undo"></i> Reset
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Existing Templates -->
                <div class="card card-info">
                    <div class="card-header">
                        <h3 class="card-title">Existing Assessment Templates</h3>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table id="templatesTable" class="table table-bordered table-striped">
                                <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Template Name</th>
                                    <th>Class</th>
                                    <th>Term</th>
                                    <th>Components</th>
                                    <th>Total Marks</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                                </thead>
                                <tbody id="templatesTableBody">
                                <!-- Data will be populated via AJAX -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

            </div>
        </section>
    </div>
</div>

<!-- Component Template (Hidden) -->
<div id="componentTemplate" style="display: none;">
    <div class="component-row border rounded p-3 mb-3">
        <div class="row">
            <div class="col-md-4">
                <div class="form-group">
                    <label>Component Name</label>
                    <input type="text" class="form-control component-name" name="component_name[]" placeholder="e.g., 1st CA, Project" required>
                </div>
            </div>
            <div class="col-md-3">
                <div class="form-group">
                    <label>Database Key</label>
                    <input type="text" class="form-control component-key" name="component_key[]" placeholder="e.g., first_ca, project" required>
                </div>
            </div>
            <div class="col-md-3">
                <div class="form-group">
                    <label>Max Marks</label>
                    <input type="number" class="form-control component-marks" name="max_marks[]" min="1" max="100" required>
                </div>
            </div>
            <div class="col-md-2">
                <div class="form-group">
                    <label>&nbsp;</label>
                    <div>
                        <button type="button" class="btn btn-sm btn-danger remove-component">
                            <i class="fas fa-trash"></i>
                        </button>
                        <button type="button" class="btn btn-sm btn-secondary move-up">
                            <i class="fas fa-arrow-up"></i>
                        </button>
                        <button type="button" class="btn btn-sm btn-secondary move-down">
                            <i class="fas fa-arrow-down"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
        <!-- /.content -->
    </div>
    <!-- /.content-wrapper -->
    <?php include "includes/footer.php";?>
    <script>
        $(function () {
            $("#teacher").DataTable({
                "responsive": true, "lengthChange": false, "autoWidth": false,
                "buttons": ["copy", "csv", "pdf", "print"]
            }).buttons().container().appendTo('#teacher_wrapper .col-md-6:eq(0)');
            $('#example2').DataTable({
                "paging": true,
                "lengthChange": false,
                "searching": true,
                "ordering": true,
                "info": true,
                "autoWidth": false,
                "responsive": true
            });
        });
    </script>
    <script>
        $(document).ready(function(){
            $('[data-toggle="tooltip"]').tooltip();
        });
    </script>

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

        // Add new component
        $('#addComponent').click(function() {
            addComponent();
        });

        // Remove component
        $(document).on('click', '.remove-component', function() {
            $(this).closest('.component-row').remove();
            updateTotalMarks();
            updateComponentOrder();
        });

        // Move component up
        $(document).on('click', '.move-up', function() {
            const row = $(this).closest('.component-row');
            const prev = row.prev('.component-row');
            if (prev.length) {
                row.insertBefore(prev);
                updateComponentOrder();
            }
        });

        // Move component down
        $(document).on('click', '.move-down', function() {
            const row = $(this).closest('.component-row');
            const next = row.next('.component-row');
            if (next.length) {
                row.insertAfter(next);
                updateComponentOrder();
            }
        });

        // Update total marks when marks change
        $(document).on('input', '.component-marks', function() {
            updateTotalMarks();
        });

        // Auto-generate database key from component name
        $(document).on('input', '.component-name', function() {
            const name = $(this).val();
            const key = name.toLowerCase()
                .replace(/[^a-z0-9\s]/g, '')
                .replace(/\s+/g, '_')
                .replace(/_+/g, '_')
                .replace(/^_|_$/g, '');
            $(this).closest('.component-row').find('.component-key').val(key);
        });

        // Form submission
        $('#templateForm').submit(function(e) {
            e.preventDefault();

            const totalMarks = parseInt($('#totalMarks').text());
            if (totalMarks !== 100) {
                Swal.fire({
                    icon: 'error',
                    title: 'Invalid Total Marks',
                    text: 'Total marks must equal 100. Current total: ' + totalMarks
                });
                return;
            }

            const components = $('.component-row').length;
            if (components === 0) {
                Swal.fire({
                    icon: 'error',
                    title: 'No Components',
                    text: 'Please add at least one assessment component.'
                });
                return;
            }

            // Validate unique component names and keys
            const names = [];
            const keys = [];
            let isValid = true;

            $('.component-name').each(function() {
                const name = $(this).val().trim();
                if (names.includes(name)) {
                    isValid = false;
                    $(this).addClass('is-invalid');
                } else {
                    names.push(name);
                    $(this).removeClass('is-invalid');
                }
            });

            $('.component-key').each(function() {
                const key = $(this).val().trim();
                if (keys.includes(key)) {
                    isValid = false;
                    $(this).addClass('is-invalid');
                } else {
                    keys.push(key);
                    $(this).removeClass('is-invalid');
                }
            });

            if (!isValid) {
                Swal.fire({
                    icon: 'error',
                    title: 'Duplicate Values',
                    text: 'Component names and database keys must be unique.'
                });
                return;
            }

            // Check if in edit mode
            const isEditMode = $(this).data('edit-mode');
            if (isEditMode) {
                updateTemplate();
            } else {
                saveTemplate();
            }
        });

        // Reset form
        $('#resetForm').click(function() {
            resetEditForm();
        });

        // Add initial component
        addComponent();

        // Load existing templates
        loadTemplates();

        function addComponent(updateMarks = true) {
            componentCounter++;
            const template = $('#componentTemplate').html();
            $('#componentsContainer').append(template);
            if (updateMarks) {
                updateTotalMarks();
            }
            updateComponentOrder();
        }

        function updateTotalMarks() {
            let total = 0;
            $('.component-marks').each(function() {
                const value = parseInt($(this).val()) || 0;
                total += value;
            });

            $('#totalMarks').text(total);

            if (total > 100) {
                $('#marksValidation').text('Total marks cannot exceed 100').show();
                $('#totalMarks').parent().removeClass('alert-info').addClass('alert-danger');
            } else if (total < 100) {
                $('#marksValidation').text('Total marks should equal 100').show();
                $('#totalMarks').parent().removeClass('alert-info alert-danger').addClass('alert-warning');
            } else {
                $('#marksValidation').hide();
                $('#totalMarks').parent().removeClass('alert-danger alert-warning').addClass('alert-info');
            }
        }

        function updateComponentOrder() {
            $('.component-row').each(function(index) {
                $(this).find('input[name="display_order[]"]').remove();
                $(this).append('<input type="hidden" name="display_order[]" value="' + (index + 1) + '">');
            });
        }

        function saveTemplate() {
            const formData = new FormData($('#templateForm')[0]);

            $.ajax({
                url: 'ajax/save_assessment_template.php',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                beforeSend: function() {
                    $('#saveTemplate').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Saving...');
                },
                success: function(response) {
                    const result = JSON.parse(response);
                    if (result.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Success',
                            text: 'Assessment template saved successfully!'
                        }).then(() => {
                            $('#resetForm').click();
                            loadTemplates();
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: result.message
                        });
                    }
                },
                error: function() {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'An error occurred while saving the template.'
                    });
                },
                complete: function() {
                    $('#saveTemplate').prop('disabled', false).html('<i class="fas fa-save"></i> Save Template');
                }
            });
        }

        function updateTemplate() {
            const formData = new FormData($('#templateForm')[0]);
            formData.append('template_id', $('#templateForm').data('template-id'));

            $.ajax({
                url: 'ajax/update_assessment_template.php',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                beforeSend: function() {
                    $('#saveTemplate').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Updating...');
                },
                success: function(response) {
                    const result = JSON.parse(response);
                    if (result.success) {
                        let message = result.message;
                        if (result.limited_update) {
                            Swal.fire({
                                icon: 'warning',
                                title: 'Limited Update',
                                text: message
                            });
                        } else {
                            Swal.fire({
                                icon: 'success',
                                title: 'Success',
                                text: message
                            });
                        }

                        resetEditForm();
                        loadTemplates();
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: result.message
                        });
                    }
                },
                error: function() {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'An error occurred while updating the template.'
                    });
                },
                complete: function() {
                    $('#saveTemplate').prop('disabled', false).html('<i class="fas fa-save"></i> Save Template');
                }
            });
        }

        // Reset form
        $('#resetForm').click(function() {
            resetEditForm();
        });

        function resetEditForm(){
            $('#templateForm').removeData('edit-mode');
            $('#templateForm').removeData('template-id');
            $('#templateForm')[0].reset();
            $('#componentsContainer').empty();
            addComponent(); // Add one default component
            // Update total marks after component is added
            setTimeout(function() {
                updateTotalMarks();
            }, 100);
            $('#saveTemplate').html('<i class="fas fa-save"></i> Save Template');
            $('#cancelEdit').remove();
        }

        function loadTemplates() {
            $.ajax({
                url: 'ajax/get_assessment_templates.php',
                type: 'GET',
                success: function(response) {
                    const templates = JSON.parse(response);
                    let html = '';

                    templates.forEach(function(template, index) {
                        html += `
                            <tr>
                                <td>${index + 1}</td>
                                <td>${template.template_name}</td>
                                <td>${template.class}</td>
                                <td>${template.term}</td>
                                <td>
                                    <small class="text-muted">
                                        ${template.components.map(c => c.component_name + ' (' + c.max_marks + ')').join(', ')}
                                    </small>
                                </td>
                                <td>${template.total_marks}</td>
                                <td>
                                    <span class="badge badge-${template.status === 'active' ? 'success' : 'secondary'}">
                                        ${template.status}
                                    </span>
                                </td>
                                <td>
                                    <button class="btn btn-sm btn-info edit-template" data-id="${template.id}">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <button class="btn btn-sm btn-danger delete-template" data-id="${template.id}">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                    ${template.status === 'active' ?
                            '<button class="btn btn-sm btn-warning deactivate-template" data-id="' + template.id + '"><i class="fas fa-pause"></i></button>' :
                            '<button class="btn btn-sm btn-success activate-template" data-id="' + template.id + '"><i class="fas fa-play"></i></button>'
                        }
                                </td>
                            </tr>
                        `;
                    });

                    $('#templatesTableBody').html(html);
                }
            });
        }

        // Template actions
        $(document).on('click', '.edit-template', function() {
            const id = $(this).data('id');
            editTemplate(id);
        });

        $(document).on('click', '.delete-template', function() {
            const id = $(this).data('id');
            deleteTemplate(id);
        });

        $(document).on('click', '.activate-template, .deactivate-template', function() {
            const id = $(this).data('id');
            const action = $(this).hasClass('activate-template') ? 'activate' : 'deactivate';
            toggleTemplateStatus(id, action);
        });

        function editTemplate(id) {
            $.ajax({
                url: 'ajax/get_template_by_id.php',
                type: 'GET',
                data: {id: id},
                success: function(response) {
                    const result = JSON.parse(response);
                    if (result.success) {
                        populateEditForm(result.template);
                        // Expand the create template card for editing
                        if ($('.card').first().hasClass('collapsed-card')) {
                            $('.card').first().find('[data-card-widget="collapse"]').click();
                        }
                    } else {
                        Swal.fire('Error!', result.message, 'error');
                    }
                },
                error: function() {
                    Swal.fire('Error!', 'Failed to load template data', 'error');
                }
            });
        }

        function populateEditForm(template) {
            // Set form to edit mode
            $('#templateForm').data('edit-mode', true);
            $('#templateForm').data('template-id', template.id);

            // Populate basic fields
            $('#templateName').val(template.template_name);
            $('#templateClass').val(template.class).trigger('change');
            $('#templateTerm').val(template.term).trigger('change');
            $('#templateDescription').val(template.description);

            // Clear existing components
            $('#componentsContainer').empty();

            // Add components without updating marks
            template.components.forEach(function(component) {
                addComponent(false);
            });
            
            // Need to wait for DOM to update before populating values
            setTimeout(function() {
                const components = $('.component-row');
                template.components.forEach(function(component, index) {
                    const componentRow = $(components[index]);
                    componentRow.find('.component-name').val(component.component_name);
                    componentRow.find('.component-key').val(component.component_key);
                    componentRow.find('.component-marks').val(component.max_marks);
                });
                
                updateTotalMarks();
            }, 100);

            // Update submit button text
            $('#saveTemplate').html('<i class="fas fa-save"></i> Update Template');

            // Add cancel edit button
            if ($('#cancelEdit').length === 0) {
                $('#saveTemplate').after('<button type="button" class="btn btn-warning ml-2" id="cancelEdit"><i class="fas fa-times"></i> Cancel Edit</button>');
            }

            // Scroll to form
            $('html, body').animate({
                scrollTop: $('.card').first().offset().top - 100
            }, 500);
        }

        // Add event handler for cancel edit button
        $(document).on('click', '#cancelEdit', function() {
            resetEditForm();
        });

        function deleteTemplate(id) {
            Swal.fire({
                title: 'Are you sure?',
                text: "This action cannot be undone!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                cancelButtonColor: '#3085d6',
                confirmButtonText: 'Yes, delete it!'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: 'ajax/delete_assessment_template.php',
                        type: 'POST',
                        data: {id: id},
                        success: function(response) {
                            const result = JSON.parse(response);
                            if (result.success) {
                                Swal.fire('Deleted!', 'Template has been deleted.', 'success');
                                loadTemplates();
                            } else {
                                Swal.fire('Error!', result.message, 'error');
                            }
                        }
                    });
                }
            });
        }

        function toggleTemplateStatus(id, action) {
            $.ajax({
                url: 'ajax/toggle_template_status.php',
                type: 'POST',
                data: {id: id, action: action},
                success: function(response) {
                    const result = JSON.parse(response);
                    if (result.success) {
                        Swal.fire('Success!', `Template ${action}d successfully.`, 'success');
                        loadTemplates();
                    } else {
                        Swal.fire('Error!', result.message, 'error');
                    }
                }
            });
        }
    });
</script>



    <?php
    }else{
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, shrink-to-fit=no">

        <?php include 'includes/styles.php'; global $school_name; ?>
        <title>Login to continue |  <?php echo $school_name; ?> </title>

        <!-- END PAGE LEVEL PLUGINS/CUSTOM STYLES -->

    </head>
    <body>
    <div class="container" style="margin-top: 20%;">
        <div class="row">
            <div class="col-lg-12 col-md-12">
                <div class="section-title text-center">
                    <h6> You need to login to continue </h6>
                    <div class="spinner-border text-info" role="status">
                        <span class="sr-only">Loading...</span>
                        <meta http-equiv='refresh' content='3; <?php echo $link; ?>'>
                    </div>
                    <p>Redirecting to the login  page...</p>
                </div>
            </div>
        </div>
    </div>

    <?php
    }

    ?>
