<?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>View 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();
        }
        ?>
        <style>
            .material-header {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                padding: 30px;
                border-radius: 10px;
                margin-bottom: 30px;
            }
            .material-icon {
                font-size: 80px;
                margin: 20px 0;
            }
            .info-box {
                border-left: 4px solid #007bff;
                padding: 15px;
                background: #f8f9fa;
                margin-bottom: 15px;
                border-radius: 5px;
            }
            .video-container {
                position: relative;
                width: 100%;
                padding-bottom: 56.25%;
                height: 0;
                overflow: hidden;
                margin: 20px 0;
                border-radius: 10px;
            }
            .video-container iframe {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
            }
            .stats-grid {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
                gap: 15px;
                margin: 20px 0;
            }
            .stat-item {
                text-align: center;
                padding: 15px;
                background: #f8f9fa;
                border-radius: 5px;
            }
            .stat-number {
                font-size: 24px;
                font-weight: bold;
                color: #007bff;
            }
            .stat-label {
                font-size: 12px;
                color: #6c757d;
                text-transform: uppercase;
            }
            .comment-item {
                border-left: 3px solid #007bff;
                padding: 15px;
                margin-bottom: 15px;
                background: #f8f9fa;
                border-radius: 3px;
            }
            .comment-author {
                font-weight: bold;
                color: #495057;
            }
            .comment-time {
                font-size: 12px;
                color: #6c757d;
            }
            .rating-display {
                font-size: 18px;
                color: #ffc107;
            }
            .file-download-btn {
                display: inline-block;
                padding: 10px 20px;
                background: #28a745;
                color: white;
                border-radius: 5px;
                text-decoration: none;
                margin: 5px;
            }
            .file-download-btn:hover {
                background: #218838;
                text-decoration: none;
            }

            .fa-eye, .fa-edit, .fa-trash{
                background-color: transparent;
            }

            .badge{
                padding: .10em .4em !important;
                line-height: 1.4 !important;
                height: 20px !important;
            }
        </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"><a href="<?php echo $conn->teacher_url();?>learning-materials">Learning Materials</a></li>
                                <li class="breadcrumb-item active">View Material</li>
                            </ol>
                        </div>
                    </div>
                </div>
            </div>

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

                    <!-- Material Header -->
                    <div class="material-header">
                        <div class="row">
                            <div class="col-md-2 text-center">
                                <?php
                                $icon_class = '';
                                switch ($material->material_type) {
                                    case 'pdf':
                                        $icon_class = 'fa-file-pdf text-danger';
                                        break;
                                    case 'video':
                                        $icon_class = 'fa-video text-primary';
                                        break;
                                    case 'document':
                                        $icon_class = 'fa-file-word text-info';
                                        break;
                                    case 'link':
                                        $icon_class = 'fa-link text-success';
                                        break;
                                    case 'audio':
                                        $icon_class = 'fa-music text-warning';
                                        break;
                                }
                                ?>
                                <i class="fas <?php echo $icon_class; ?> material-icon" style="color: white;"></i>
                            </div>
                            <div class="col-md-10">
                                <h2><?php echo htmlspecialchars($material->title); ?></h2>
                                <p class="mb-0"><strong>Type:</strong> <?php echo strtoupper($material->material_type); ?></p>
                                <p class="mb-0"><strong>Subject:</strong> <?php echo htmlspecialchars($material->subject_name); ?></p>
                                <p class="mb-0"><strong>Class/Section:</strong> <?php echo htmlspecialchars($material->class_name . ' - ' . $material->section_name); ?></p>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-8">

                            <!-- Material Content -->
                            <div class="card">
                                <div class="card-header">
                                    <h3 class="card-title">Material Content</h3>
                                </div>
                                <div class="card-body">

                                    <?php if ($material->description): ?>
                                        <div class="info-box">
                                            <strong>Description</strong><br>
                                            <?php echo nl2br(htmlspecialchars($material->description)); ?>
                                        </div>
                                    <?php endif; ?>

                                    <?php if ($material->duration): ?>
                                        <div class="info-box">
                                            <strong><i class="fas fa-clock"></i> Duration:</strong> <?php echo htmlspecialchars($material->duration); ?>
                                        </div>
                                    <?php endif; ?>

                                    <!-- Display based on material type -->
                                    <?php if ($material->material_type === 'video'): ?>
                                        <?php if (strpos($material->external_link, 'youtube.com') !== false || strpos($material->external_link, 'youtu.be') !== false): ?>
                                            <div class="video-container">
                                                <?php
                                                // Extract YouTube video ID
                                                preg_match('/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/', $material->external_link, $matches);
                                                $video_id = $matches[1] ?? null;
                                                if ($video_id):
                                                    ?>
                                                    <iframe src="https://www.youtube.com/embed/<?php echo $video_id; ?>"
                                                            allowfullscreen
                                                            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture">
                                                    </iframe>
                                                <?php else: ?>
                                                    <div class="alert alert-warning">
                                                        <i class="fas fa-exclamation-triangle"></i> Invalid YouTube URL
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                        <?php elseif ($material->file_path): ?>
                                            <video width="100%" height="400" controls style="border-radius: 10px;">
                                                <source src="<?php echo $conn->main_url() . $material->file_path; ?>" type="video/mp4">
                                                Your browser does not support the video tag.
                                            </video>
                                        <?php endif; ?>

                                    <?php elseif ($material->material_type === 'audio'): ?>
                                        <audio width="100%" controls style="margin: 20px 0;">
                                            <source src="<?php echo $conn->main_url() . $material->file_path; ?>" type="audio/mpeg">
                                            Your browser does not support the audio element.
                                        </audio>

                                    <?php elseif ($material->material_type === 'pdf'): ?>
                                        <div style="margin: 20px 0;">
                                            <embed src="<?php echo $conn->main_url() . $material->file_path; ?>"
                                                   type="application/pdf"
                                                   width="100%"
                                                   height="600">
                                        </div>

                                    <?php elseif ($material->material_type === 'link'): ?>

                                        <?php if (strpos($material->external_link, 'youtube.com') !== false || strpos($material->external_link, 'youtu.be') !== false): ?>
                                            <div class="video-container">
                                                <?php
                                                // Extract YouTube video ID
                                                preg_match('/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/', $material->external_link, $matches);
                                                $video_id = $matches[1] ?? null;
                                                if ($video_id):
                                                    ?>
                                                    <iframe src="https://www.youtube.com/embed/<?php echo $video_id; ?>"
                                                            allowfullscreen
                                                            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture">
                                                    </iframe>
                                                <?php else: ?>
                                                    <div class="alert alert-warning">
                                                        <i class="fas fa-exclamation-triangle"></i> Invalid YouTube URL
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                        <?php else: ?>
                                            <div class="alert alert-info">
                                                <strong>External Link:</strong><br>
                                                <a href="<?php echo htmlspecialchars($material->external_link); ?>"
                                                   target="_blank"
                                                   class="file-download-btn">
                                                    <i class="fas fa-external-link-alt"></i> Open Link
                                                </a>
                                            </div>
                                        <?php endif; ?>

                                    <?php elseif ($material->material_type === 'document' && $material->file_path): ?>
                                        <div class="alert alert-info">
                                            <strong>Document Available for Download:</strong><br>
                                            <a href="<?php echo $conn->main_url() . $material->file_path; ?>"
                                               download
                                               class="file-download-btn">
                                                <i class="fas fa-download"></i> Download Document
                                            </a>
                                        </div>
                                    <?php endif; ?>

                                </div>
                            </div>

                            <!-- Statistics -->
                            <div class="card mt-3">
                                <div class="card-header">
                                    <h3 class="card-title">Statistics & Engagement</h3>
                                </div>
                                <div class="card-body">
                                    <div class="stats-grid">
                                        <div class="stat-item">
                                            <div class="stat-number"><?php echo $material->views_count ?? 0; ?></div>
                                            <div class="stat-label">Total Views</div>
                                        </div>
                                        <div class="stat-item">
                                            <div class="stat-number"><?php echo $material->ratings_count ?? 0; ?></div>
                                            <div class="stat-label">Ratings</div>
                                        </div>
                                        <div class="stat-item">
                                            <div class="stat-number">
                                                <?php echo $material->avg_rating ? number_format($material->avg_rating, 1) : 'N/A'; ?>
                                            </div>
                                            <div class="stat-label">Avg Rating</div>
                                        </div>
                                        <div class="stat-item">
                                            <div class="stat-number"><?php echo $material->file_size ?? 'N/A'; ?></div>
                                            <div class="stat-label">File Size</div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Comments Section -->
                            <div class="card mt-3">
                                <div class="card-header">
                                    <h3 class="card-title">Comments & Feedback</h3>
                                </div>
                                <div class="card-body">
                                    <?php
                                    $comments = $elearning->getMaterialComments($material_id);
                                    if (!empty($comments)) {
                                        foreach ($comments as $comment) {
                                            ?>
                                            <div class="comment-item">
                                                <div class="comment-author"><?php echo htmlspecialchars($comment->user_name); ?></div>
                                                <div class="comment-time">
                                                    <i class="fas fa-clock"></i> <?php echo date('M d, Y \a\t h:i A', strtotime($comment->created_at)); ?>
                                                    <span class="badge badge-info ml-2"><?php echo strtoupper($comment->user_type); ?></span>
                                                </div>
                                                <p class="mt-2 mb-0"><?php echo nl2br(htmlspecialchars($comment->comment_text)); ?></p>
                                            </div>
                                            <?php
                                        }
                                    } else {
                                        echo '<p class="text-muted">No comments yet</p>';
                                    }
                                    ?>
                                </div>
                            </div>

                        </div>

                        <!-- Sidebar -->
                        <div class="col-md-4">

                            <!-- Material Info -->
                            <div class="card">
                                <div class="card-header">
                                    <h3 class="card-title">Material Information</h3>
                                </div>
                                <div class="card-body">
                                    <div class="info-box">
                                        <strong>Status:</strong><br>
                                        <span class="badge badge-<?php echo $material->status == 'active' ? 'success' : 'warning'; ?>">
                                        <?php echo strtoupper($material->status); ?>
                                    </span>
                                    </div>

                                    <div class="info-box">
                                        <strong>Uploaded By:</strong><br>
                                        <span class="badge badge-secondary"><?php echo strtoupper($material->uploader_type); ?></span>
                                    </div>

                                    <div class="info-box">
                                        <strong>Term:</strong><br>
                                        <?php echo htmlspecialchars($material->term_name); ?>
                                    </div>

                                    <div class="info-box">
                                        <strong>Uploaded Date:</strong><br>
                                        <?php echo date('M d, Y h:i A', strtotime($material->created_at)); ?>
                                    </div>

                                    <div class="info-box">
                                        <strong>Last Updated:</strong><br>
                                        <?php echo date('M d, Y h:i A', strtotime($material->updated_at)); ?>
                                    </div>

                                    <?php if ($material->material_type !== 'link'): ?>
                                        <div class="info-box">
                                            <strong>File:</strong><br>
                                            <?php
                                            $file_name = basename($material->file_path);
                                            ?>
                                            <code style="font-size: 11px;"><?php echo $file_name; ?></code>
                                        </div>
                                    <?php else: ?>
                                        <div class="info-box">
                                            <strong>External URL:</strong><br>
                                            <a href="<?php echo htmlspecialchars($material->external_link); ?>" target="_blank" class="text-truncate d-block">
                                                <?php echo substr(htmlspecialchars($material->external_link), 0, 40); ?>...
                                            </a>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- Actions -->
                            <div class="card">
                                <div class="card-header">
                                    <h3 class="card-title">Actions</h3>
                                </div>
                                <div class="card-body">
                                    <a href="<?php echo $conn->teacher_url();?>edit-material?id=<?php echo $material->id; ?>"
                                       class="btn btn-primary btn-block mb-2">
                                        <i class="fas fa-edit"></i> Edit Material
                                    </a>
                                    <button class="btn 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 Material
                                    </button>
                                    <a href="<?php echo $conn->teacher_url();?>learning-materials"
                                       class="btn btn-secondary btn-block mt-2">
                                        <i class="fas fa-arrow-left"></i> Back to Materials
                                    </a>
                                </div>
                            </div>

                            <!-- Rating Summary -->
                            <?php if ($material->avg_rating): ?>
                                <div class="card">
                                    <div class="card-header">
                                        <h3 class="card-title">Rating Summary</h3>
                                    </div>
                                    <div class="card-body text-center">
                                        <div class="rating-display">
                                            <?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>';
                                            }
                                            ?>
                                        </div>
                                        <h4><?php echo number_format($material->avg_rating, 1); ?> / 5.0</h4>
                                        <p class="text-muted">Based on <?php echo $material->ratings_count; ?> ratings</p>
                                    </div>
                                </div>
                            <?php endif; ?>

                        </div>
                    </div>

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

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


    <script>
        $(function() {
            $('.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
}
?>