<?php
/**
 * Video Watch Page - Public
 * Shareable URL: video.php?id=X
 */

require_once 'config/database.php';
require_once 'includes/functions.php';
require_once 'includes/auth.php';

$videoId = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (!$videoId) {
    header('Location: index.php');
    exit;
}

$video = getVideoById($videoId);

if (!$video || $video['status'] !== 'active') {
    header('Location: index.php');
    exit;
}

// Increment view count
global $pdo;
try {
    $pdo->prepare("UPDATE videos SET download_count = download_count + 1 WHERE id = ?")->execute([$videoId]);
} catch (Exception $e) {}

// Get related videos from same category
$relatedVideos = [];
if (!empty($video['category_id'])) {
    $stmt = $pdo->prepare("SELECT v.*, c.name as category_name FROM videos v 
                           LEFT JOIN categories c ON v.category_id = c.id 
                           WHERE v.category_id = ? AND v.id != ? AND v.status = 'active' 
                           ORDER BY v.created_at DESC LIMIT 6");
    $stmt->execute([$video['category_id'], $videoId]);
    $relatedVideos = $stmt->fetchAll();
}

$settings = getAllSettings();
$categories = getCategories();

$siteName = $settings['site_name'] ?? 'Video Portal';
$portalLogo = $settings['portal_logo'] ?? '';
$rtl = $settings['rtl_direction'] ?? '0';
$dir = $rtl == '1' ? 'rtl' : 'ltr';
$primaryColor = $settings['primary_color'] ?? '#3498db';
$secondaryColor = $settings['secondary_color'] ?? '#2c3e50';
$sidebarColor = $settings['sidebar_color'] ?? '#1e272e';
$footerText = $settings['footer_text'] ?? '';

// Shareable URL
$shareUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') 
            . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

// Determine video type
$videoUrl = $video['video_url'] ?? '';
$isYouTube = strpos($videoUrl, 'youtube.com') !== false || strpos($videoUrl, 'youtu.be') !== false;
$isVimeo = strpos($videoUrl, 'vimeo.com') !== false;
$isLocalFile = $video['video_type'] === 'file';
$isPlayable = $isYouTube || $isVimeo || $isLocalFile || preg_match('/\.(mp4|webm|ogg|mov)$/i', $videoUrl);

// Extract embed URL
$embedUrl = '';
if ($isYouTube) {
    if (strpos($videoUrl, 'youtu.be/') !== false) {
        $ytId = explode('/', parse_url($videoUrl, PHP_URL_PATH))[1] ?? '';
    } else {
        parse_str(parse_url($videoUrl, PHP_URL_QUERY) ?? '', $params);
        $ytId = $params['v'] ?? '';
    }
    $embedUrl = 'https://www.youtube.com/embed/' . $ytId . '?autoplay=1&rel=0';
} elseif ($isVimeo) {
    $vimeoId = basename(parse_url($videoUrl, PHP_URL_PATH));
    $embedUrl = 'https://player.vimeo.com/video/' . $vimeoId . '?autoplay=1';
}
?>
<!DOCTYPE html>
<html lang="<?= $rtl == '1' ? 'he' : 'en' ?>" dir="<?= $dir ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($video['title']) ?> - <?= htmlspecialchars($siteName) ?></title>
    
    <!-- Open Graph for sharing -->
    <meta property="og:title" content="<?= htmlspecialchars($video['title']) ?>">
    <meta property="og:description" content="<?= htmlspecialchars($video['description'] ?? '') ?>">
    <meta property="og:url" content="<?= htmlspecialchars($shareUrl) ?>">
    <meta property="og:type" content="video.other">
    <?php if (!empty($video['thumbnail'])): ?>
    <meta property="og:image" content="assets/uploads/videos/<?= htmlspecialchars($video['thumbnail']) ?>">
    <?php endif; ?>
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="assets/css/style.css">
    <style>
        :root {
            --primary-color: <?= $primaryColor ?>;
            --secondary-color: <?= $secondaryColor ?>;
            --sidebar-color: <?= $sidebarColor ?>;
        }
        
        /* Video Player */
        .video-player-container {
            background: #000;
            border-radius: 12px;
            overflow: hidden;
            margin-bottom: 25px;
            box-shadow: 0 5px 30px rgba(0,0,0,0.3);
        }
        
        .video-player {
            position: relative;
            padding-top: 56.25%;
            background: #000;
        }
        
        .video-player video,
        .video-player iframe {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            border: none;
        }
        
        .video-player .external-link {
            position: absolute;
            top: 0; left: 0; right: 0; bottom: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            text-align: center;
        }
        
        .external-link i { font-size: 60px; margin-bottom: 15px; color: var(--primary-color); }
        .external-link a {
            display: inline-block;
            margin-top: 15px;
            padding: 12px 30px;
            background: var(--primary-color);
            color: white;
            text-decoration: none;
            border-radius: 8px;
            font-weight: 600;
        }
        
        /* Video Info */
        .video-details {
            background: white;
            border-radius: 12px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        
        .video-details h1 {
            font-size: 24px;
            color: var(--secondary-color);
            margin-bottom: 15px;
        }
        
        .video-meta-bar {
            display: flex;
            align-items: center;
            gap: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
            margin-bottom: 15px;
            flex-wrap: wrap;
        }
        
        .video-meta-bar span {
            color: #666;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 6px;
        }
        
        .video-description {
            color: #555;
            line-height: 1.7;
            font-size: 15px;
        }
        
        /* Action Buttons */
        .video-actions {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            margin-top: 20px;
        }
        
        .video-actions .btn {
            padding: 12px 20px;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 8px;
            cursor: pointer;
            border: none;
            text-decoration: none;
            transition: all 0.2s;
        }
        
        .btn-download-lg {
            background: #27ae60;
            color: white;
        }
        .btn-download-lg:hover { background: #219a52; }
        
        .btn-share {
            background: #3498db;
            color: white;
        }
        .btn-share:hover { background: #2980b9; }
        
        .btn-copy {
            background: #8e44ad;
            color: white;
        }
        .btn-copy:hover { background: #7d3c98; }
        
        .btn-back {
            background: #95a5a6;
            color: white;
        }
        .btn-back:hover { background: #7f8c8d; }
        
        /* Share URL Box */
        .share-url-box {
            display: none;
            margin-top: 15px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 8px;
            border: 1px solid #e1e1e1;
        }
        
        .share-url-box.active { display: block; }
        
        .share-url-box label {
            font-weight: 600;
            margin-bottom: 8px;
            display: block;
            color: #444;
        }
        
        .share-url-input {
            display: flex;
            gap: 10px;
        }
        
        .share-url-input input {
            flex: 1;
            padding: 10px 15px;
            border: 2px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
            direction: ltr;
        }
        
        .share-url-input button {
            padding: 10px 20px;
            background: var(--primary-color);
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            white-space: nowrap;
        }
        
        .share-social {
            display: flex;
            gap: 10px;
            margin-top: 12px;
        }
        
        .share-social a {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 16px;
            text-decoration: none;
            transition: transform 0.2s;
        }
        
        .share-social a:hover { transform: scale(1.1); }
        .share-whatsapp { background: #25D366; }
        .share-telegram { background: #0088cc; }
        .share-facebook { background: #1877F2; }
        .share-twitter { background: #1DA1F2; }
        .share-email { background: #666; }
        
        .copied-toast {
            display: none;
            color: #27ae60;
            font-weight: 600;
            margin-top: 8px;
        }
        
        .copied-toast.show { display: block; }
        
        /* Related Videos */
        .related-section h2 {
            font-size: 20px;
            margin-bottom: 20px;
            color: var(--secondary-color);
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .related-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 20px;
        }
        
        .related-card {
            background: white;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            transition: transform 0.2s;
        }
        
        .related-card:hover { transform: translateY(-3px); }
        
        .related-card a { text-decoration: none; color: inherit; }
        
        .related-card .thumb {
            height: 140px;
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 30px;
            position: relative;
            overflow: hidden;
        }
        
        .related-card .thumb img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .related-card .info {
            padding: 12px 15px;
        }
        
        .related-card .info h4 {
            font-size: 14px;
            margin-bottom: 5px;
            color: #333;
        }
        
        .related-card .info small { color: #888; }
        
        @media (max-width: 768px) {
            .video-details h1 { font-size: 20px; }
            .video-actions { flex-direction: column; }
            .video-actions .btn { justify-content: center; }
            .related-grid { grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); }
        }
    </style>
</head>
<body class="<?= $rtl == '1' ? 'rtl' : '' ?>">
    <div class="portal-wrapper">
        <aside class="sidebar">
            <div class="sidebar-header">
                <?php if (!empty($portalLogo)): ?>
                    <img src="assets/uploads/logos/<?= $portalLogo ?>" alt="<?= htmlspecialchars($siteName) ?>">
                <?php else: ?>
                    <i class="fas fa-play-circle" style="font-size: 40px;"></i>
                <?php endif; ?>
                <h2><?= htmlspecialchars($siteName) ?></h2>
            </div>
            
            <ul class="sidebar-menu">
                <li>
                    <a href="index.php">
                        <i class="fas fa-home"></i>
                        <span>All Videos</span>
                    </a>
                </li>
                
                <div class="menu-divider"></div>
                
                <?php foreach ($categories as $category): ?>
                <li>
                    <a href="index.php?category=<?= $category['id'] ?>"
                       class="<?= ($video['category_id'] ?? 0) == $category['id'] ? 'active' : '' ?>">
                        <i class="<?= $category['icon'] ?? 'fas fa-folder' ?>"></i>
                        <span><?= htmlspecialchars($category['name']) ?></span>
                    </a>
                </li>
                <?php endforeach; ?>
                
                <?php if (isLoggedIn() && isAdmin()): ?>
                <div class="menu-divider"></div>
                <li>
                    <a href="admin/dashboard.php">
                        <i class="fas fa-cog"></i>
                        <span>Admin Panel</span>
                    </a>
                </li>
                <li>
                    <a href="logout.php">
                        <i class="fas fa-sign-out-alt"></i>
                        <span>Logout</span>
                    </a>
                </li>
                <?php endif; ?>
            </ul>
        </aside>
        
        <main class="main-content">
            <!-- Video Player -->
            <div class="video-player-container">
                <div class="video-player">
                    <?php if ($isYouTube || $isVimeo): ?>
                        <iframe src="<?= htmlspecialchars($embedUrl) ?>" 
                                allowfullscreen allow="autoplay; encrypted-media"></iframe>
                    <?php elseif ($isLocalFile): ?>
                        <video controls autoplay>
                            <source src="assets/uploads/videos/<?= htmlspecialchars($video['file_path']) ?>" type="video/mp4">
                            Your browser does not support video playback.
                        </video>
                    <?php elseif (preg_match('/\.(mp4|webm|ogg|mov)$/i', $videoUrl)): ?>
                        <video controls autoplay>
                            <source src="<?= htmlspecialchars($videoUrl) ?>">
                            Your browser does not support video playback.
                        </video>
                    <?php else: ?>
                        <div class="external-link">
                            <div>
                                <i class="fas fa-external-link-alt"></i>
                                <p>This video is hosted externally</p>
                                <a href="<?= htmlspecialchars($videoUrl) ?>" target="_blank">
                                    <i class="fas fa-external-link-alt"></i> Open Video
                                </a>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- Video Details -->
            <div class="video-details">
                <h1><?= htmlspecialchars($video['title']) ?></h1>
                
                <div class="video-meta-bar">
                    <span><i class="fas fa-folder"></i> <?= htmlspecialchars($video['category_name'] ?? 'Uncategorized') ?></span>
                    <span><i class="fas fa-eye"></i> <?= number_format($video['download_count']) ?> views</span>
                    <span><i class="fas fa-calendar"></i> <?= date('M d, Y', strtotime($video['created_at'])) ?></span>
                    <?php if ($video['video_type'] === 'file'): ?>
                        <span><i class="fas fa-hdd"></i> Hosted</span>
                    <?php else: ?>
                        <span><i class="fas fa-link"></i> External</span>
                    <?php endif; ?>
                </div>
                
                <?php if (!empty($video['description'])): ?>
                <div class="video-description">
                    <?= nl2br(htmlspecialchars($video['description'])) ?>
                </div>
                <?php endif; ?>
                
                <div class="video-actions">
                    <a href="download.php?id=<?= $video['id'] ?>" class="btn btn-download-lg">
                        <i class="fas fa-download"></i> Download
                    </a>
                    <button class="btn btn-share" onclick="toggleShare()">
                        <i class="fas fa-share-alt"></i> Share
                    </button>
                    <button class="btn btn-copy" onclick="copyLink()">
                        <i class="fas fa-link"></i> Copy Link
                    </button>
                    <a href="index.php" class="btn btn-back">
                        <i class="fas fa-arrow-left"></i> Back
                    </a>
                </div>
                
                <!-- Share URL Box -->
                <div class="share-url-box" id="shareBox">
                    <label><i class="fas fa-link"></i> Video Link:</label>
                    <div class="share-url-input">
                        <input type="text" id="shareUrl" value="<?= htmlspecialchars($shareUrl) ?>" readonly onclick="this.select()">
                        <button onclick="copyLink()"><i class="fas fa-copy"></i> Copy</button>
                    </div>
                    <div class="copied-toast" id="copiedToast">
                        <i class="fas fa-check"></i> Link copied to clipboard!
                    </div>
                    
                    <div class="share-social">
                        <a href="https://wa.me/?text=<?= urlencode($video['title'] . ' - ' . $shareUrl) ?>" 
                           target="_blank" class="share-whatsapp" title="WhatsApp">
                            <i class="fab fa-whatsapp"></i>
                        </a>
                        <a href="https://t.me/share/url?url=<?= urlencode($shareUrl) ?>&text=<?= urlencode($video['title']) ?>" 
                           target="_blank" class="share-telegram" title="Telegram">
                            <i class="fab fa-telegram-plane"></i>
                        </a>
                        <a href="https://www.facebook.com/sharer/sharer.php?u=<?= urlencode($shareUrl) ?>" 
                           target="_blank" class="share-facebook" title="Facebook">
                            <i class="fab fa-facebook-f"></i>
                        </a>
                        <a href="https://twitter.com/intent/tweet?url=<?= urlencode($shareUrl) ?>&text=<?= urlencode($video['title']) ?>" 
                           target="_blank" class="share-twitter" title="Twitter">
                            <i class="fab fa-twitter"></i>
                        </a>
                        <a href="mailto:?subject=<?= urlencode($video['title']) ?>&body=<?= urlencode($video['title'] . "\n\n" . $shareUrl) ?>" 
                           class="share-email" title="Email">
                            <i class="fas fa-envelope"></i>
                        </a>
                    </div>
                </div>
            </div>
            
            <!-- Related Videos -->
            <?php if (!empty($relatedVideos)): ?>
            <div class="related-section">
                <h2><i class="fas fa-film"></i> Related Videos</h2>
                <div class="related-grid">
                    <?php foreach ($relatedVideos as $rel): ?>
                    <div class="related-card">
                        <a href="video.php?id=<?= $rel['id'] ?>">
                            <div class="thumb">
                                <?php if (!empty($rel['thumbnail'])): ?>
                                    <img src="assets/uploads/videos/<?= $rel['thumbnail'] ?>" alt="">
                                <?php else: ?>
                                    <i class="fas fa-play"></i>
                                <?php endif; ?>
                            </div>
                            <div class="info">
                                <h4><?= htmlspecialchars($rel['title']) ?></h4>
                                <small><i class="fas fa-eye"></i> <?= number_format($rel['download_count']) ?> views</small>
                            </div>
                        </a>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>
            
            <div style="text-align: center; padding: 30px 0; color: #666; font-size: 14px;">
                <?= htmlspecialchars($footerText) ?>
            </div>
        </main>
    </div>
    
    <button class="mobile-toggle">
        <i class="fas fa-bars"></i>
    </button>
    
    <script src="assets/js/script.js"></script>
    <script>
        function toggleShare() {
            document.getElementById('shareBox').classList.toggle('active');
        }
        
        function copyLink() {
            var input = document.getElementById('shareUrl');
            input.select();
            input.setSelectionRange(0, 99999);
            
            if (navigator.clipboard) {
                navigator.clipboard.writeText(input.value).then(function() {
                    showCopied();
                });
            } else {
                document.execCommand('copy');
                showCopied();
            }
            
            // Show share box if not visible
            document.getElementById('shareBox').classList.add('active');
        }
        
        function showCopied() {
            var toast = document.getElementById('copiedToast');
            toast.classList.add('show');
            setTimeout(function() {
                toast.classList.remove('show');
            }, 3000);
        }
    </script>
</body>
</html>
