    <?php
    header('Content-Type: application/json');

    // Enable error reporting for debugging (disable in production)
    error_reporting(E_ALL);
    ini_set('display_errors', 0);
    ini_set('log_errors', 1);

    // Configuration
    $downloadDir = __DIR__ . '/downloads/';
    $maxFileSize = 100 * 1024 * 1024; // 100MB max file size

    // Include pure PHP YouTube downloader
    require_once __DIR__ . '/youtube_downloader.php';

    // Function to send error response
    function sendError($message) {
        echo json_encode(['success' => false, 'message' => $message]);
        exit;
    }

    // Check if required functions are available
    $hasShellExec = function_exists('shell_exec');
    $hasExec = function_exists('exec');
    $hasProcOpen = function_exists('proc_open');
    $hasCurl = function_exists('curl_init');

    // Check allow_url_fopen properly (returns "1", "On", "0", "Off", or false)
    $allowUrlFopen = ini_get('allow_url_fopen');
    $hasFileGetContents = ($allowUrlFopen === '1' || $allowUrlFopen === 'On' || $allowUrlFopen === 'on' || $allowUrlFopen === true);

    // We need at least file_get_contents with allow_url_fopen for pure PHP method
    if (!$hasFileGetContents) {
        // Try to test if it actually works (sometimes ini_get is wrong)
        $testUrl = 'https://www.google.com/favicon.ico';
        $testResult = @file_get_contents($testUrl, false, stream_context_create([
            'http' => ['timeout' => 5]
        ]));
        
        if ($testResult === false) {
            sendError('allow_url_fopen appears to be disabled. Please enable it in php.ini, .htaccess, or .user.ini file. Contact your hosting provider if needed.');
        }
        // If test works, continue even if ini_get says it's disabled
    }

    // Create downloads directory if it doesn't exist
    if (!file_exists($downloadDir)) {
        mkdir($downloadDir, 0755, true);
    }

    // Get YouTube URL from POST request
    $youtubeUrl = isset($_POST['youtube_url']) ? trim($_POST['youtube_url']) : '';

    if (empty($youtubeUrl)) {
        sendError('Please provide a YouTube URL');
    }

    // Validate YouTube URL
    if (!preg_match('/^(https?:\/\/)?(www\.)?(youtube\.com|youtu\.be)\/.+/', $youtubeUrl)) {
        sendError('Invalid YouTube URL');
    }

    // Check if it's a playlist URL
    $isPlaylist = false;
    $playlistId = null;
    $videoId = null;
    
    // Extract playlist ID
    if (preg_match('/[&?]list=([a-zA-Z0-9_-]+)/', $youtubeUrl, $playlistMatches)) {
        $isPlaylist = true;
        $playlistId = $playlistMatches[1];
    }
    
    // Extract video ID (for single video or first video in playlist)
    if (preg_match('/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]{11})/', $youtubeUrl, $matches)) {
        $videoId = $matches[1];
    }
    
    // If it's a playlist URL, handle it differently
    if ($isPlaylist && $playlistId) {
        // Check if ZipArchive is available
        if (!class_exists('ZipArchive')) {
            sendError('ZIP support is not available on this server. Please contact your hosting provider to enable the ZipArchive extension.');
        }
        
        // Handle playlist download
        require_once __DIR__ . '/youtube_downloader.php';
        $playlistDownloader = new YouTubePlaylistDownloader($playlistId);
        
        // Try to get video IDs
        $videoIds = $playlistDownloader->getVideoIds(50); // Limit to 50 videos
        
        // If extraction failed, try alternative method using watch page
        if ((!$videoIds || empty($videoIds)) && $videoId) {
            $videoIds = $playlistDownloader->getVideoIdsFromWatchPage($videoId);
        }
        
        if (!$videoIds || empty($videoIds)) {
            sendError('Could not extract videos from playlist. The playlist may be private, empty, or YouTube\'s format may have changed. Please try a different playlist or contact support.');
        }
        
        $playlistTitle = $playlistDownloader->getPlaylistTitle();
        $playlistTitle = preg_replace('/[^a-zA-Z0-9_-]/', '_', $playlistTitle);
        $playlistTitle = substr($playlistTitle, 0, 50); // Limit length
        
        // Download all videos and create ZIP
        $zipFilename = 'playlist_' . $playlistTitle . '_' . uniqid() . '.zip';
        $zipPath = $downloadDir . $zipFilename;
        
        $zip = new ZipArchive();
        if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== TRUE) {
            sendError('Could not create ZIP file');
        }
        
        $successCount = 0;
        $failedCount = 0;
        $totalVideos = count($videoIds);
        
        foreach ($videoIds as $index => $vidId) {
            $downloader = new YouTubeDownloader($vidId);
            $tempFilename = 'temp_' . uniqid() . '.mp3';
            $tempPath = $downloadDir . $tempFilename;
            
            if ($downloader->downloadAudio($tempPath)) {
                $videoTitle = $downloader->getTitle();
                $videoTitle = preg_replace('/[^a-zA-Z0-9_-]/', '_', $videoTitle);
                $videoTitle = substr($videoTitle, 0, 100);
                $safeFilename = ($index + 1) . '_' . $videoTitle . '.mp3';
                
                $zip->addFile($tempPath, $safeFilename);
                $successCount++;
            } else {
                $failedCount++;
            }
            
            // Clean up temp file after adding to zip
            @unlink($tempPath);
        }
        
        $zip->close();
        
        if ($successCount === 0) {
            @unlink($zipPath);
            sendError('Failed to download any videos from the playlist.');
        }
        
        // Check ZIP file size
        $zipSize = filesize($zipPath);
        if ($zipSize > $maxFileSize) {
            @unlink($zipPath);
            sendError('Playlist ZIP file is too large (max ' . round($maxFileSize / 1024 / 1024) . 'MB). Try downloading fewer videos.');
        }
        
        // Return download link
        $downloadUrl = 'downloads/' . $zipFilename;
        echo json_encode([
            'success' => true,
            'download_url' => $downloadUrl,
            'filename' => $zipFilename,
            'size' => $zipSize,
            'is_playlist' => true,
            'total_videos' => $totalVideos,
            'success_count' => $successCount,
            'failed_count' => $failedCount
        ]);
        exit;
    }
    
    // Handle single video download (existing code)
    if (!$videoId) {
        sendError('Could not extract video ID from URL');
    }
    
    // Reconstruct clean URL with just the video ID
    $youtubeUrl = 'https://www.youtube.com/watch?v=' . $videoId;

    // Clean up old files (older than 1 hour)
    $files = glob($downloadDir . '*');
    $now = time();
    foreach ($files as $file) {
        if (is_file($file) && ($now - filemtime($file)) > 3600) {
            @unlink($file);
        }
    }

    // Generate unique filename
    $filename = 'audio_' . uniqid() . '.mp3';
    $outputPath = $downloadDir . $filename;

    // Try pure PHP method first (works without shell commands)
    require_once __DIR__ . '/youtube_downloader.php';
    $downloader = new YouTubeDownloader($videoId);
    $downloadSuccess = false;

    // Attempt pure PHP download
    if ($downloader->downloadAudio($outputPath)) {
        $downloadSuccess = true;
        $actualOutputPath = $outputPath;
    } else {
        // Get more detailed error information
        $videoInfo = $downloader->getVideoInfo();
        if (!$videoInfo) {
            sendError('Could not extract video information from YouTube. The video may be private, unavailable, or YouTube\'s format may have changed. Please try again later.');
        }
        
        $audioUrl = $downloader->getAudioStreamUrl();
        if (!$audioUrl) {
            sendError('Could not find audio stream for this video. The video may not have audio or may be restricted.');
        }
        // Fallback to yt-dlp if available and shell commands are allowed
        if ($hasShellExec || $hasExec || $hasProcOpen) {
            // Check if yt-dlp is available
            $isWindows = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
            $whichCommand = $isWindows ? 'where' : 'which';
            
            // Function to execute command
            function executeCommand($command) {
                if (function_exists('proc_open')) {
                    $descriptorspec = [
                        0 => ['pipe', 'r'],
                        1 => ['pipe', 'w'],
                        2 => ['pipe', 'w']
                    ];
                    $process = @proc_open($command, $descriptorspec, $pipes);
                    if (is_resource($process)) {
                        fclose($pipes[0]);
                        $output = stream_get_contents($pipes[1]);
                        fclose($pipes[1]);
                        fclose($pipes[2]);
                        proc_close($process);
                        return trim($output);
                    }
                }
                if (function_exists('shell_exec')) {
                    return trim(@shell_exec($command . ' 2>&1'));
                }
                if (function_exists('exec')) {
                    $output = [];
                    @exec($command . ' 2>&1', $output);
                    return trim(implode("\n", $output));
                }
                return null;
            }
            
            $ytdlp = executeCommand("$whichCommand yt-dlp");
            $ytdl = executeCommand("$whichCommand youtube-dl");
            
            $ytdlCommand = null;
            if (!empty($ytdlp)) {
                $ytdlCommand = trim($ytdlp);
            } elseif (!empty($ytdl)) {
                $ytdlCommand = trim($ytdl);
            } else {
                // Try common paths
                $commonPaths = [
                    '/usr/local/bin/yt-dlp',
                    '/usr/bin/yt-dlp',
                    '/usr/local/bin/youtube-dl',
                    '/usr/bin/youtube-dl',
                    'yt-dlp',
                    'youtube-dl'
                ];
                
                foreach ($commonPaths as $path) {
                    if (@file_exists($path) && is_executable($path)) {
                        $ytdlCommand = $path;
                        break;
                    }
                }
            }
            
            if (!empty($ytdlCommand)) {
                // Use yt-dlp as fallback
                $escapedUrl = escapeshellarg($youtubeUrl);
                $escapedOutput = escapeshellarg($outputPath);
                $command = "$ytdlCommand -x --audio-format mp3 --audio-quality 0 --no-playlist -o $escapedOutput $escapedUrl 2>&1";
                
                $output = [];
                $returnVar = 0;
                
                if (function_exists('proc_open')) {
                    $descriptorspec = [
                        0 => ['pipe', 'r'],
                        1 => ['pipe', 'w'],
                        2 => ['pipe', 'w']
                    ];
                    $process = @proc_open($command, $descriptorspec, $pipes);
                    if (is_resource($process)) {
                        fclose($pipes[0]);
                        while (!feof($pipes[1])) {
                            $line = fgets($pipes[1]);
                            if ($line !== false) $output[] = trim($line);
                        }
                        while (!feof($pipes[2])) {
                            $line = fgets($pipes[2]);
                            if ($line !== false) $output[] = trim($line);
                        }
                        fclose($pipes[1]);
                        fclose($pipes[2]);
                        $returnVar = proc_close($process);
                    }
                } elseif (function_exists('exec')) {
                    exec($command, $output, $returnVar);
                } elseif (function_exists('shell_exec')) {
                    $result = shell_exec($command);
                    $output = $result ? explode("\n", trim($result)) : [];
                }
                
                if (file_exists($outputPath)) {
                    $downloadSuccess = true;
                    $actualOutputPath = $outputPath;
                } elseif (file_exists($outputPath . '.mp3')) {
                    $downloadSuccess = true;
                    $actualOutputPath = $outputPath . '.mp3';
                    $filename = basename($actualOutputPath);
                }
            }
        }
        
        if (!$downloadSuccess) {
            sendError('Failed to download video. YouTube may have changed their format, or the video may be unavailable. Please try again later.');
        }
    }

    // Check if file exists
    if (!file_exists($actualOutputPath)) {
        sendError('Downloaded file not found. Please try again.');
    }

    // Check file size
    $fileSize = filesize($actualOutputPath);
    if ($fileSize === false || $fileSize == 0) {
        @unlink($actualOutputPath);
        sendError('Downloaded file is empty or invalid');
    }

    if ($fileSize > $maxFileSize) {
        @unlink($actualOutputPath);
        sendError('File too large (max ' . round($maxFileSize / 1024 / 1024) . 'MB)');
    }

    // Return download link
    $downloadUrl = 'downloads/' . $filename;
    echo json_encode([
        'success' => true, 
        'download_url' => $downloadUrl,
        'filename' => $filename,
        'size' => $fileSize
    ]);
    ?>
