<?php
defined('_ISVALID') or exit;

class VUploadSystem {
    public static function uploadForm() {
        if (!VSession::isLoggedIn()) {
            return '<div class="error">Please login to upload videos</div>';
        }
        
        return '
        <div class="upload-container">
            <h2>Upload Video</h2>
            <form id="upload-form" method="post" enctype="multipart/form-data">
                <div class="form-group">
                    <label>Video File</label>
                    <input type="file" name="video_file" accept="video/*" required>
                    <small>Supported formats: MP4, AVI, MOV, WMV (Max: 500MB)</small>
                </div>
                
                <div class="form-group">
                    <label>Title</label>
                    <input type="text" name="title" placeholder="Enter video title" required maxlength="100">
                </div>
                
                <div class="form-group">
                    <label>Description</label>
                    <textarea name="description" placeholder="Describe your video" rows="4"></textarea>
                </div>
                
                <div class="form-group">
                    <label>Category</label>
                    <select name="category">
                        <option value="1">Entertainment</option>
                        <option value="2">Education</option>
                        <option value="3">Music</option>
                        <option value="4">Gaming</option>
                        <option value="5">Sports</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label>Privacy</label>
                    <select name="privacy">
                        <option value="public">Public</option>
                        <option value="private">Private</option>
                        <option value="unlisted">Unlisted</option>
                    </select>
                </div>
                
                <button type="submit" class="btn-upload">Upload Video</button>
            </form>
            
            <div id="upload-progress" style="display:none;">
                <div class="progress-bar">
                    <div class="progress-fill"></div>
                </div>
                <p>Uploading... <span id="progress-text">0%</span></p>
            </div>
        </div>';
    }
    
    public static function processUpload() {
        if (!VSession::isLoggedIn()) {
            return ['error' => 'Not logged in'];
        }
        
        if (!isset($_FILES['video_file']) || $_FILES['video_file']['error'] !== UPLOAD_ERR_OK) {
            return ['error' => 'No file uploaded or upload error'];
        }
        
        $file = $_FILES['video_file'];
        $title = trim($_POST['title'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $category = (int)($_POST['category'] ?? 1);
        $privacy = $_POST['privacy'] ?? 'public';
        
        // Validate inputs
        if (empty($title)) {
            return ['error' => 'Title is required'];
        }
        
        // Check file size (500MB max)
        if ($file['size'] > 500 * 1024 * 1024) {
            return ['error' => 'File too large (max 500MB)'];
        }
        
        // Check file type
        $allowed_types = ['video/mp4', 'video/avi', 'video/quicktime', 'video/x-msvideo'];
        if (!in_array($file['type'], $allowed_types)) {
            return ['error' => 'Invalid file type'];
        }
        
        // Generate unique filename
        $file_key = uniqid() . time();
        $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
        $filename = $file_key . '.' . $extension;
        
        // Create upload directory
        $upload_dir = 'f_data/videos/' . date('Y/m/');
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0755, true);
        }
        
        $target_path = $upload_dir . $filename;
        
        // Move uploaded file
        if (move_uploaded_file($file['tmp_name'], $target_path)) {
            // Save to database
            global $class_database;
            $user_id = VSession::getUserId();
            
            $sql = "INSERT INTO db_videofiles (
                usr_id, file_key, file_title, file_description, file_category,
                privacy, file_name, file_path, upload_date, approved, processing_status
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), 1, 'pending')";
            
            $result = $class_database->execute($sql, [
                $user_id, $file_key, $title, $description, $category,
                $privacy, $filename, $target_path
            ]);
            
            if ($result) {
                // Queue video for processing
                $processor = new VVideoProcessor();
                $jobId = $processor->queueVideoProcessing($target_path, $file_key, [
                    'formats' => ['1080p', '720p', '480p', '360p'],
                    'generate_preview' => true,
                    'generate_hls' => true
                ]);
                
                VLogger::getInstance()->info('Video uploaded and queued for processing', [
                    'file_key' => $file_key,
                    'user_id' => $user_id,
                    'job_id' => $jobId,
                    'file_size' => $file['size'],
                    'original_name' => $file['name']
                ]);
                
                return [
                    'success' => 'Video uploaded successfully and is being processed',
                    'file_key' => $file_key,
                    'job_id' => $jobId,
                    'message' => 'Your video is being processed. You will be notified when it\'s ready.'
                ];
            } else {
                // Clean up file if database insert failed
                unlink($target_path);
                return ['error' => 'Database error'];
            }
        }
        
        return ['error' => 'Failed to save file'];
    }
}
?>