<?php
session_start();
error_reporting(0);
 ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <style>
        .material-player {
            background: #000;
            border-radius: 10px;
            overflow: hidden;
            margin-bottom: 30px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        .video-container {
            position: relative;
            width: 100%;
            padding-bottom: 56.25%;
            height: 0;
            overflow: hidden;
        }
        .video-container iframe {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
        }
        .material-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 25px;
            border-radius: 10px;
            margin-bottom: 30px;
        }
        .progress-section {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            border-left: 4px solid #007bff;
        }
        .rating-section {
            background: #fff3cd;
            padding: 15px;
            border-radius: 10px;
            margin: 15px 0;
        }
        .star-rating {
            font-size: 24px;
            cursor: pointer;
        }
        .star-rating i {
            color: #ddd;
            margin-right: 5px;
            transition: color 0.2s;
        }
        .star-rating i:hover,
        .star-rating i.active {
            color: #ffc107;
        }
        .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;
        }
        .badge-badge {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 3px;
            font-size: 11px;
            margin-left: 8px;
        }
        .material-icon {
            font-size: 60px;
            margin-right: 20px;
        }
        .related-materials {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 15px;
            margin-top: 20px;
        }
        .related-material-card {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            border-left: 3px solid #007bff;
            cursor: pointer;
            transition: all 0.3s;
        }
        .related-material-card:hover {
            background: #e9ecef;
            transform: translateX(5px);
        }
        .timer {
            font-size: 14px;
            color: #6c757d;
            margin-top: 10px;
        }
    </style>

    <?php include '../admin/includes/styles.php'; ?>
    <?php

    if(isset($_SESSION['student'])){

    require_once '../admin/Classes/ELearning.php';
    $elearning = new ELearning();

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

    $material_id = (int)$_GET['id'];

    // Get student info
    $sql = "SELECT studentID, name, classesID, sectionid FROM student WHERE username = :username";
    $conn->query($sql);
    $conn->bind(':username', $_SESSION['student']);
    $student = $conn->fetchSingle();

    if (!$student) {
        header("Location: $student_login_link");
        exit();
    }

    $student_id = $student->studentID;

    // Get material details
    $material = $elearning->getMaterialById($material_id);

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

    // Verify student has access (same class and section)
    if ($material->class_id != $student->classesID || $material->section_id != $student->sectionid) {
        header('Location: learning-materials');
        exit();
    }

    ?>
    <title> <?php echo htmlspecialchars($material->title); ?> | <?php echo $school_name; ?> </title>
</head>
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">

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

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

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

       <!-- Start Section -->
        <section class="content">
            <div class="container-fluid">

                <!-- Material Header -->
                <div class="material-header">
                    <div class="row">
                        <div class="col-md-1 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-11">
                            <h2><?php echo htmlspecialchars($material->title); ?></h2>
                            <p class="mb-0"><strong>Subject:</strong> <?php echo htmlspecialchars($material->subject_name); ?></p>
                            <p class="mb-0"><strong>Type:</strong> <span class="badge badge-info"><?php echo strtoupper($material->material_type); ?></span></p>
                            <?php if ($material->duration): ?>
                                <p class="mb-0"><strong>Duration:</strong> <?php echo htmlspecialchars($material->duration); ?></p>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-lg-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="alert alert-info">
                                        <strong>Description</strong><br>
                                        <?php echo nl2br(htmlspecialchars($material->description)); ?>
                                    </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="material-player">
                                            <div class="video-container">
                                                <?php
                                                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 endif; ?>
                                            </div>
                                        </div>
                                    <?php elseif ($material->file_path): ?>
                                        <div class="material-player">
                                            <video width="100%" height="400" controls>
                                                <source src="<?php echo $conn->main_url() . $material->file_path; ?>" type="video/mp4">
                                                Your browser does not support the video tag.
                                            </video>
                                        </div>
                                    <?php endif; ?>

                                <?php elseif ($material->material_type === 'audio'): ?>
                                    <div class="material-player">
                                        <div style="padding: 40px; text-align: center;">
                                            <i class="fas fa-music fa-3x text-warning mb-3"></i>
                                            <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>
                                        </div>
                                    </div>

                                <?php elseif ($material->material_type === 'pdf'): ?>
                                    <div class="material-player">
                                        <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="material-player">
                                            <div class="video-container">
                                                <?php
                                                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 endif; ?>
                                            </div>
                                        </div>
                                    <?php else: ?>
                                    <div class="alert alert-info">
                                        <i class="fas fa-link"></i> <strong>External Resource:</strong><br>
                                        Click the button below to access the external resource.
                                        <br><br>
                                        <a href="<?php echo htmlspecialchars($material->external_link); ?>"
                                           target="_blank"
                                           class="btn btn-primary mt-2">
                                            <i class="fas fa-external-link-alt"></i> Open Resource
                                        </a>
                                    </div>
                                    <?php endif; ?>

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

                            </div>
                        </div>

                        <!-- Progress Section -->
                        <div class="card mt-3">
                            <div class="card-header">
                                <h3 class="card-title">Your Progress</h3>
                            </div>
                            <div class="card-body">
                                <div class="progress-section">
                                    <?php
                                    // Get student's progress for this material
                                    $progress_sql = "SELECT * FROM student_material_progress 
                                                   WHERE student_id = :student_id AND material_id = :material_id";
                                    $conn->query($progress_sql);
                                    $conn->bind(':student_id', $student_id);
                                    $conn->bind(':material_id', $material_id);
                                    $progress = $conn->fetchSingle();

                                    $progress_status = $progress ? $progress->status : 'not_started';
                                    $progress_percentage = $progress ? $progress->progress_percentage : 0;
                                    $time_spent = $progress ? $progress->time_spent : 0;
                                    ?>

                                    <div class="row">
                                        <div class="col-md-6">
                                            <p><strong>Status:</strong></p>
                                            <span class="badge badge-<?php
                                            echo $progress_status == 'completed' ? 'success' :
                                                ($progress_status == 'in_progress' ? 'warning' : 'secondary');
                                            ?>" style="font-size: 14px; padding: 8px 12px;">
                                                <?php
                                                echo $progress_status == 'completed' ? '<i class="fas fa-check-circle"></i> Completed' :
                                                    ($progress_status == 'in_progress' ? '<i class="fas fa-spinner"></i> In Progress' : '<i class="fas fa-circle"></i> Not Started');
                                                ?>
                                            </span>
                                        </div>
                                        <div class="col-md-6">
                                            <p><strong>Time Spent:</strong></p>
                                            <span id="time-spent">
                                                <?php
                                                $hours = floor($time_spent / 3600);
                                                $minutes = floor(($time_spent % 3600) / 60);
                                                echo $hours > 0 ? $hours . 'h ' : '';
                                                echo $minutes . 'm';
                                                ?>
                                            </span>
                                        </div>
                                    </div>

                                    <div class="mt-3">
                                        <p><strong>Progress: <?php echo $progress_percentage; ?>%</strong></p>
                                        <div class="progress">
                                            <div class="progress-bar bg-success" role="progressbar"
                                                 style="width: <?php echo $progress_percentage; ?>%"
                                                 aria-valuenow="<?php echo $progress_percentage; ?>"
                                                 aria-valuemin="0" aria-valuemax="100">
                                            </div>
                                        </div>
                                    </div>

                                    <div class="mt-3">
                                        <button class="btn btn-primary" id="mark-completed-btn">
                                            <i class="fas fa-check"></i> Mark as Completed
                                        </button>
                                        <button class="btn btn-info" id="mark-progress-btn">
                                            <i class="fas fa-spinner"></i> Mark as In Progress
                                        </button>
                                    </div>

                                    <div class="timer mt-3">
                                        <i class="fas fa-clock"></i> Time tracking is active (only updated when you mark material status)
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Rating Section -->
                        <div class="card mt-3">
                            <div class="card-header">
                                <h3 class="card-title">Rate This Material</h3>
                            </div>
                            <div class="card-body">
                                <div class="rating-section">
                                    <p><strong>How helpful was this material?</strong></p>
                                    <div class="star-rating" id="star-rating">
                                        <i class="far fa-star" data-rating="1"></i>
                                        <i class="far fa-star" data-rating="2"></i>
                                        <i class="far fa-star" data-rating="3"></i>
                                        <i class="far fa-star" data-rating="4"></i>
                                        <i class="far fa-star" data-rating="5"></i>
                                    </div>
                                    <div class="mt-3">
                                        <textarea class="form-control" id="review-text" rows="3"
                                                  placeholder="Share your feedback about this material (optional)"></textarea>
                                    </div>
                                    <button class="btn btn-success mt-2" id="submit-rating-btn">
                                        <i class="fas fa-star"></i> Submit Rating
                                    </button>
                                    <div id="rating-message"></div>
                                </div>
                            </div>
                        </div>

                        <!-- Comments Section -->
                        <div class="card mt-3">
                            <div class="card-header">
                                <h3 class="card-title">Comments & Discussion</h3>
                            </div>
                            <div class="card-body">

                                <!-- New Comment Form -->
                                <div class="mb-4">
                                    <h5>Add Your Comment</h5>
                                    <textarea class="form-control" id="new-comment" rows="3"
                                              placeholder="Share your thoughts or ask questions about this material..."></textarea>
                                    <button class="btn btn-primary mt-2" id="submit-comment-btn">
                                        <i class="fas fa-paper-plane"></i> Post Comment
                                    </button>
                                    <div id="comment-message"></div>
                                </div>

                                <hr>

                                <!-- Comments List -->
                                <h5>Comments</h5>
                                <div id="comments-list">
                                    <?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); ?>
                                                    <span class="badge-badge badge-info"><?php echo strtoupper($comment->user_type); ?></span>
                                                </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)); ?>
                                                </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. Be the first to comment!</p>';
                                    }
                                    ?>
                                </div>
                            </div>
                        </div>

                    </div>

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

                        <!-- Material Info Card -->
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title">Material Info</h3>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <strong>Subject:</strong><br>
                                    <?php echo htmlspecialchars($material->subject_name); ?>
                                </div>

                                <div class="mb-3">
                                    <strong>Class/Section:</strong><br>
                                    <?php echo htmlspecialchars($material->class_name . ' - ' . $material->section_name); ?>
                                </div>

                                <div class="mb-3">
                                    <strong>Type:</strong><br>
                                    <span class="badge badge-info"><?php echo strtoupper($material->material_type); ?></span>
                                </div>

                                <div class="mb-3">
                                    <strong>Views:</strong><br>
                                    <i class="fas fa-eye"></i> <?php echo $material->views_count ?? 0; ?>
                                </div>

                                <?php if ($material->avg_rating): ?>
                                    <div class="mb-3">
                                        <strong>Rating:</strong><br>
                                        <div 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>';
                                            }
                                            ?>
                                        </div>
                                        <?php echo number_format($material->avg_rating, 1); ?>/5.0
                                    </div>
                                <?php endif; ?>

                                <a href="learning-materials" class="btn btn-secondary btn-block mt-3">
                                    <i class="fas fa-arrow-left"></i> Back to Materials
                                </a>
                            </div>
                        </div>

                        <!-- Related Materials -->
                        <?php
                        // Get related materials from same subject
                        $related_sql = "SELECT id, title, subject_id, material_type 
                                       FROM learning_materials 
                                       WHERE subject_id = :subject_id 
                                       AND class_id = :class_id 
                                       AND id != :material_id 
                                       AND status = 'active'
                                       LIMIT 5";
                        $conn->query($related_sql);
                        $conn->bind(':subject_id', $material->subject_id);
                        $conn->bind(':class_id', $material->class_id);
                        $conn->bind(':material_id', $material_id);
                        $related = $conn->fetchMultiple();

                        if (!empty($related)):
                            ?>
                            <div class="card mt-3">
                                <div class="card-header">
                                    <h3 class="card-title">Related Materials</h3>
                                </div>
                                <div class="card-body">
                                    <?php foreach ($related as $rel): ?>
                                        <a href="view-material.php?id=<?php echo $rel->id; ?>" class="related-material-card">
                                            <i class="fas fa-file-<?php echo $rel->material_type == 'pdf' ? 'pdf' : 'alt'; ?>"></i>
                                            <?php echo htmlspecialchars(substr($rel->title, 0, 40)); ?>
                                        </a>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        <?php endif; ?>

                    </div>
                </div>

            </div>
        </section>
       <!-- End  Section -->

    </div>
    <!-- /.content-wrapper -->
    <?php include "../admin/includes/footer.php";?>


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

        })

        $(function() {
            var materialId = <?php echo $material_id; ?>;
            var startTime = new Date();
            var timeTracking = null;

            // Mark material status
            $('#mark-completed-btn').on('click', function() {
                updateProgress('completed');
            });

            $('#mark-progress-btn').on('click', function() {
                updateProgress('in_progress');
            });

            function updateProgress(status) {
                var timeSpent = Math.floor((new Date() - startTime) / 1000);

                $.ajax({
                    url: 'api/material-progress.php',
                    method: 'POST',
                    data: {
                        material_id: materialId,
                        status: status,
                        time_spent: timeSpent,
                        progress_percentage: status == 'completed' ? 100 : 50
                    },
                    success: function(response) {
                        var data = JSON.parse(response);
                        if (data.success) {
                            location.reload();
                        } else {
                            toastr.error(data.message);
                           // alert('Error: ' + data.message);
                        }
                    },
                    error: function() {
                        toastr.error('An error occurred. Please try again.');
                    }
                });
            }

            // Star rating
            var currentRating = 0;
            $('#star-rating i').on('mouseover', function() {
                var rating = $(this).data('rating');
                $('#star-rating i').each(function() {
                    if ($(this).data('rating') <= rating) {
                        $(this).removeClass('far').addClass('fas').css('color', '#ffc107');
                    } else {
                        $(this).removeClass('fas').addClass('far').css('color', '#ddd');
                    }
                });
            });

            $('#star-rating').on('mouseleave', function() {
                if (currentRating > 0) {
                    $('#star-rating i').each(function() {
                        if ($(this).data('rating') <= currentRating) {
                            $(this).removeClass('far').addClass('fas').css('color', '#ffc107');
                        }
                    });
                } else {
                    $('#star-rating i').removeClass('fas').addClass('far').css('color', '#ddd');
                }
            });

            $('#star-rating i').on('click', function() {
                currentRating = $(this).data('rating');
            });

            // Submit rating
            $('#submit-rating-btn').on('click', function() {
                if (currentRating === 0) {
                   // alert('Please select a rating');
                    toastr.error('Please select a rating');
                    return;
                }

                var reviewText = $('#review-text').val();

                $.ajax({
                    url: 'api/material-rating.php',
                    method: 'POST',
                    data: {
                        material_id: materialId,
                        rating: currentRating,
                        review_text: reviewText
                    },
                    success: function(response) {
                        var data = JSON.parse(response);
                        if (data.success) {
                            $('#rating-message').html('<div class="alert alert-success mt-2"><i class="fas fa-check-circle"></i> ' + data.message + '</div>');
                            $('#review-text').val('');
                            setTimeout(function() {
                                $('#rating-message').html('');
                            }, 3000);
                        } else {
                           // alert('Error: ' + data.message);
                            toastr.error('Error: ' + data.message);
                        }
                    },
                    error: function() {
                        //alert('An error occurred. Please try again.');
                        toastr.error('An error occurred. Please try again.');
                    }
                });
            });

            // Submit comment
            $('#submit-comment-btn').on('click', function() {
                var commentText = $('#new-comment').val().trim();
                if (!commentText) {
                    //alert('Please enter a comment');
                    toastr.error('Please enter a comment');
                    return;
                }

                $.ajax({
                    url: 'api/material-comments.php',
                    method: 'POST',
                    data: {
                        material_id: materialId,
                        comment_text: commentText
                    },
                    success: function(response) {
                        var data = JSON.parse(response);
                        if (data.success) {
                            $('#new-comment').val('');
                            $('#comment-message').html('<div class="alert alert-success"><i class="fas fa-check-circle"></i> ' + data.message + '</div>');
                            setTimeout(function() {
                                location.reload();
                            }, 1000);
                        } else {
                            alert('Error: ' + data.message);
                        }
                    },
                    error: function() {
                        alert('An error occurred. Please try again.');
                    }
                });
            });
        });

    </script>


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


        <?php include '../admin/includes/styles.php'; ?>
        <title>Login to continue </title>

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

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

    <?php
    }

    ?>
