<?php
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>Learning Materials | <?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;
        ?>
        <style>
            .material-card {
                transition: transform 0.2s;
                border-left: 4px solid #007bff;
            }
            .material-card:hover {
                transform: translateY(-5px);
                box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            }
            .material-icon {
                font-size: 40px;
                margin-bottom: 10px;
            }
            .stats-card {
                border-radius: 10px;
            }

            .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">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 active">Learning Materials</li>
                            </ol>
                        </div>
                    </div>
                </div>
            </div>

            <section class="content">
                <div class="container-fluid">

                    <!-- Statistics Cards -->
                    <?php
                    $stats = $elearning->getMaterialStatistics($username);
                    ?>
                    <div class="row">
                        <div class="col-lg-3 col-6">
                            <div class="small-box bg-info stats-card">
                                <div class="inner">
                                    <h3><?php echo $stats->total_materials ?? 0; ?></h3>
                                    <p>Total Materials</p>
                                </div>
                                <div class="icon">
                                    <i class="fas fa-book"></i>
                                </div>
                            </div>
                        </div>

                        <div class="col-lg-3 col-6">
                            <div class="small-box bg-success stats-card">
                                <div class="inner">
                                    <h3><?php echo $stats->total_views ?? 0; ?></h3>
                                    <p>Total Views</p>
                                </div>
                                <div class="icon">
                                    <i class="fas fa-eye"></i>
                                </div>
                            </div>
                        </div>

                        <div class="col-lg-3 col-6">
                            <div class="small-box bg-warning stats-card">
                                <div class="inner">
                                    <h3><?php echo $stats->videos ?? 0; ?></h3>
                                    <p>Videos</p>
                                </div>
                                <div class="icon">
                                    <i class="fas fa-video"></i>
                                </div>
                            </div>
                        </div>

                        <div class="col-lg-3 col-6">
                            <div class="small-box bg-danger stats-card">
                                <div class="inner">
                                    <h3><?php echo $stats->students_engaged ?? 0; ?></h3>
                                    <p>Students Engaged</p>
                                </div>
                                <div class="icon">
                                    <i class="fas fa-users"></i>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filter Section -->
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Filter Materials</h3>
                            <div class="card-tools">
                                <a href="<?php echo $conn->teacher_url();?>add-learning-material" class="btn btn-primary btn-sm">
                                    <i class="fas fa-plus"></i> Add New Material
                                </a>
                            </div>
                        </div>
                        <div class="card-body">
                            <form method="GET" id="filter-form">
                                <div class="row">
                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label>Class</label>
                                            <select name="filter_class" id="filter_class" class="form-control select2">
                                                <option value="">All Classes</option>
                                                <?php
                                                $sql = "SELECT * FROM classes WHERE teacher_name = :teacher_name ORDER BY name";
                                                $conn->query($sql);
                                                $conn->bind(':teacher_name', $teacher_name);
                                                $classes = $conn->fetchMultiple();
                                                foreach ($classes as $class) {
                                                    $selected = (isset($_GET['filter_class']) && $_GET['filter_class'] == $class->id) ? 'selected' : '';
                                                    echo "<option value='{$class->id}' {$selected}>{$class->name}</option>";
                                                }
                                                ?>
                                            </select>
                                        </div>
                                    </div>

                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label>Section</label>
                                            <select name="filter_section" id="filter_section" class="form-control select2">
                                                <option value="">All Sections</option>
                                            </select>
                                        </div>
                                    </div>

                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label>Subject</label>
                                            <select name="filter_subject" id="filter_subject" class="form-control select2">
                                                <option value="">All Subjects</option>
                                            </select>
                                        </div>
                                    </div>

                                    <div class="col-md-3">
                                        <div class="form-group">
                                            <label>Material Type</label>
                                            <select name="filter_type" class="form-control select2">
                                                <option value="">All Types</option>
                                                <option value="pdf" <?php echo (isset($_GET['filter_type']) && $_GET['filter_type'] == 'pdf') ? 'selected' : ''; ?>>PDF</option>
                                                <option value="video" <?php echo (isset($_GET['filter_type']) && $_GET['filter_type'] == 'video') ? 'selected' : ''; ?>>Video</option>
                                                <option value="document" <?php echo (isset($_GET['filter_type']) && $_GET['filter_type'] == 'document') ? 'selected' : ''; ?>>Document</option>
                                                <option value="link" <?php echo (isset($_GET['filter_type']) && $_GET['filter_type'] == 'link') ? 'selected' : ''; ?>>External Link</option>
                                                <option value="audio" <?php echo (isset($_GET['filter_type']) && $_GET['filter_type'] == 'audio') ? 'selected' : ''; ?>>Audio</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-filter"></i> Apply Filters
                                </button>
                                <a href="<?php echo $conn->teacher_url();?>learning-materials" class="btn btn-secondary">
                                    <i class="fas fa-redo"></i> Reset
                                </a>
                            </form>
                        </div>
                    </div>

                    <!-- Materials List -->
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">All Learning Materials</h3>
                            <div class="card-tools">
                                <button type="button" class="btn btn-tool" id="toggle-view">
                                    <i class="fas fa-th" id="view-icon"></i> Toggle View
                                </button>
                            </div>
                        </div>
                        <div class="card-body">

                            <!-- Grid View -->
                            <div id="grid-view">
                                <div class="row">
                                    <?php
                                    $sql = "SELECT lm.*, s.subject_name, c.name as class_name, sec.name as section_name,
                                        (SELECT AVG(rating) FROM material_ratings WHERE material_id = lm.id) as avg_rating,
                                        (SELECT COUNT(*) FROM material_comments WHERE material_id = lm.id AND status = 'active') as comments_count
                                    FROM learning_materials lm
                                    LEFT JOIN subjects s ON lm.subject_id = s.id
                                    LEFT JOIN classes c ON lm.class_id = c.id
                                    LEFT JOIN sections sec ON lm.section_id = sec.id
                                    WHERE 1=1 AND uploaded_by =:username";

                                    // Apply filters
                                    if (isset($_GET['filter_class']) && !empty($_GET['filter_class'])) {
                                        $sql .= " AND lm.class_id = " . (int)$_GET['filter_class'];
                                    }
                                    if (isset($_GET['filter_section']) && !empty($_GET['filter_section'])) {
                                        $sql .= " AND lm.section_id = " . (int)$_GET['filter_section'];
                                    }
                                    if (isset($_GET['filter_subject']) && !empty($_GET['filter_subject'])) {
                                        $sql .= " AND lm.subject_id = " . (int)$_GET['filter_subject'];
                                    }
                                    if (isset($_GET['filter_type']) && !empty($_GET['filter_type'])) {
                                        $sql .= " AND lm.material_type = '" . $_GET['filter_type'] . "'";
                                    }

                                    $sql .= " ORDER BY lm.created_at DESC";

                                    $conn->query($sql);
                                    $conn->bind(':username', $username);
                                    $materials = $conn->fetchMultiple();


                                    if (!empty($materials)) {
                                        foreach ($materials as $material) {
                                            // Determine icon based on material type
                                            $icon_class = '';
                                            $icon_color = '';
                                            switch ($material->material_type) {
                                                case 'pdf':
                                                    $icon_class = 'fa-file-pdf';
                                                    $icon_color = 'text-danger';
                                                    break;
                                                case 'video':
                                                    $icon_class = 'fa-video';
                                                    $icon_color = 'text-primary';
                                                    break;
                                                case 'document':
                                                    $icon_class = 'fa-file-word';
                                                    $icon_color = 'text-info';
                                                    break;
                                                case 'link':
                                                    $icon_class = 'fa-link';
                                                    $icon_color = 'text-success';
                                                    break;
                                                case 'audio':
                                                    $icon_class = 'fa-music';
                                                    $icon_color = 'text-warning';
                                                    break;
                                            }
                                            ?>
                                            <div class="col-md-4 col-sm-6 mb-4">
                                                <div class="card material-card">
                                                    <div class="card-body">
                                                        <div class="text-center material-icon">
                                                            <i class="fas <?php echo $icon_class . ' ' . $icon_color; ?>"></i>
                                                        </div>
                                                        <h5 class="card-title w-100"><?php echo htmlspecialchars($material->title); ?></h5>
                                                        <p class="text-muted small">
                                                            <i class="fas fa-book"></i> <?php echo htmlspecialchars($material->subject_name); ?><br>
                                                            <i class="fas fa-school"></i> <?php echo htmlspecialchars($material->class_name); ?> - <?php echo htmlspecialchars($material->section_name); ?>
                                                        </p>

                                                        <?php if ($material->description): ?>
                                                            <p class="card-text small"><?php echo substr(htmlspecialchars($material->description), 0, 100); ?>...</p>
                                                        <?php endif; ?>

                                                        <div class="d-flex justify-content-between align-items-center mb-2">
                                                            <small class="text-muted">
                                                                <i class="fas fa-eye"></i> <?php echo $material->views_count ?? 0; ?> views
                                                            </small>
                                                            <?php if ($material->avg_rating): ?>
                                                                <small class="text-warning">
                                                                    <i class="fas fa-star"></i> <?php echo number_format($material->avg_rating, 1); ?>
                                                                </small>
                                                            <?php endif; ?>
                                                        </div>

                                                        <div class="btn-group btn-block">
                                                            <a href="view-material?id=<?php echo $material->id; ?>" class="btn btn-sm btn-primary">
                                                                <i class="fas fa-eye"></i> View
                                                            </a>
                                                            <a href="edit-material?id=<?php echo $material->id; ?>" class="btn btn-sm btn-info">
                                                                <i class="fas fa-edit"></i> Edit
                                                            </a>
                                                            <button class="btn btn-sm btn-danger 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 class="card-footer text-muted small">
                                                        <i class="fas fa-clock"></i> <?php echo date('M d, Y', strtotime($material->created_at)); ?>
                                                        <?php if ($material->status == 'inactive'): ?>
                                                            <span class="badge badge-warning float-right">Inactive</span>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            </div>
                                            <?php
                                        }
                                    } else {
                                        echo '<div class="col-12"><div class="alert alert-info">No learning materials found. <a href="' . $conn->teacher_url() . 'add-learning-material">Add your first material</a></div></div>';
                                    }
                                    ?>
                                </div>
                            </div>

                            <!-- Table View (Hidden by default) -->
                            <div id="table-view" style="display: none;">
                                <table id="materials-table" class="table table-bordered table-striped">
                                    <thead>
                                    <tr>
                                        <th>Title</th>
                                        <th>Type</th>
                                        <th>Subject</th>
                                        <th>Class/Section</th>
                                        <th>Views</th>
                                        <th>Status</th>
                                        <th>Date</th>
                                        <th>Actions</th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    <?php
                                    if (!empty($materials)) {
                                        foreach ($materials as $material) {
                                            ?>
                                            <tr>
                                                <td><?php echo htmlspecialchars($material->title); ?></td>
                                                <td>
                                            <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>
                                                </td>
                                                <td><?php echo htmlspecialchars($material->subject_name); ?></td>
                                                <td><?php echo htmlspecialchars($material->class_name . ' - ' . $material->section_name); ?></td>
                                                <td><?php echo $material->views_count ?? 0; ?></td>
                                                <td>
                                            <span class="badge badge-<?php echo $material->status == 'active' ? 'success' : 'warning'; ?>">
                                                <?php echo ucfirst($material->status); ?>
                                            </span>
                                                </td>
                                                <td><?php echo date('M d, Y', strtotime($material->created_at)); ?></td>
                                                <td>
                                                    <div class="btn-group">
                                                        <a href="view-material.php?id=<?php echo $material->id; ?>" class="btn btn-xs btn-primary" title="View">
                                                            <i class="fas fa-eye"></i>
                                                        </a>
                                                        <a href="edit-material.php?id=<?php echo $material->id; ?>" class="btn btn-xs btn-info" title="Edit">
                                                            <i class="fas fa-edit"></i>
                                                        </a>
                                                        <button class="btn btn-xs btn-danger delete-material" data-id="<?php echo $material->id; ?>" data-title="<?php echo htmlspecialchars($material->title); ?>" title="Delete">
                                                            <i class="fas fa-trash"></i>
                                                        </button>
                                                    </div>
                                                </td>
                                            </tr>
                                            <?php
                                        }
                                    }
                                    ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </div>

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


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

            // Initialize DataTable
            $('#materials-table').DataTable({
                "responsive": true,
                "lengthChange": true,
                "autoWidth": false,
                "buttons": ["copy", "csv", "excel", "pdf", "print"]
            });
        });

        // Toggle between grid and table view
        $('#toggle-view').on('click', function() {
            $('#grid-view').toggle();
            $('#table-view').toggle();

            var icon = $('#view-icon');
            if (icon.hasClass('fa-th')) {
                icon.removeClass('fa-th').addClass('fa-list');
            } else {
                icon.removeClass('fa-list').addClass('fa-th');
            }
        });

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

                $.ajax({
                    type: 'POST',
                    url: 'fetch_subject.php',
                    data: 'classesID=' + classID,
                    success: function(html) {
                        $('#filter_subject').html(html);
                    }
                });
            } else {
                $('#filter_section').html('<option value="">All Sections</option>');
                $('#filter_subject').html('<option value="">All Subjects</option>');
            }
        });

        // 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);
                            location.reload();
                        } else {
                            alert(data.message);
                        }
                    },
                    error: function() {
                        alert('An error occurred. Please try again.');
                    }
                });
            }
        });

        // Load filters on page load if they exist
        $(document).ready(function() {
            <?php if (isset($_GET['filter_class']) && !empty($_GET['filter_class'])): ?>
            var classID = <?php echo $_GET['filter_class']; ?>;
            $.ajax({
                type: 'POST',
                url: 'fetch_section.php',
                data: 'classesID=' + classID,
                success: function(html) {
                    $('#filter_section').html(html);
                    <?php if (isset($_GET['filter_section'])): ?>
                    $('#filter_section').val('<?php echo $_GET['filter_section']; ?>');
                    <?php endif; ?>
                }
            });

            $.ajax({
                type: 'POST',
                url: 'fetch_subject.php',
                data: 'classesID=' + classID,
                success: function(html) {
                    $('#filter_subject').html(html);
                    <?php if (isset($_GET['filter_subject'])): ?>
                    $('#filter_subject').val('<?php echo $_GET['filter_subject']; ?>');
                    <?php endif; ?>
                }
            });
            <?php endif; ?>
        });
    </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
}
?>