<?php

namespace ProudNerds\Video;

class ImageExtractor
{
    /**
     * Extract a screenshot from a video file at a given percentage.
     *
     * @param string $inputFile The input video file.
     * @param string $outputDir The output directory for the screenshot.
     * @param int $percentage The percentage of the video to extract the screenshot from.
     *
     * @return false|string The path to the screenshot or false if the screenshot could not be created.
     */
    public function extract($inputFile, $outputDir, $percentage)
    {
        // Calculate the duration of the video
        $durationCommand = 'ffmpeg -i ' . escapeshellarg($inputFile) . ' 2>&1 | grep "Duration"';
        $durationOutput = exec($durationCommand);
        preg_match('/Duration: (\d+):(\d+):(\d+\.\d+)/', $durationOutput, $matches);
        $hours = $matches[1];
        $minutes = $matches[2];
        $seconds = $matches[3];
        $durationInSeconds = ($hours * 3600) + ($minutes * 60) + $seconds;

        // Calculate the time position based on the percentage
        $timePosition = (string)floor($durationInSeconds * ($percentage / 100));

        // Create a screenshot of the video at the given percentage
        $screenshot = $outputDir . 'screenshot-' . $percentage . '.jpg';
        if (!file_exists($screenshot)) {
            $command = 'ffmpeg -i ' . escapeshellarg($inputFile) . ' -ss ' . escapeshellarg($timePosition) . ' -vf "thumbnail,scale=iw/2:ih/2" -frames:v 1 ' . escapeshellarg($screenshot);
            exec($command . ' > /dev/null 2>&1');
        }

        // Check if the screenshot was created successfully
        if (!file_exists($screenshot)) {
            return false;
        }

        // Return the path to the screenshot
        return $screenshot;
    }
}
