<?php
/**
 * Main Portal Page - Public
 * Video Portal Management System
 */

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

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

$selectedCategory = isset($_GET['category']) ? intval($_GET['category']) : null;
$searchQuery = isset($_GET['search']) ? trim($_GET['search']) : '';

// Get videos (with search)
if (!empty($searchQuery)) {
    global $pdo;
    $searchTerm = '%' . $searchQuery . '%';
    $sql = "SELECT v.*, c.name as category_name 
            FROM videos v 
            LEFT JOIN categories c ON v.category_id = c.id 
            WHERE v.status = 'active' AND (v.title LIKE ? OR v.description LIKE ?)";
    $params = [$searchTerm, $searchTerm];
    
    if ($selectedCategory) {
        $sql .= " AND v.category_id = ?";
        $params[] = $selectedCategory;
    }
    $sql .= " ORDER BY v.created_at DESC";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $videos = $stmt->fetchAll();
} else {
    $videos = getVideos($selectedCategory);
}

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

$flash = getFlashMessage();

// Base URL for shareable links
$baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') 
           . '://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['SCRIPT_NAME']);
$baseUrl = rtrim($baseUrl, '/') . '/';
?>
<!DOCTYPE html>
<html lang="<?php echo $rtl == '1' ? 'he' : 'en'; ?>" dir="<?= $dir ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($siteName) ?></title>
    <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 ?>;
        }
        
        .search-box {
            display: flex;
            align-items: center;
            gap: 10px;
            flex: 1;
            max-width: 400px;
            margin: 0 20px;
        }
        .search-box input {
            flex: 1;
            padding: 10px 15px;
            border: 2px solid #e1e1e1;
            border-radius: 25px;
            font-size: 14px;
            outline: none;
            transition: border-color 0.3s;
            direction: <?= $dir ?>;
        }
        .search-box input:focus { border-color: var(--primary-color); }
        .search-box button {
            padding: 10px 20px;
            background: var(--primary-color);
            color: white;
            border: none;
            border-radius: 25px;
            cursor: pointer;
        }
        .search-box button:hover { filter: brightness(1.1); }
        
        .search-results-info {
            background: #fff3cd;
            color: #856404;
            padding: 10px 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .search-results-info a { color: #856404; }
        
        .video-thumbnail { position: relative; cursor: pointer; }
        .video-thumbnail .play-overlay {
            position: absolute; top: 0; left: 0; width: 100%; height: 100%;
            background: rgba(0,0,0,0.4);
            display: flex; align-items: center; justify-content: center;
            opacity: 0; transition: opacity 0.3s;
        }
        .video-thumbnail:hover .play-overlay { opacity: 1; }
        .play-overlay i { font-size: 50px; color: white; }
        
        .video-buttons {
            display: flex; gap: 10px; margin-top: 15px;
        }
        .video-buttons .btn {
            flex: 1; text-align: center; padding: 10px; border-radius: 6px;
            text-decoration: none; font-size: 13px; font-weight: 600;
            display: flex; align-items: center; justify-content: center;
            gap: 6px; cursor: pointer; border: none; color: white;
        }
        .btn-play { background: var(--primary-color); }
        .btn-download { background: #27ae60; }
        .btn-play:hover, .btn-download:hover { filter: brightness(1.1); }
        
        @media (max-width: 768px) {
            .top-bar { flex-wrap: wrap; }
            .search-box { order: 3; max-width: 100%; width: 100%; margin: 15px 0 0 0; }
        }
    </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" class="<?= !$selectedCategory && empty($searchQuery) ? 'active' : '' ?>">
                        <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="<?= $selectedCategory == $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">
            <div class="top-bar">
                <h1>
                    <?php if (!empty($searchQuery)): ?>
                        Search Results
                    <?php elseif ($selectedCategory): ?>
                        <?php 
                        foreach ($categories as $cat) {
                            if ($cat['id'] == $selectedCategory) {
                                echo htmlspecialchars($cat['name']) . ' Videos';
                                break;
                            }
                        }
                        ?>
                    <?php else: ?>
                        All Videos
                    <?php endif; ?>
                </h1>
                
                <form class="search-box" method="GET" action="index.php">
                    <?php if ($selectedCategory): ?>
                        <input type="hidden" name="category" value="<?= $selectedCategory ?>">
                    <?php endif; ?>
                    <input type="text" name="search" placeholder="Search videos..." 
                           value="<?= htmlspecialchars($searchQuery) ?>">
                    <button type="submit"><i class="fas fa-search"></i></button>
                </form>
                
                <div class="user-info">
                    <span><?= htmlspecialchars($siteName) ?></span>
                </div>
            </div>
            
            <?php if ($flash): ?>
                <div class="alert alert-<?= $flash['type'] ?>">
                    <i class="fas fa-<?= $flash['type'] === 'success' ? 'check-circle' : 'exclamation-circle' ?>"></i>
                    <?= $flash['message'] ?>
                </div>
            <?php endif; ?>
            
            <?php if (!empty($searchQuery)): ?>
                <div class="search-results-info">
                    <span><i class="fas fa-search"></i> Found <?= count($videos) ?> result(s) for "<?= htmlspecialchars($searchQuery) ?>"</span>
                    <a href="index.php<?= $selectedCategory ? '?category='.$selectedCategory : '' ?>">
                        <i class="fas fa-times"></i> Clear search
                    </a>
                </div>
            <?php endif; ?>
            
            <?php if (!empty($welcomeMessage) && !$selectedCategory && empty($searchQuery)): ?>
            <div class="card">
                <div class="card-body">
                    <p><?= nl2br(htmlspecialchars($welcomeMessage)) ?></p>
                </div>
            </div>
            <?php endif; ?>
            
            <?php if (empty($videos)): ?>
                <div class="card">
                    <div class="card-body">
                        <div class="empty-state">
                            <i class="fas fa-video-slash"></i>
                            <h3>No Videos Found</h3>
                            <p><?= !empty($searchQuery) ? 'Try different keywords.' : 'There are no videos yet.' ?></p>
                        </div>
                    </div>
                </div>
            <?php else: ?>
                <div class="video-grid">
                    <?php foreach ($videos as $video): ?>
                    <div class="video-card">
                        <a href="video.php?id=<?= $video['id'] ?>" style="text-decoration: none; color: inherit;">
                            <div class="video-thumbnail">
                                <?php if (!empty($video['thumbnail'])): ?>
                                    <img src="assets/uploads/videos/<?= $video['thumbnail'] ?>" 
                                         alt="<?= htmlspecialchars($video['title']) ?>">
                                <?php else: ?>
                                    <i class="fas fa-play"></i>
                                <?php endif; ?>
                                <div class="play-overlay">
                                    <i class="fas fa-play-circle"></i>
                                </div>
                            </div>
                        </a>
                        <div class="video-info">
                            <h3><a href="video.php?id=<?= $video['id'] ?>" style="text-decoration: none; color: inherit;"><?= htmlspecialchars($video['title']) ?></a></h3>
                            <p><?= htmlspecialchars(strlen($video['description'] ?? '') > 100 ? substr($video['description'], 0, 100) . '...' : ($video['description'] ?? '')) ?></p>
                            <div class="video-meta">
                                <span class="video-category">
                                    <i class="fas fa-folder"></i> 
                                    <?= htmlspecialchars($video['category_name'] ?? 'Uncategorized') ?>
                                </span>
                                <span>
                                    <i class="fas fa-eye"></i> 
                                    <?= number_format($video['download_count']) ?>
                                </span>
                            </div>
                            <div class="video-buttons">
                                <a href="video.php?id=<?= $video['id'] ?>" class="btn btn-play">
                                    <i class="fas fa-play"></i> Watch
                                </a>
                                <a href="download.php?id=<?= $video['id'] ?>" class="btn btn-download">
                                    <i class="fas fa-download"></i> Download
                                </a>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </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>
</body>
</html>
