<?php

require_once __DIR__ . '/../../vendor/getid3/getid3.php';

/**
 * MediaAnalysisService
 * Handles media file analysis and metadata extraction
 */
class MediaAnalysisService {
    
    /**
     * Get image dimensions
     */
    public static function getImageMetadata($filePath) {
        $meta = ['size' => filesize($filePath)];
        
        $imgInfo = @getimagesize($filePath);
        if ($imgInfo) {
            $meta['width'] = $imgInfo[0];
            $meta['height'] = $imgInfo[1];
        }
        
        return $meta;
    }
    
    /**
     * Get video metadata (dimensions and duration)
     */
    public static function getVideoMetadata($filePath) {
        $meta = ['size' => filesize($filePath)];
        
        // Try ffprobe first
        $ffprobePath = shell_exec('which ffprobe');
        $ffprobeUsed = false;
        
        if ($ffprobePath) {
            $ffprobe = trim($ffprobePath);
            if ($ffprobe !== '') {
                $cmd = escapeshellcmd($ffprobe) . ' -v error -select_streams v:0 -show_entries stream=width,height,duration -of default=noprint_wrappers=1:nokey=1 ' . escapeshellarg($filePath);
                $out = shell_exec($cmd);
                
                if ($out) {
                    $lines = explode("\n", trim($out));
                    if (count($lines) >= 3) {
                        $meta['width'] = (int)$lines[0];
                        $meta['height'] = (int)$lines[1];
                        $meta['duration'] = (float)$lines[2];
                        $ffprobeUsed = true;
                    }
                }
            }
        }
        
        // Fallback to getID3 if ffprobe not available or failed
        if (!$ffprobeUsed) {
            try {
                $getID3 = new \getID3();
                $info = $getID3->analyze($filePath);
                
                if (!empty($info['video']['resolution_x']) && !empty($info['video']['resolution_y'])) {
                    $meta['width'] = (int)$info['video']['resolution_x'];
                    $meta['height'] = (int)$info['video']['resolution_y'];
                }
                
                if (!empty($info['playtime_seconds'])) {
                    $meta['duration'] = (float)$info['playtime_seconds'];
                }
            } catch (\Exception $e) {
                // Ignore errors, metadata remains empty
            }
        }
        
        return $meta;
    }
    
    /**
     * Parse config.yaml for ad dimensions
     */
    public static function parseAdConfig($configPath) {
        if (!file_exists($configPath)) {
            return [];
        }
        
        $yaml = file_get_contents($configPath);
        $meta = [];
        $width = 0;
        $height = 0;
        
        $lines = preg_split('/\r?\n/', $yaml);
        foreach ($lines as $line) {
            if ($width === 0 && preg_match('/width\s*:\s*["\']?([\d,.]+)\s*([a-zA-Z%]*)["\']?/i', $line, $wMatch)) {
                $val = str_replace([',', ' '], '', $wMatch[1]);
                $width = (int)floatval($val);
            }
            if ($height === 0 && preg_match('/height\s*:\s*["\']?([\d,.]+)\s*([a-zA-Z%]*)["\']?/i', $line, $hMatch)) {
                $val = str_replace([',', ' '], '', $hMatch[1]);
                $height = (int)floatval($val);
            }
        }
        
        if ($width > 0) $meta['width'] = $width;
        if ($height > 0) $meta['height'] = $height;
        
        return $meta;
    }
    
    /**
     * Extract dimensions from folder name (e.g., "800x250")
     */
    public static function parseDimensionsFromFolderName($folderName) {
        if (preg_match('/(\d{2,5})[xX](\d{2,5})/', $folderName, $matches)) {
            return [
                'width' => (int)$matches[1],
                'height' => (int)$matches[2]
            ];
        }
        return [];
    }
    
    /**
     * Beautify tab names (replace _ and - with spaces, capitalize)
     */
    public static function beautifyTabName($name) {
        $name = str_replace(['_', '-'], ' ', $name);
        $name = mb_strtolower($name, 'UTF-8');
        $name = preg_replace_callback('/\b\w/u', function($m) { 
            return mb_strtoupper($m[0], 'UTF-8'); 
        }, $name);
        return $name;
    }
}
