<?php
ob_start();
session_start();
if(isset($_SESSION['teacher'])){
    $username = $_SESSION['teacher'];

    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <?php include '../admin/includes/styles.php'; ?>
        <title>Edit Learning Material | <?php echo $school_name; ?></title>
        <?php
        require_once 'Classes/Elearning.php';
        $elearning = new ELearning();

         // Get teacher info
        $sql = "SELECT * FROM teachers WHERE username = :username";
        $conn->query($sql);
        $conn->bind(':username', $username);
        $teacher = $conn->fetchSingle();

        if (!$teacher) {
            header("Location: $teacher_login_link");
            exit();
        }

        $teacher_id = $teacher->id;
        $teacher_name = $teacher->name;

        if (!isset($_GET['id'])) {
            header('Location: learning-materials');
            exit();
        }

        $material_id = (int)$_GET['id'];
        $material = $elearning->getMaterialById($material_id);

        if (!$material) {
            header('Location: learning-materials');
            exit();
        }

        // Check permission (uploader can edit)
        if (
            $material->uploaded_by != $_SESSION['teacher']
        ) {
            header('Location: learning-materials');
            exit();
        }

        ?>
        <style>
            .form-section {
                margin-bottom: 30px;
                padding-bottom: 30px;
                border-bottom: 1px solid #dee2e6;
            }
            .form-section:last-child {
                border-bottom: none;
            }
            .section-title {
                font-size: 18px;
                font-weight: 600;
                margin-bottom: 20px;
                color: #333;
            }
            .current-file-info {
                padding: 15px;
                background: #e7f3ff;
                border-left: 4px solid #007bff;
                border-radius: 4px;
                margin-bottom: 20px;
            }
            .fa-eye, .fa-edit, .fa-trash{
                background-color: transparent;
            }
        </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">Editing Learning Materials</h1>
                        </div>
                        <div class="col-sm-6">
                            <ol class="breadcrumb float-sm-right">
                                <li class="breadcrumb-item"><a href="<?php echo $conn->teacher_url();?>">Home</a></li>
                                <li class="breadcrumb-item"><a href="<?php echo $conn->teacher_url();?>learning-materials">Learning Materials</a></li>
                                <li class="breadcrumb-item active">Edit 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">Edit Material Details</h3>
                                </div>

                                <form class="form-horizontal" id="material-edit-form" method="POST" enctype="multipart/form-data">
                                    <div class="card-body">
                                        <input type="hidden" name="material_id" value="<?php echo $material->id; ?>">

                                        <!-- Material Type Info -->
                                        <div class="form-section">
                                            <div class="section-title">Material Type</div>
                                            <div class="form-group row">
                                                <label class="col-sm-3 col-form-label">Material Type</label>
                                                <div class="col-sm-9">
                                                    <input type="text" class="form-control" value="<?php echo strtoupper($material->material_type); ?>" readonly>
                                                    <small class="form-text text-muted">Cannot be changed after creation</small>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Basic Information -->
                                        <div class="form-section">
                                            <div class="section-title">Basic Information</div>

                                            <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"
                                                           value="<?php echo htmlspecialchars($material->title); ?>" required>
                                                </div>
                                            </div>

                                            <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="5"><?php echo htmlspecialchars($material->description); ?></textarea>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Classification -->
                                        <div class="form-section">
                                            <div class="section-title">Classification</div>

                                            <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">
                                                    <input type="text" class="form-control" value="<?php echo htmlspecialchars($material->class_name); ?>" readonly>
                                                    <small class="form-text text-muted">Cannot be changed after creation</small>
                                                </div>
                                            </div>

                                            <div class="form-group row">
                                                <label for="section" class="col-sm-3 col-form-label">Section</label>
                                                <div class="col-sm-9">
                                                    <input type="text" class="form-control" value="<?php echo htmlspecialchars($material->section_name); ?>" readonly>
                                                    <small class="form-text text-muted">Cannot be changed after creation</small>
                                                </div>
                                            </div>

                                            <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">
                                                    <?php
                                                    $sql = "SELECT id, subject_name FROM subjects WHERE class_id = :class_id ORDER BY subject_name";
                                                    $conn->query($sql);
                                                    $conn->bind(':class_id', $material->class_id);
                                                    $subjects = $conn->fetchMultiple();
                                                    ?>
                                                    <select name="subject" id="subject" class="form-control select2" required>
                                                        <?php
                                                        foreach ($subjects as $subject) {
                                                            $selected = ($subject->id == $material->subject_id) ? 'selected' : '';
                                                            echo "<option value='{$subject->id}' {$selected}>{$subject->subject_name}</option>";
                                                        }
                                                        ?>
                                                    </select>
                                                </div>
                                            </div>

                                            <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>
                                                        <?php
                                                        foreach ($terms as $term) {
                                                            $selected = ($term->id == $material->term_id) ? 'selected' : '';
                                                            echo "<option value='{$term->id}' {$selected}>{$term->name}</option>";
                                                        }
                                                        ?>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Media Details -->
                                        <div class="form-section">
                                            <div class="section-title">Media Details</div>

                                            <?php if ($material->material_type !== 'link'): ?>
                                                <div class="current-file-info">
                                                    <strong><i class="fas fa-file"></i> Current File:</strong><br>
                                                    <?php echo htmlspecialchars(basename($material->file_path)); ?>
                                                    <br>
                                                    <small>Size: <?php echo htmlspecialchars($material->file_size); ?></small>
                                                </div>
                                            <?php endif; ?>

                                            <?php if ($material->material_type === 'video' || $material->material_type === 'audio'): ?>
                                                <div class="form-group row">
                                                    <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"
                                                               value="<?php echo htmlspecialchars($material->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>
                                            <?php endif; ?>

                                            <?php if ($material->material_type === 'link'): ?>
                                                <div class="form-group row">
                                                    <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"
                                                               value="<?php echo htmlspecialchars($material->external_link); ?>" required>
                                                        <small class="form-text text-muted">Provide the full URL (e.g., YouTube link, Google Drive link, etc.)</small>
                                                    </div>
                                                </div>
                                            <?php endif; ?>
                                        </div>

                                        <!-- Status & Visibility -->
                                        <div class="form-section">
                                            <div class="section-title">Status & Visibility</div>

                                            <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" <?php echo ($material->status === 'active') ? 'selected' : ''; ?>>Active</option>
                                                        <option value="inactive" <?php echo ($material->status === 'inactive') ? 'selected' : ''; ?>>Inactive</option>
                                                    </select>
                                                    <small class="form-text text-muted">Inactive materials will not be visible to students</small>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Additional Information -->
                                        <div class="form-section">
                                            <div class="section-title">Additional Information</div>

                                            <div class="row">
                                                <div class="col-md-6">
                                                    <div class="info-box">
                                                        <strong>Uploaded By:</strong><br>
                                                        <?php echo htmlspecialchars($material->uploaded_by); ?>
                                                    </div>
                                                </div>
                                                <div class="col-md-6">
                                                    <div class="info-box">
                                                        <strong>Views:</strong><br>
                                                        <?php echo $material->views_count ?? 0; ?>
                                                    </div>
                                                </div>
                                            </div>

                                            <div class="row">
                                                <div class="col-md-6">
                                                    <div class="info-box">
                                                        <strong>Created:</strong><br>
                                                        <?php echo date('M d, Y \a\t h:i A', strtotime($material->created_at)); ?>
                                                    </div>
                                                </div>
                                                <div class="col-md-6">
                                                    <div class="info-box">
                                                        <strong>Last Updated:</strong><br>
                                                        <?php echo date('M d, Y \a\t h:i A', strtotime($material->updated_at)); ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Submit Buttons -->
                                        <div class="form-group row">
                                            <label class="col-sm-3 col-form-label"></label>
                                            <div class="col-sm-9">
                                                <button type="submit" name="edit_material" class="btn btn-primary" id="submit-btn">
                                                    <i class="fas fa-save"></i> Update Material
                                                </button>
                                                <a href="<?php echo $conn->teacher_url();?>view-material?id=<?php echo $material->id; ?>" class="btn btn-info">
                                                    <i class="fas fa-eye"></i> View Material
                                                </a>
                                                <a href="<?php echo $conn->teacher_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 mt-3">
                                <h5><i class="icon fas fa-info"></i> Note:</h5>
                                <ul class="mb-0">
                                    <li>Material type, class, and section cannot be changed after creation</li>
                                    <li>To change the file, please delete this material and upload a new one</li>
                                    <li>Subject can be changed to reassign the material to a different subject</li>
                                </ul>
                            </div>
                        </div>

                        <!-- Sidebar -->
                        <div class="col-md-2">
                            <div class="card">
                                <div class="card-header">
                                    <h3 class="card-title">Material Stats</h3>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <strong>Type:</strong><br>
                                        <span class="badge badge-<?php
                                        echo $material->material_type == 'video' ? 'primary' :
                                            ($material->material_type == 'pdf' ? 'danger' :
                                                ($material->material_type == 'link' ? 'success' : 'info'));
                                        ?>">
                                        <?php echo strtoupper($material->material_type); ?>
                                    </span>
                                    </div>

                                    <div class="mb-3">
                                        <strong>Status:</strong><br>
                                        <span class="badge badge-<?php echo $material->status == 'active' ? 'success' : 'warning'; ?>">
                                        <?php echo strtoupper($material->status); ?>
                                    </span>
                                    </div>

                                    <div class="mb-3">
                                        <strong>Views:</strong><br>
                                        <span class="badge badge-info"><?php echo $material->views_count ?? 0; ?></span>
                                    </div>

                                    <?php if ($material->avg_rating): ?>
                                        <div class="mb-3">
                                            <strong>Avg Rating:</strong><br>
                                            <span class="text-warning">
                                        <?php
                                        $rating = round($material->avg_rating);
                                        for ($i = 1; $i <= 5; $i++) {
                                            echo $i <= $rating ? '<i class="fas fa-star"></i>' : '<i class="far fa-star"></i>';
                                        }
                                        ?>
                                    </span>
                                        </div>
                                    <?php endif; ?>

                                    <hr>

                                    <a href="<?php echo $conn->teacher_url();?>view-material?id=<?php echo $material->id; ?>"
                                       class="btn btn-sm btn-primary btn-block mb-2">
                                        <i class="fas fa-eye"></i> View
                                    </a>
                                    <button class="btn btn-sm btn-danger btn-block delete-material"
                                            data-id="<?php echo $material->id; ?>"
                                            data-title="<?php echo htmlspecialchars($material->title); ?>">
                                        <i class="fas fa-trash"></i> Delete
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </div>

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


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

        $('#material-edit-form').on('submit', function(e) {
            e.preventDefault();

            var formData = new FormData(this);
            // Ensure edit_material parameter is included
            formData.append('edit_material', '1');

            $.ajax({
                url: 'process-edit-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> Updating material, please wait...');
                },
                success: function(data) {
                    $('#submit-btn').attr('disabled', false);
                    $('#submit-btn').html('<i class="fas fa-save"></i> Update Material');
                    $('#success-msg').html(data);

                    // Scroll to message
                    $('html, body').animate({
                        scrollTop: $('#success-msg').offset().top - 100
                    }, 500);

                    // Reset form if successful
                    if (data.includes('success')) {
                        setTimeout(function() {
                            window.location.href = '<?php echo $conn->teacher_url();?>view-material?id=<?php echo $material->id; ?>';
                        }, 2000);
                    }
                },
                error: function() {
                    $('#submit-btn').attr('disabled', false);
                    $('#submit-btn').html('<i class="fas fa-save"></i> Update Material');
                    alert('An error occurred. Please try again.');
                }
            });
        });

        // Delete material
        $('.delete-material').on('click', function() {
            var materialId = $(this).data('id');
            var materialTitle = $(this).data('title');

            if (confirm('Are you sure you want to delete "' + materialTitle + '"? This action cannot be undone.')) {
                $.ajax({
                    url: 'delete-material.php',
                    method: 'POST',
                    data: { material_id: materialId },
                    success: function(response) {
                        var data = JSON.parse(response);
                        if (data.success) {
                            alert(data.message);
                            window.location.href = '<?php echo $conn->teacher_url();?>learning-materials';
                        } else {
                            alert(data.message);
                        }
                    },
                    error: function() {
                        alert('An error occurred. Please try again.');
                    }
                });
            }
        });
    </script>
    </body>
    </html>
    <?php
} else {
    ?>
    <!DOCTYPE html>
    <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 '../admin/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 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 $teacher_login_link; ?>'>
                    </div>
                    <p>Redirecting to the login page...</p>
                </div>
            </div>
        </div>
    </div>
    </body>
    </html>
    <?php
}
?>