<?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'; ?>
        <title>Add Learning Material | <?php echo $school_name; ?></title>
        <style>
            .upload-area {
                border: 2px dashed #007bff;
                border-radius: 5px;
                padding: 30px;
                text-align: center;
                background: #f8f9fa;
                cursor: pointer;
                transition: all 0.3s;
            }
            .upload-area:hover {
                background: #e9ecef;
                border-color: #0056b3;
            }
            .upload-area.dragover {
                background: #d4edff;
                border-color: #0056b3;
            }
            .file-preview {
                margin-top: 15px;
                padding: 10px;
                background: #fff;
                border: 1px solid #dee2e6;
                border-radius: 5px;
            }
            .material-type-icon {
                font-size: 48px;
                margin-bottom: 15px;
            }
        </style>
    </head>
    <body class="hold-transition sidebar-mini layout-fixed">
    <div class="wrapper">
        <?php include 'includes/notifications.php'; ?>
        <?php include "includes/sidebar.php"; ?>

        <div class="content-wrapper">
            <div class="content-header">
                <div class="container-fluid">
                    <div class="row mb-2">
                        <div class="col-sm-6">
                            <h1 class="m-0">Add Learning Material</h1>
                        </div>
                        <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"><a href="<?php echo $conn->base_url();?>learning-materials">Learning Materials</a></li>
                                <li class="breadcrumb-item active">Add Material</li>
                            </ol>
                        </div>
                    </div>
                </div>
            </div>

            <section class="content">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-md-10">
                            <div class="card card-primary">
                                <div class="card-header">
                                    <h3 class="card-title">Material Details</h3>
                                </div>

                                <form class="form-horizontal" id="material-add-form" method="POST" enctype="multipart/form-data">
                                    <div class="card-body">

                                        <!-- Material Type Selection -->
                                        <div class="form-group row">
                                            <label class="col-sm-3 col-form-label">Material Type <span class="text-danger">*</span></label>
                                            <div class="col-sm-9">
                                                <div class="btn-group btn-group-toggle" data-toggle="buttons">
                                                    <label class="btn btn-outline-primary active">
                                                        <input type="radio" name="material_type" value="pdf" id="type_pdf" checked>
                                                        <i class="fas fa-file-pdf"></i> PDF
                                                    </label>
                                                    <label class="btn btn-outline-primary">
                                                        <input type="radio" name="material_type" value="video" id="type_video">
                                                        <i class="fas fa-video"></i> Video
                                                    </label>
                                                    <label class="btn btn-outline-primary">
                                                        <input type="radio" name="material_type" value="document" id="type_doc">
                                                        <i class="fas fa-file-word"></i> Document
                                                    </label>
                                                    <label class="btn btn-outline-primary">
                                                        <input type="radio" name="material_type" value="link" id="type_link">
                                                        <i class="fas fa-link"></i> External Link
                                                    </label>
                                                    <label class="btn btn-outline-primary">
                                                        <input type="radio" name="material_type" value="audio" id="type_audio">
                                                        <i class="fas fa-music"></i> Audio
                                                    </label>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Title -->
                                        <div class="form-group row">
                                            <label for="title" class="col-sm-3 col-form-label">Title <span class="text-danger">*</span></label>
                                            <div class="col-sm-9">
                                                <input type="text" class="form-control" id="title" name="title" required>
                                            </div>
                                        </div>

                                        <!-- Description -->
                                        <div class="form-group row">
                                            <label for="description" class="col-sm-3 col-form-label">Description</label>
                                            <div class="col-sm-9">
                                                <textarea class="form-control" id="description" name="description" rows="4" placeholder="Provide details about this material..."></textarea>
                                            </div>
                                        </div>

                                        <!-- Class Selection -->
                                        <div class="form-group row">
                                            <label for="class" class="col-sm-3 col-form-label">Class <span class="text-danger">*</span></label>
                                            <div class="col-sm-9">
                                                <?php
                                                $sql = "SELECT * FROM classes ORDER BY name";
                                                $conn->query($sql);
                                                $classes = $conn->fetchMultiple();
                                                ?>
                                                <select name="class" id="classID" class="form-control select2" required>
                                                    <option value="">Select class</option>
                                                    <?php
                                                    if ($conn->rowCount() > 0) {
                                                        foreach ($classes as $class) {
                                                            echo "<option value='{$class->id}'>{$class->name}</option>";
                                                        }
                                                    } else {
                                                        echo "<option value=''>No classes found</option>";
                                                    }
                                                    ?>
                                                </select>
                                            </div>
                                        </div>

                                        <!-- Section Selection -->
                                      <div class="form-group row">
                                            <label for="section" class="col-sm-3 col-form-label">Section <span class="text-danger">*</span></label>
                                            <div class="col-sm-9">
                                                <select name="section" id="section" class="form-control select2"required>
                                                    <option value="">Select class first</option>
                                                </select>
                                            </div>
                                        </div>

                                        <!-- Subject Selection -->
                                        <div class="form-group row">
                                            <label for="subject" class="col-sm-3 col-form-label">Subject <span class="text-danger">*</span></label>
                                            <div class="col-sm-9">
                                                <select name="subject" id="subject" class="form-control select2" required>
                                                    <option value="">Select class first</option>
                                                </select>
                                            </div>
                                        </div>

                                        <!-- Term Selection -->
                                        <div class="form-group row">
                                            <label for="term" class="col-sm-3 col-form-label">Term <span class="text-danger">*</span></label>
                                            <div class="col-sm-9">
                                                <?php
                                                $sql = "SELECT * FROM terms ORDER BY name";
                                                $conn->query($sql);
                                                $terms = $conn->fetchMultiple();
                                                ?>
                                                <select name="term" id="term" class="form-control select2" required>
                                                    <option value="">Select term</option>
                                                    <?php
                                                    if ($conn->rowCount() > 0) {
                                                        foreach ($terms as $term) {
                                                            echo "<option value='{$term->id}'>{$term->name}</option>";
                                                        }
                                                    }
                                                    ?>
                                                </select>
                                            </div>
                                        </div>

                                        <!-- File Upload Area (Hidden for external links) -->
                                        <div class="form-group row" id="file-upload-section">
                                            <label class="col-sm-3 col-form-label">Upload File <span class="text-danger">*</span></label>
                                            <div class="col-sm-9">
                                                <div class="upload-area" id="upload-area">
                                                    <div class="material-type-icon">
                                                        <i class="fas fa-cloud-upload-alt text-primary"></i>
                                                    </div>
                                                    <h5>Drag & Drop your file here</h5>
                                                    <p class="text-muted">or click to browse</p>
                                                    <p class="text-muted small" id="file-type-hint">Accepted: PDF files up to 50MB</p>
                                                    <input type="file" id="material_file" name="material_file" style="display: none;" accept=".pdf">
                                                </div>
                                                <div class="file-preview" id="file-preview" style="display: none;">
                                                    <div class="d-flex justify-content-between align-items-center">
                                                        <div>
                                                            <i class="fas fa-file mr-2"></i>
                                                            <span id="file-name"></span>
                                                            <small class="text-muted ml-2" id="file-size"></small>
                                                        </div>
                                                        <button type="button"class="btn btn-sm btn-danger" id="remove-file">
                                                            <i class="fas fa-times"></i>
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- External Link (Visible for link type) -->
                                        <div class="form-group row" id="external-link-section" style="display: none;">
                                            <label for="external_link" class="col-sm-3 col-form-label">External Link <span class="text-danger">*</span></label>
                                            <div class="col-sm-9">
                                                <input type="url" class="form-control" id="external_link" name="external_link" placeholder="https://example.com/resource">
                                                <small class="form-text text-muted">Provide the full URL (e.g., YouTube link, Google Drive link, etc.)</small>
                                            </div>
                                        </div>

                                        <!-- Duration (for videos/audio) -->
                                       <div class="form-group row" id="duration-section" style="display: none;">
                                            <label for="duration" class="col-sm-3 col-form-label">Duration</label>
                                            <div class="col-sm-9">
                                                <input type="text" class="form-control" id="duration"name="duration" placeholder="e.g., 15:30 or 1:45:30">
                                                <small class="form-text text-muted">Format: MM:SS or HH:MM:SS</small>
                                            </div>
                                        </div>

                                        <!-- Status -->
                                        <div class="form-group row">
                                            <label for="status" class="col-sm-3 col-form-label">Status <span class="text-danger">*</span></label>
                                            <div class="col-sm-9">
                                                <select name="status" id="status" class="form-control" required>
                                                    <option value="active">Active</option>
                                                    <option value="inactive">Inactive</option>
                                                </select>
                                            </div>
                                        </div>

                                        <!-- Submit Button -->
                                        <div class="form-group row">
                                            <label class="col-sm-3 col-form-label"></label>
                                            <div class="col-sm-9">
                                                <button type="submit" name="add_material" class="btn btn-primary" id="submit-btn">
                                                    <i class="fas fa-save"></i> Add Material
                                                </button>
                                                <a href="<?php echo $conn->base_url();?>learning-materials" class="btn btn-secondary">
                                                    <i class="fas fa-times"></i> Cancel
                                                </a>
                                            </div>
                                        </div>

                                    </div>
                                    <div id="success-msg"></div>
                                </form>
                            </div>

                            <!-- Info Alert -->
                            <div class="alert alert-info">
                                <h5><i class="icon fas fa-info"></i> Note:</h5>
                                <ul class="mb-0">
                                    <li>Maximum file size: 50MB for PDFs, 200MB for videos</li>
                                    <li>Supported video formats: MP4, AVI, MOV, WebM</li>
                                    <li>Supported audio formats: MP3, WAV, OGG</li>
                                    <li>For large video files, consider uploading to YouTube and using external link</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </div>

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

        <script>
            $(function() {
                $('.select2').select2();
            });

            // Fetch sections based on class selection
            $('#classID').on('change', function() {
                var classID = $(this).val();
                if (classID) {
                    $.ajax({
                        type: 'POST',
                        url: 'fetch_section.php',
                        data: 'classesID=' + classID,
                        success: function(html) {
                            $('#section').html(html);
                        }
                    });

                    // Fetch subjects for the class
                    $.ajax({
                        type: 'POST',
                        url: 'fetch_subject.php',
                        data: 'classesID=' + classID,
                        success: function(html) {
                            $('#subject').html(html);
                        }
                    });
                } else {
                    $('#section').html('<option value="">Select class first</option>');
                    $('#subject').html('<option value="">Select class first</option>');
                }
            });

            // Handle material type change
            $('input[name="material_type"]').on('change', function() {
                var type = $(this).val();
                var fileInput = $('#material_file');
               var fileHint = $('#file-type-hint');
                var fileUploadSection = $('#file-upload-section');
                var externalLinkSection = $('#external-link-section');
                var durationSection = $('#duration-section');

                // Reset visibility
                fileUploadSection.show();
                externalLinkSection.hide();
                durationSection.hide();

               //Update based on type
                switch(type) {
                    case 'pdf':
                        fileInput.attr('accept', '.pdf');
                        fileHint.text('Accepted: PDF files up to 50MB');
                        break;
                    case 'video':
                        fileInput.attr('accept', '.mp4,.avi,.mov,.webm');
                        fileHint.text('Accepted: MP4, AVI, MOV, WebM up to 200MB');
                        durationSection.show();
                        break;
                    case 'document':
                        fileInput.attr('accept', '.doc,.docx,.txt,.ppt,.pptx');
                        fileHint.text('Accepted: DOC, DOCX, TXT, PPT, PPTX up to 50MB');
                        break;
                    case 'audio':
                        fileInput.attr('accept', '.mp3,.wav,.ogg');
                        fileHint.text('Accepted: MP3, WAV, OGG up to 50MB');
                        durationSection.show();
                        break;
                    case 'link':
                        fileUploadSection.hide();
                        externalLinkSection.show();
                        durationSection.show();
                        break;
                }
            });

            // Drag and drop functionality
            var uploadArea = $('#upload-area');
            var fileInput = $('#material_file');

           uploadArea.on('click', function(e) {
                // Prevent the click event from bubbling up if it's already on the file input
                if (e.target !== fileInput[0]) {
                    fileInput.click();
                }
            });

            uploadArea.on('dragover', function(e) {
                e.preventDefault();
                e.stopPropagation();
                $(this).addClass('dragover');
            });

            uploadArea.on('dragleave', function(e) {
                e.preventDefault();
                e.stopPropagation();
                $(this).removeClass('dragover');
            });

            uploadArea.on('drop', function(e) {
                e.preventDefault();
                e.stopPropagation();
                $(this).removeClass('dragover');

                var files = e.originalEvent.dataTransfer.files;
                if (files.length > 0) {
                    fileInput[0].files = files;
                    displayFilePreview(files[0]);
                }
            });

            fileInput.on('change', function() {
                if(this.files.length > 0) {
                    displayFilePreview(this.files[0]);
                }
            });

            function displayFilePreview(file) {
                var fileSize =(file.size / 1024 / 1024).toFixed(2);
                $('#file-name').text(file.name);
                $('#file-size').text('(' + fileSize + ' MB)');
                $('#file-preview').show();
                uploadArea.hide();
            }

            $('#remove-file').on('click',function() {
                fileInput.val('');
                $('#file-preview').hide();
                uploadArea.show();
            });

            // Form submission
            $('#material-add-form').on('submit', function(e) {
                e.preventDefault();

                var materialType = $('input[name="material_type"]:checked').val();
                var formData =new FormData(this);
                // Ensure add_material parameter is included
                formData.append('add_material', '1');

                // Validate based on material type
               if (materialType === 'link') {
                    if (!$('#external_link').val()) {
                        alert('Please provide an external link');
                        return false;
                    }
                }else {
                    if (!fileInput[0].files.length) {
                        alert('Please select a file to upload');
                        return false;
                   }
                }

                $.ajax({
                    url: 'process-add-material.php',
                    method: 'POST',
                    data: formData,
                    contentType: false,
                    cache: false,
                    processData: false,
                    beforeSend: function() {
                        $('#submit-btn').attr('disabled', 'disabled');
                        $('#submit-btn').html('<i class="fas fa-spinner fa-spin"></i> Uploading material, please wait...');
                    },
                    success: function(data) {
                        $('#submit-btn').attr('disabled', false);
                        $('#submit-btn').html('<i class="fas fa-save"></i> Add Material');
                        $('#success-msg').html(data);

                        // Reset form if successful
                        if (data.includes('success')) {
                            setTimeout(function() {
                                window.location.href = '<?php echo $conn->base_url();?>learning-materials';
                            }, 2000);
                        }
                    },
                    error: function() {
                        $('#submit-btn').attr('disabled', false);
                        $('#submit-btn').html('<i class="fas fa-save"></i> Add Material');
                        alert('An error occurred. Please try again.');
                   }
                });
            });
        </script>
    </body>
    </html>
    <?php
} else {
    ?>
    <!DOCTYPEhtml>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Login to continue | <?php echo $school_name; ?></title>
        <?php include 'includes/styles.php'; ?>
    </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 needto 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 tothe login page...</p>
                </div>
            </div>
        </div>
    </div>
    </body>
    </html>
    <?php
}
?>