<?php
/**
 * Download Handler
 * Video Portal Management System
 */

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

// No login required for downloads
$videoId = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (!$videoId) {
    setFlashMessage('danger', 'Invalid video ID');
    redirect('index.php');
}

$video = getVideoById($videoId);

if (!$video || $video['status'] !== 'active') {
    setFlashMessage('danger', 'Video not found');
    redirect('index.php');
}

// Log the download
$userId = $_SESSION['user_id'] ?? 0;
if ($userId) {
    logDownload($videoId, $userId);
}

// Redirect to video URL or serve file
if ($video['video_type'] === 'file' && !empty($video['file_path'])) {
    $filePath = __DIR__ . '/assets/uploads/videos/' . $video['file_path'];
    
    if (file_exists($filePath)) {
        // Get file info
        $fileName = basename($video['file_path']);
        $fileSize = filesize($filePath);
        $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
        
        // Get mime type with fallback
        $mimeTypes = [
            'mp4' => 'video/mp4',
            'avi' => 'video/x-msvideo',
            'mov' => 'video/quicktime',
            'mkv' => 'video/x-matroska',
            'wmv' => 'video/x-ms-wmv',
            'flv' => 'video/x-flv',
            'webm' => 'video/webm',
            'zip' => 'application/zip',
            'rar' => 'application/x-rar-compressed',
            'pdf' => 'application/pdf',
            'doc' => 'application/msword',
            'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        ];
        
        $mimeType = $mimeTypes[$fileExt] ?? 'application/octet-stream';
        
        // Clear any output buffers
        while (ob_get_level()) {
            ob_end_clean();
        }
        
        // Set headers for download
        header('Content-Description: File Transfer');
        header('Content-Type: ' . $mimeType);
        header('Content-Disposition: attachment; filename="' . $fileName . '"');
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . $fileSize);
        
        // Read and output file
        readfile($filePath);
        exit;
    } else {
        setFlashMessage('danger', 'File not found on server');
        redirect('index.php');
    }
} elseif (!empty($video['video_url'])) {
    // Redirect to external URL
    header('Location: ' . $video['video_url']);
    exit;
} else {
    setFlashMessage('danger', 'No download available for this video');
    redirect('index.php');
}
