<?php

namespace ProudNerds\Video;

class VideoConverter
{
    public function convert($inputFile, $outputDir)
    {
        echo "VideoConverter: Starting conversion for file: " . basename($inputFile) . "\n";
        echo "VideoConverter: Output directory: " . $outputDir . "\n";

        // Variable bitrate factor crf (0 = lossless, 51 = worst quality)
        $allowedCodecs = [
            'video/mp4' => ['v' => 'h264', 'a' => 'aac', 'options' => '-profile:v baseline -level 3.1 -pix_fmt yuv420p -crf 23 -movflags +faststart'],
            'video/webm' => ['v' => 'vp8', 'a' => 'libvorbis', 'options' => '-crf 10 -b:v 0'],
        ];

        // Define the sizes
        $sizes = [480, 720, 1080];
        $success = false;

        // First create all mp4 files since it is the most common format
        foreach ($allowedCodecs as $type => $codec) {
            foreach ($sizes as $height) {
                $outputFile = $outputDir . 'video-' . $height . 'p.' . explode('/', $type)[1];
                echo 'Converting ' . basename($inputFile) . ' to ' . basename($outputFile) . PHP_EOL;
                if (file_exists($outputFile)) {
                    echo ' - ALREADY EXISTS' . PHP_EOL;
                    $success = true;
                    continue;
                }

                $command = 'ffmpeg -i ' . escapeshellarg($inputFile) . ' -c:v ' . $codec['v'] . ' -c:a ' . $codec['a'] . ' ' . $codec['options'] . " -vf scale=-2:{$height} " . escapeshellarg($outputFile);

                // Show the command being executed for debugging
                echo "Executing: " . $command . "\n";

                // Execute the command without output
                echo ' - RUNNING ' . PHP_EOL;
                $output = [];
                $returnValue = 0;
                exec($command . ' 2>&1', $output, $returnValue);

                if ($returnValue === 0) {
                    echo ' - DONE (Return Value: ' . $returnValue . ')' . PHP_EOL;
                    $success = true;
                } else {
                    echo ' - FAILED (Return Value: ' . $returnValue . ')' . PHP_EOL;
                    echo "Error output: " . implode("\n", $output) . "\n";
                }
            }
        }

        // Return true if at least one conversion was successful
        return $success;
    }
}
