<?php
session_start();
require("dbconnect.php");

// Ensure the user is logged in
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
    header("Location: login.php");
    exit;
}

$user_id = $_SESSION['USER_ID']; // Get logged-in user ID

// Fetch only those videos which are granted access to the user
$query = "SELECT course_video.video_title, course_video.video_link, course_video.id, course_video.day, 
                 user_video_access.watched
          FROM user_video_access
          JOIN course_video ON user_video_access.video_id = course_video.id
          WHERE user_video_access.user_id = ? AND user_video_access.status = 1 AND course_video.status = 1
          ORDER BY course_video.day ASC, course_video.id ASC";  // Sort by day and then by video ID

$stmt = $con->prepare($query);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();

// Fetch the first video (for the center display)
$current_video = mysqli_fetch_assoc($result);

// Convert YouTube URL to Embed Format
function convertToEmbed($url) {
    return str_replace("watch?v=", "embed/", $url);
}

// Set first video link (Download Protection Added)
$first_video_link = isset($current_video['video_link']) ? convertToEmbed($current_video['video_link']) . "?controls=1&autoplay=1&disablekb=1&modestbranding=1&rel=0" : "";

// Check if all videos for the current day are watched
$watched_query = "SELECT COUNT(*) as total_videos, 
                          SUM(CASE WHEN watched = 1 THEN 1 ELSE 0 END) as watched_videos 
                  FROM user_video_access
                  JOIN course_video ON user_video_access.video_id = course_video.id
                  WHERE user_video_access.user_id = ? AND course_video.day = ?";
$watched_stmt = $con->prepare($watched_query);
$watched_stmt->bind_param("ii", $user_id, $current_video['day']);
$watched_stmt->execute();
$watched_result = $watched_stmt->get_result();
$watched_data = $watched_result->fetch_assoc();

// Prevent division by zero if there are no videos for the day
$total_videos = $watched_data['total_videos'];
$watched_videos = $watched_data['watched_videos'];
$watched_percentage = ($total_videos > 0) ? ($watched_videos / $total_videos) * 100 : 0;
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Videos | Secure</title>
    
    <!-- Bootstrap 5 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    
    <style>
        body {
            background-color: #f0f8ff;
            font-family: Arial, sans-serif;
        }
        .container {
            margin-top: 20px;
        }

        /* Disable Right-Click on Whole Page */
        body {
            -webkit-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
            user-select: none;
        }

        iframe {
            pointer-events: none;
        }
        
        /* Main Video Styling */
        .video-container {
            width: 100%;
            height: 500px;
            margin: auto;
            background: #000;
            border-radius: 10px;
            display: flex;
            justify-content: center;
            align-items: center;
            transition: all 0.3s ease;
        }
        
        .video-container iframe {
            width: 100%;
            height: 100%;
            border-radius: 10px;
        }

        /* Video List (Sidebar) */
        .video-list {
            max-height: 500px;
            overflow-y: auto;
        }

        .video-card {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
            padding: 10px;
            border-radius: 10px;
            transition: 0.3s;
            background: white;
        }

        .video-card:hover {
            background: #f1f1f1;
            cursor: pointer;
        }

        .video-card img {
            width: 120px;
            height: 80px;
            border-radius: 10px;
        }

        .video-card .video-info {
            padding-left: 10px;
        }

        .video-title {
            font-size: 16px;
            font-weight: bold;
        }

        .video-title:hover {
            color: #007bff;
        }

        .video-day-title {
            font-size: 20px;
            font-weight: bold;
            margin-top: 20px;
            color: #007bff;
        }

        .progress {
            height: 20px;
        }

        /* Responsive Layout for Video Container */
        .video-container.sm {
            height: 300px;
        }

        .video-container.md {
            height: 500px;
        }

        .video-container.lg {
            height: 700px;
        }

        /* Footer Styling */
        footer {
            background-color: #343a40;
            color: white;
            padding: 10px 0;
            text-align: center;
            font-size: 14px;
        }

    </style>
</head>
<body>

<!-- Navbar with Support Number and Logout Button -->
<nav class="navbar navbar-light">
    <div class="container-fluid">
        <a class="navbar-brand fw-bold">My Videos</a>
        <span class="text-muted blinking">Support: +91-8882488159</span> <!-- Support number with blinking effect -->
        <a href="logout.php" class="btn btn-danger">Logout</a>
    </div>
</nav>

<div class="container">
    <div class="row">
        <!-- Main Video (Download Protected) -->
        <div class="col-md-8">
            <?php if ($current_video): ?>
                <div class="video-container shadow" id="main-video-container">
                    <iframe id="main-video" src="<?php echo htmlspecialchars($first_video_link); ?>" 
                            frameborder="0" allow="autoplay; accelerometer; clipboard-write; encrypted-media; gyroscope; picture-in-picture" 
                            allowfullscreen>
                    </iframe>
                </div>
                <h4 class="mt-3" id="video-title"><?php echo htmlspecialchars($current_video['video_title']); ?></h4>
                <div class="progress mt-3">
                    <div class="progress-bar" role="progressbar" style="width: <?php echo $watched_percentage; ?>%" 
                         aria-valuenow="<?php echo $watched_percentage; ?>" aria-valuemin="0" aria-valuemax="100">
                        <?php echo round($watched_percentage, 2); ?>% Watched
                    </div>
                </div>

                <!-- Video Size Selector -->
                <div class="mt-3">
                    <label for="video-size">Select Video Size:</label>
                    <select id="video-size" class="form-select" onchange="changeVideoSize(this)">
                        <option value="sm">Small</option>
                        <option value="md" selected>Medium</option>
                        <option value="lg">Large</option>
                    </select>
                </div>

                <!-- Message After Watching All Videos -->
                <?php if ($watched_percentage == 100): ?>
                    <div class="alert alert-success mt-4">You have completed all videos for Day <?php echo $current_video['day']; ?>!</div>
                <?php endif; ?>

            <?php else: ?>
                <div class="alert alert-info text-center mt-4">No videos available for you.</div>
            <?php endif; ?>
        </div>

        <!-- Sidebar Video List -->
        <div class="col-md-4">
            <h5 class="mb-3">Recommended Videos</h5>
            <div class="video-list">
                <?php 
                // Reset result pointer to the beginning to loop through again
                mysqli_data_seek($result, 0);
                $day_videos = [];

                // Group videos by day
                while ($video = mysqli_fetch_assoc($result)) {
                    $day_videos[$video['day']][] = $video;
                }

                // Display videos by day, in ascending order
                foreach ($day_videos as $day => $videos) {
                    echo "<div class='video-day-title'>Day $day</div>";
                    foreach ($videos as $video) {
                        if ($video['id'] != $current_video['id']) {
                            $video_link = convertToEmbed($video['video_link']) . "?controls=1&autoplay=1&disablekb=1&modestbranding=1&rel=0";
                            ?>
                            <div class="video-card" onclick="changeVideo('<?php echo $video_link; ?>', '<?php echo $video['video_title']; ?>')">
                                <img src="https://img.youtube.com/vi/<?php echo explode("embed/", $video_link)[1]; ?>/0.jpg" alt="Thumbnail">
                                <div class="video-info">
                                    <p class="video-title"><?php echo htmlspecialchars($video['video_title']); ?></p>
                                </div>
                            </div>
                            <?php
                        }
                    }
                }
                ?>
            </div>
        </div>
    </div>
</div>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Certificate Download</title>

    <!-- Bootstrap 5 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">

    <style>
        /* Certificate Section Styling */
        .certificate-section {
            background: #f8f9fa; /* Light grey background */
            border: 3px dashed #28a745; /* Green dashed border */
            padding: 20px;
            border-radius: 12px;
            text-align: center;
            margin-top: 20px;
            transition: all 0.3s ease-in-out;
            box-shadow: 0px 5px 15px rgba(0, 0, 0, 0.1);
        }

        .certificate-section:hover {
            background: #e9f5ee; /* Light green on hover */
            border-color: #218838; /* Darker green border */
            box-shadow: 0px 8px 20px rgba(0, 128, 0, 0.3);
        }

        .certificate-btn {
            font-size: 18px;
            font-weight: bold;
            padding: 12px;
            transition: 0.3s;
        }

        .certificate-btn:hover {
            background: #218838 !important; /* Dark green */
            border-color: #1e7e34 !important;
            transform: scale(1.05); /* Slight zoom effect */
        }

        /* Disabled Button Styling */
        .certificate-btn[disabled] {
            background: #6c757d;
            border-color: #6c757d;
            color: #ddd;
            cursor: not-allowed;
        }
    </style>
</head>
<body>

<div class="container">
    <div class="certificate-section">
        <?php 
        // Example variables (remove these in real implementation)
        $can_download_cert = false; 
        $cert_eligible_date = "2025-03-15"; 
        ?>

        <?php if ($can_download_cert): ?>
            <a href="generate_certificate.php" class="btn btn-success w-100 certificate-btn">🎓 Download Certificate</a>
        <?php else: ?>
            <button class="btn btn-secondary w-100 certificate-btn" disabled>⏳ Certificate available on: <?php echo $cert_eligible_date; ?></button>
        <?php endif; ?>
    </div>
</div>

</body>
</html>

<script>
    function changeVideo(videoLink, videoTitle) {
        var mainVideo = document.getElementById('main-video');
        
        // Clear the iframe source first to stop current video
        mainVideo.src = "about:blank";

        // Set the new video source with autoplay
        setTimeout(() => {
            mainVideo.src = videoLink + "&autoplay=1"; // Enable AutoPlay
            document.getElementById('video-title').textContent = videoTitle;
        }, 100); // Delay to ensure video changes smoothly
    }

    // Change Video Size dynamically
    function changeVideoSize(select) {
        var videoContainer = document.getElementById('main-video-container');
        var selectedSize = select.value;
        
        videoContainer.classList.remove('sm', 'md', 'lg');
        videoContainer.classList.add(selectedSize);
    }
</script>

</body>
</html>
