<?php
/**
 * Videos Management
 */

session_start();
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/security.php';
require_once __DIR__ . '/includes/auth.php';

checkAdminAuth();

$pdo = getDBConnection();
$message = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? 'create';
    $id = intval($_POST['id'] ?? 0);
    
    $title = sanitizeInput($_POST['title'] ?? '');
    $description = sanitizeInput($_POST['description'] ?? '');
    $videoUrl = sanitizeInput($_POST['video_url'] ?? '');
    $videoType = sanitizeInput($_POST['video_type'] ?? 'youtube');
    $thumbnailUrl = sanitizeInput($_POST['thumbnail_url'] ?? '');
    $autoplay = isset($_POST['autoplay']) ? 1 : 0;
    $loop = isset($_POST['loop']) ? 1 : 0;
    $muted = isset($_POST['muted']) ? 1 : 0;
    $showControls = isset($_POST['show_controls']) ? 1 : 0;
    $displayOrder = intval($_POST['display_order'] ?? 0);
    $status = sanitizeInput($_POST['status'] ?? 'active');
    
    $uploadDir = __DIR__ . '/../uploads/videos/';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }
    
    // Handle video file upload
    $videoFile = null;
    if (isset($_FILES['video_file']) && $_FILES['video_file']['error'] === UPLOAD_ERR_OK) {
        $allowedVideoTypes = ['video/mp4', 'video/webm', 'video/ogg', 'video/quicktime', 'video/x-msvideo'];
        $maxVideoSize = 500 * 1024 * 1024; // 500MB
        
        if ($_FILES['video_file']['size'] > $maxVideoSize) {
            $message = 'Video file is too large. Maximum size is 500MB.';
        } elseif (in_array($_FILES['video_file']['type'], $allowedVideoTypes)) {
            $extension = pathinfo($_FILES['video_file']['name'], PATHINFO_EXTENSION);
            $filename = 'video_' . uniqid() . '_' . time() . '.' . $extension;
            if (move_uploaded_file($_FILES['video_file']['tmp_name'], $uploadDir . $filename)) {
                $videoFile = $filename;
                $videoType = 'direct';
                $videoUrl = $filename; // Store filename for direct videos
            } else {
                $message = 'Failed to upload video file.';
            }
        } else {
            $message = 'Invalid video file type. Allowed: MP4, WebM, OGG, MOV, AVI.';
        }
    }
    
    // Handle thumbnail upload
    $thumbnailFile = null;
    if (isset($_FILES['thumbnail']) && $_FILES['thumbnail']['error'] === UPLOAD_ERR_OK) {
        $allowedTypes = ['image/jpeg', 'image/png', 'image/webp'];
        if (in_array($_FILES['thumbnail']['type'], $allowedTypes)) {
            $extension = pathinfo($_FILES['thumbnail']['name'], PATHINFO_EXTENSION);
            $filename = 'thumb_' . uniqid() . '_' . time() . '.' . $extension;
            if (move_uploaded_file($_FILES['thumbnail']['tmp_name'], $uploadDir . $filename)) {
                $thumbnailFile = $filename;
            }
        }
    }
    
    // Determine final video URL and type
    $finalVideoUrl = null;
    $finalVideoType = null;
    
    if ($videoFile) {
        $finalVideoUrl = $videoFile;
        $finalVideoType = 'direct';
    } elseif (!empty($videoUrl)) {
        $finalVideoUrl = $videoUrl;
        $finalVideoType = $videoType;
    } elseif ($action === 'update' && $id) {
        // When editing, keep existing video if no new one provided
        $existingStmt = $pdo->prepare("SELECT video_url, video_type FROM videos WHERE id = :id");
        $existingStmt->execute([':id' => $id]);
        $existingData = $existingStmt->fetch(PDO::FETCH_ASSOC);
        if ($existingData) {
            $finalVideoUrl = $existingData['video_url'];
            $finalVideoType = $existingData['video_type'];
        }
    }
    
    if (empty($title)) {
        $message = 'Title is required.';
    } elseif (empty($finalVideoUrl) && $action === 'create') {
        $message = 'Either Video URL or Video File is required.';
    } elseif (empty($finalVideoUrl)) {
        $message = 'Either Video URL or Video File is required.';
    } else {
        if ($action === 'create') {
            $stmt = $pdo->prepare("
                INSERT INTO videos (title, description, video_url, video_type, thumbnail_url, 
                autoplay, `loop`, muted, show_controls, display_order, status) 
                VALUES (:title, :desc, :url, :type, :thumb, :autoplay, :loop, :muted, :controls, :order, :status)
            ");
            $stmt->execute([
                ':title' => $title,
                ':desc' => $description,
                ':url' => $finalVideoUrl,
                ':type' => $finalVideoType,
                ':thumb' => $thumbnailFile ?: $thumbnailUrl,
                ':autoplay' => $autoplay,
                ':loop' => $loop,
                ':muted' => $muted,
                ':controls' => $showControls,
                ':order' => $displayOrder,
                ':status' => $status
            ]);
            $message = 'Video created successfully!';
        } else {
            // Get old video and thumbnail for cleanup
            $oldStmt = $pdo->prepare("SELECT video_url, thumbnail_url, video_type FROM videos WHERE id = :id");
            $oldStmt->execute([':id' => $id]);
            $oldData = $oldStmt->fetch(PDO::FETCH_ASSOC);
            
            // Delete old video file if it was uploaded
            if ($oldData && $oldData['video_type'] === 'direct' && $videoFile) {
                $oldVideoPath = __DIR__ . '/../uploads/videos/' . basename($oldData['video_url']);
                if (file_exists($oldVideoPath) && !is_dir($oldVideoPath)) {
                    unlink($oldVideoPath);
                }
            }
            
            // Delete old thumbnail if new one uploaded
            if ($thumbnailFile && $oldData && $oldData['thumbnail_url']) {
                $oldThumbPath = __DIR__ . '/../uploads/videos/' . basename($oldData['thumbnail_url']);
                if (file_exists($oldThumbPath) && !is_dir($oldThumbPath)) {
                    unlink($oldThumbPath);
                }
            }
            
            $finalThumb = $thumbnailFile ?: $thumbnailUrl;
            
            $stmt = $pdo->prepare("
                UPDATE videos SET title = :title, description = :desc, video_url = :url, 
                video_type = :type, thumbnail_url = :thumb, autoplay = :autoplay, 
                `loop` = :loop, muted = :muted, show_controls = :controls, 
                display_order = :order, status = :status WHERE id = :id
            ");
            $stmt->execute([
                ':title' => $title, ':desc' => $description, ':url' => $finalVideoUrl,
                ':type' => $finalVideoType, ':thumb' => $finalThumb, ':autoplay' => $autoplay,
                ':loop' => $loop, ':muted' => $muted, ':controls' => $showControls,
                ':order' => $displayOrder, ':status' => $status, ':id' => $id
            ]);
            $message = 'Video updated successfully!';
        }
    }
}

// Handle delete
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $stmt = $pdo->prepare("SELECT video_url, thumbnail_url, video_type FROM videos WHERE id = :id");
    $stmt->execute([':id' => $id]);
    $videoData = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($videoData) {
        // Delete video file if it was uploaded
        if ($videoData['video_type'] === 'direct' && $videoData['video_url']) {
            $videoPath = __DIR__ . '/../uploads/videos/' . basename($videoData['video_url']);
            if (file_exists($videoPath) && !is_dir($videoPath)) {
                unlink($videoPath);
            }
        }
        
        // Delete thumbnail if it was uploaded
        if ($videoData['thumbnail_url']) {
            $thumbPath = __DIR__ . '/../uploads/videos/' . basename($videoData['thumbnail_url']);
            if (file_exists($thumbPath) && !is_dir($thumbPath)) {
                unlink($thumbPath);
            }
        }
    }
    
    $pdo->prepare("DELETE FROM videos WHERE id = :id")->execute([':id' => $id]);
    $message = 'Video deleted successfully!';
}

// Get edit item
$editItem = null;
if (isset($_GET['edit'])) {
    $id = intval($_GET['edit']);
    $stmt = $pdo->prepare("SELECT * FROM videos WHERE id = :id");
    $stmt->execute([':id' => $id]);
    $editItem = $stmt->fetch();
}

// Get all videos
$videos = $pdo->query("
    SELECT * FROM videos ORDER BY display_order ASC, created_at DESC
")->fetchAll();

$pageTitle = 'Videos';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?> - Admin Panel</title>
    <link rel="stylesheet" href="assets/admin-modern.css">
</head>
<body>
    <?php 
    $GLOBALS['pdo'] = $pdo;
    include 'includes/sidebar.php'; 
    ?>
    
    <div class="admin-main">
        <?php include 'includes/header-new.php'; ?>
        
        <div class="admin-container">
            <?php if ($message): ?>
                <div class="message success"><?php echo htmlspecialchars($message); ?></div>
            <?php endif; ?>
            
            <!-- Add/Edit Form -->
            <div class="card slide-up">
                <div class="card-header">
                    <h3 class="card-title"><?php echo $editItem ? 'Edit Video' : 'Add New Video'; ?></h3>
                </div>
                <form method="POST" enctype="multipart/form-data" id="videoForm" style="padding: 1.5rem;" onsubmit="return validateVideoForm()">
                    <input type="hidden" name="action" value="<?php echo $editItem ? 'update' : 'create'; ?>">
                    <?php if ($editItem): ?>
                        <input type="hidden" name="id" value="<?php echo $editItem['id']; ?>">
                    <?php endif; ?>
                    
                    <div class="form-group">
                        <label class="form-label">Video Title *</label>
                        <input type="text" name="title" class="form-control" required
                               value="<?php echo htmlspecialchars($editItem['title'] ?? ''); ?>"
                               placeholder="e.g., Drilling Operations in Action">
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Description</label>
                        <textarea name="description" class="form-control" rows="3"><?php echo htmlspecialchars($editItem['description'] ?? ''); ?></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Video Source *</label>
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin-bottom: 1rem;">
                            <div>
                                <label style="display: flex; align-items: center; gap: 0.5rem; margin-bottom: 0.5rem;">
                                    <input type="radio" name="video_source" value="url" id="video_source_url" 
                                           <?php echo ($editItem && $editItem['video_type'] !== 'direct') || !$editItem ? 'checked' : ''; ?>
                                           onchange="toggleVideoInput()">
                                    <span>Video URL</span>
                                </label>
                                <div id="video_url_section">
                                    <input type="url" name="video_url" id="video_url" class="form-control"
                                           value="<?php echo htmlspecialchars(($editItem && $editItem['video_type'] !== 'direct') ? ($editItem['video_url'] ?? '') : ''); ?>"
                                           placeholder="YouTube/Vimeo URL or direct video link">
                                    <small style="color: var(--text-secondary); display: block; margin-top: 0.5rem;">
                                        For YouTube: https://www.youtube.com/watch?v=VIDEO_ID<br>
                                        For Vimeo: https://vimeo.com/VIDEO_ID<br>
                                        Or direct video URL
                                    </small>
                                </div>
                            </div>
                            <div>
                                <label style="display: flex; align-items: center; gap: 0.5rem; margin-bottom: 0.5rem;">
                                    <input type="radio" name="video_source" value="file" id="video_source_file"
                                           <?php echo ($editItem && $editItem['video_type'] === 'direct') ? 'checked' : ''; ?>
                                           onchange="toggleVideoInput()">
                                    <span>Upload Video File</span>
                                </label>
                                <div id="video_file_section">
                                    <input type="file" name="video_file" id="video_file" class="form-control" 
                                           accept="video/mp4,video/webm,video/ogg,video/quicktime,video/x-msvideo">
                                    <small style="color: var(--text-secondary); display: block; margin-top: 0.5rem;">
                                        Max size: 500MB<br>
                                        Formats: MP4, WebM, OGG, MOV, AVI
                                    </small>
                                    <?php if ($editItem && $editItem['video_type'] === 'direct' && $editItem['video_url']): ?>
                                        <div style="margin-top: 0.5rem; padding: 0.5rem; background: var(--bg-primary, #F8FAFC); border-radius: var(--radius-md);">
                                            <strong>Current video:</strong> <?php echo htmlspecialchars(basename($editItem['video_url'])); ?>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-group" id="video_type_section" style="<?php echo ($editItem && $editItem['video_type'] === 'direct') ? 'display: none;' : ''; ?>">
                            <label class="form-label">Video Type</label>
                            <select name="video_type" id="video_type" class="form-control">
                                <option value="youtube" <?php echo ($editItem['video_type'] ?? 'youtube') === 'youtube' ? 'selected' : ''; ?>>YouTube</option>
                                <option value="vimeo" <?php echo ($editItem['video_type'] ?? '') === 'vimeo' ? 'selected' : ''; ?>>Vimeo</option>
                                <option value="direct" <?php echo ($editItem['video_type'] ?? '') === 'direct' ? 'selected' : ''; ?>>Direct Video URL</option>
                                <option value="embed" <?php echo ($editItem['video_type'] ?? '') === 'embed' ? 'selected' : ''; ?>>Embed Code</option>
                            </select>
                        </div>
                    </div>
                    
                    <script>
                    function toggleVideoInput() {
                        const urlRadio = document.getElementById('video_source_url');
                        const fileRadio = document.getElementById('video_source_file');
                        const urlSection = document.getElementById('video_url_section');
                        const fileSection = document.getElementById('video_file_section');
                        const typeSection = document.getElementById('video_type_section');
                        const urlInput = document.getElementById('video_url');
                        const fileInput = document.getElementById('video_file');
                        
                        if (urlRadio.checked) {
                            urlSection.style.display = 'block';
                            fileSection.style.display = 'none';
                            typeSection.style.display = 'block';
                            urlInput.removeAttribute('disabled');
                            fileInput.setAttribute('disabled', 'disabled');
                            fileInput.value = '';
                        } else {
                            urlSection.style.display = 'none';
                            fileSection.style.display = 'block';
                            typeSection.style.display = 'none';
                            urlInput.setAttribute('disabled', 'disabled');
                            fileInput.removeAttribute('disabled');
                            urlInput.value = '';
                        }
                    }
                    
                    function validateVideoForm() {
                        const urlRadio = document.getElementById('video_source_url');
                        const urlInput = document.getElementById('video_url');
                        const fileInput = document.getElementById('video_file');
                        const isEdit = <?php echo $editItem ? 'true' : 'false'; ?>;
                        const hasExistingVideo = <?php echo ($editItem && $editItem['video_type'] === 'direct') ? 'true' : 'false'; ?>;
                        
                        if (urlRadio.checked) {
                            if (!urlInput.value.trim() && !isEdit) {
                                alert('Please enter a video URL or upload a video file.');
                                return false;
                            }
                        } else {
                            if (!fileInput.files.length && !hasExistingVideo && !isEdit) {
                                alert('Please upload a video file or enter a video URL.');
                                return false;
                            }
                        }
                        return true;
                    }
                    
                    // Initialize on page load
                    document.addEventListener('DOMContentLoaded', function() {
                        toggleVideoInput();
                    });
                    </script>
                    
                    <div class="form-group">
                        <label class="form-label">Thumbnail Image</label>
                        <input type="file" name="thumbnail" accept="image/jpeg,image/png,image/webp" class="form-control">
                        <?php if ($editItem && $editItem['thumbnail_url']): ?>
                            <div style="margin-top: 0.5rem;">
                                <?php if (strpos($editItem['thumbnail_url'], 'uploads/') !== false): ?>
                                    <img src="../uploads/videos/<?php echo htmlspecialchars(basename($editItem['thumbnail_url'])); ?>" 
                                         alt="Current thumbnail" style="max-width: 200px; border-radius: var(--radius-md);">
                                <?php else: ?>
                                    <img src="<?php echo htmlspecialchars($editItem['thumbnail_url']); ?>" 
                                         alt="Current thumbnail" style="max-width: 200px; border-radius: var(--radius-md);">
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                        <input type="text" name="thumbnail_url" class="form-control" style="margin-top: 0.5rem;"
                               value="<?php echo htmlspecialchars($editItem['thumbnail_url'] ?? ''); ?>"
                               placeholder="Or enter thumbnail URL">
                    </div>
                    
                    <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 1rem; margin: 1rem 0;">
                        <div class="form-group">
                            <label>
                                <input type="checkbox" name="autoplay" value="1" <?php echo ($editItem['autoplay'] ?? 1) ? 'checked' : ''; ?>>
                                Autoplay
                            </label>
                        </div>
                        <div class="form-group">
                            <label>
                                <input type="checkbox" name="muted" value="1" <?php echo ($editItem['muted'] ?? 1) ? 'checked' : ''; ?>>
                                Muted (required for autoplay)
                            </label>
                        </div>
                        <div class="form-group">
                            <label>
                                <input type="checkbox" name="loop" value="1" <?php echo ($editItem['loop'] ?? 0) ? 'checked' : ''; ?>>
                                Loop
                            </label>
                        </div>
                        <div class="form-group">
                            <label>
                                <input type="checkbox" name="show_controls" value="1" <?php echo ($editItem['show_controls'] ?? 1) ? 'checked' : ''; ?>>
                                Show Controls
                            </label>
                        </div>
                    </div>
                    
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                        <div class="form-group">
                            <label class="form-label">Display Order</label>
                            <input type="number" name="display_order" class="form-control"
                                   value="<?php echo $editItem['display_order'] ?? 0; ?>">
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Status</label>
                            <select name="status" class="form-control">
                                <option value="active" <?php echo ($editItem['status'] ?? 'active') === 'active' ? 'selected' : ''; ?>>Active</option>
                                <option value="inactive" <?php echo ($editItem['status'] ?? '') === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                            </select>
                        </div>
                    </div>
                    
                    <div style="margin-top: 1.5rem;">
                        <button type="submit" class="btn btn-primary">
                            <?php echo $editItem ? 'Update Video' : 'Create Video'; ?>
                        </button>
                        <?php if ($editItem): ?>
                            <a href="videos.php" class="btn btn-secondary">Cancel</a>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
            
            <!-- Videos List -->
            <div class="card slide-up" style="animation-delay: 0.1s; margin-top: 1.5rem;">
                <div class="card-header">
                    <h3 class="card-title">All Videos (<?php echo count($videos); ?>)</h3>
                </div>
                <div style="overflow-x: auto;">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>Thumbnail</th>
                                <th>Title</th>
                                <th>Type</th>
                                <th>Order</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($videos as $video): ?>
                            <tr>
                                <td>
                                    <?php if ($video['thumbnail_url']): ?>
                                        <?php if (strpos($video['thumbnail_url'], 'uploads/') !== false): ?>
                                            <img src="../uploads/videos/<?php echo htmlspecialchars(basename($video['thumbnail_url'])); ?>" 
                                                 alt="Thumbnail" style="width: 80px; height: 45px; object-fit: cover; border-radius: var(--radius-sm);">
                                        <?php else: ?>
                                            <img src="<?php echo htmlspecialchars($video['thumbnail_url']); ?>" 
                                                 alt="Thumbnail" style="width: 80px; height: 45px; object-fit: cover; border-radius: var(--radius-sm);">
                                        <?php endif; ?>
                                    <?php else: ?>
                                        <span style="font-size: 0.875rem; color: var(--text-secondary);">No thumbnail</span>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo htmlspecialchars($video['title']); ?></td>
                                <td>
                                    <span class="badge badge-secondary"><?php echo ucfirst($video['video_type']); ?></span>
                                </td>
                                <td><?php echo $video['display_order']; ?></td>
                                <td>
                                    <span class="badge badge-<?php echo $video['status'] === 'active' ? 'success' : 'danger'; ?>">
                                        <?php echo ucfirst($video['status']); ?>
                                    </span>
                                </td>
                                <td>
                                    <div style="display: flex; gap: 0.5rem;">
                                        <a href="?edit=<?php echo $video['id']; ?>" class="btn btn-primary" style="padding: 0.375rem 0.75rem; font-size: 0.875rem;">Edit</a>
                                        <a href="?delete=<?php echo $video['id']; ?>" 
                                           class="btn" 
                                           style="padding: 0.375rem 0.75rem; font-size: 0.875rem; background: var(--danger-color, #EF4444); color: white;"
                                           onclick="return confirm('Are you sure you want to delete this video?')">Delete</a>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    
    <script src="assets/admin.js"></script>
</body>
</html>

