<?php

require_once __DIR__ . '/MediaAnalysisService.php';
require_once __DIR__ . '/FileSystemService.php';

/**
 * AdsOverviewService
 * Handles the complex ads overview tree generation with metadata
 */
class AdsOverviewService {
    
    /**
     * Generate recursive ads overview as structured tree
     */
    public static function generateOverview($clientDir, $projectName) {
        $adsRoot = __DIR__ . FileSystemService::getAreaPath() . "/$clientDir/$projectName/ads";
        $baseUrl = $_ENV['BACKEND_URL'] ?? (
            isset($_SERVER['HTTP_HOST']) 
                ? (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] 
                : ''
        );
        
        $tree = self::scanAdsFolder($adsRoot, '', $baseUrl, $clientDir, $projectName);
        
        return [
            'success' => true,
            'data' => $tree
        ];
    }
    
    /**
     * Recursively scan ads folder structure
     */
    private static function scanAdsFolder($absPath, $relPath, $baseUrl, $clientDir, $projectName) {
        $result = [];
        if (!is_dir($absPath)) return $result;
        
        $entries = array_diff(scandir($absPath), ['.', '..']);
        
        foreach ($entries as $entry) {
            $entryAbs = "$absPath/$entry";
            $entryRel = $relPath ? "$relPath/$entry" : $entry;
            
            if (is_dir($entryAbs)) {
                $children = self::scanAdsFolder($entryAbs, $entryRel, $baseUrl, $clientDir, $projectName);
                $depth = substr_count($entryRel, '/');
                
                $type = match($depth) {
                    0 => 'category',
                    1 => 'subcategory', 
                    2 => 'ad',
                    default => 'folder'
                };
                
                $node = [
                    'name' => $entry,
                    'title' => MediaAnalysisService::beautifyTabName($entry),
                    'type' => $type,
                ];
                
                if ($type === 'ad') {
                    $node = self::processAdFolder($node, $entryAbs, $children, $baseUrl, $clientDir, $projectName, $relPath, $entry);
                } else {
                    $node['children'] = array_filter($children, fn($c) => in_array($c['type'], ['category','subcategory','ad','folder']));
                }
                
                $result[] = $node;
                
            } else {
                // File
                $fileNode = self::processFile($entryAbs, $entry, $baseUrl, $clientDir, $projectName, $relPath);
                if ($fileNode) {
                    $result[] = $fileNode;
                }
            }
        }
        
        // Sort: folders first, then files
        usort($result, function($a, $b) {
            if (($a['type'] === 'file') !== ($b['type'] === 'file')) {
                return $a['type'] === 'file' ? 1 : -1;
            }
            return strnatcasecmp($a['name'], $b['name']);
        });
        
        return $result;
    }
    
    /**
     * Process ad folder with HTML detection and config parsing
     */
    private static function processAdFolder($node, $entryAbs, $children, $baseUrl, $clientDir, $projectName, $relPath, $entry) {
        // Check if subfolder with 'html' in name exists
        $htmlFolder = null;
        foreach (scandir($entryAbs) as $sub) {
            if ($sub === '.' || $sub === '..') continue;
            if (is_dir("$entryAbs/$sub") && stripos($sub, 'html') !== false) {
                $htmlFolder = $sub;
                break;
            }
        }
        
        // Collect files, but ignore config.yaml
        $node['files'] = array_values(array_filter($children, function($child) {
            if (in_array($child['type'], ['category','subcategory','ad','folder'])) return false;
            if (isset($child['name']) && preg_match('/^config\.ya?ml$/i', $child['name'])) return false;
            return true;
        }));
        
        // Special case: HTML folder found
        if ($htmlFolder) {
            $htmlAbs = "$entryAbs/$htmlFolder";
            $htmlIndex = "$htmlAbs/index.html";
            
            // Look for config.yaml one level above HTML folder (in ad folder)
            $configYaml = "$entryAbs/config.yaml";
            $meta = [];
            
            if (is_file($configYaml)) {
                $meta = MediaAnalysisService::parseAdConfig($configYaml);
            } else {
                // Fallback: try to extract dimensions from ad folder name (e.g. 800x250)
                $adFolderName = basename($entryAbs);
                $meta = MediaAnalysisService::parseDimensionsFromFolderName($adFolderName);
            }
            
            if (is_file($htmlIndex)) {
                $url = "$baseUrl/area/" . rawurlencode($clientDir) . "/" . rawurlencode($projectName) . "/ads/" 
                     . ($relPath ? str_replace('%2F', '/', rawurlencode($relPath)) . '/' : '') 
                     . rawurlencode($entry) . "/" . rawurlencode($htmlFolder) . "/index.html";
                
                $fileMeta = [
                    'name' => 'index.html',
                    'type' => 'html',
                    'url' => $url,
                    'size' => filesize($htmlIndex),
                    'width' => $meta['width'] ?? 123,
                    'height' => $meta['height'] ?? 456
                ];
                
                // Add index.html only if not already in files
                $already = false;
                foreach ($node['files'] as $f) {
                    if ($f['name'] === 'index.html') { 
                        $already = true; 
                        break; 
                    }
                }
                if (!$already) {
                    $node['files'][] = $fileMeta;
                }
            }
        }
        
        return $node;
    }
    
    /**
     * Process individual file with metadata
     */
    private static function processFile($fileAbs, $entry, $baseUrl, $clientDir, $projectName, $relPath) {
        $type = FileSystemService::getFileType($entry);
        
        $url = "$baseUrl/area/" . rawurlencode($clientDir) . "/" . rawurlencode($projectName) . "/ads/" 
             . ($relPath ? str_replace('%2F', '/', rawurlencode($relPath)) . '/' : '') . rawurlencode($entry);
        
        $meta = ['size' => filesize($fileAbs)];
        
        // Get metadata based on file type
        if ($type === 'image') {
            $imageMeta = MediaAnalysisService::getImageMetadata($fileAbs);
            $meta = array_merge($meta, $imageMeta);
        } elseif ($type === 'video') {
            $videoMeta = MediaAnalysisService::getVideoMetadata($fileAbs);
            $meta = array_merge($meta, $videoMeta);
        }
        
        return array_merge([
            'name' => $entry,
            'title' => MediaAnalysisService::beautifyTabName($entry),
            'type' => $type === 'other' ? 'file' : $type,
            'url' => $url
        ], $meta);
    }
}
