<?php

require_once __DIR__ . '/../Services/AuthorizationService.php';
require_once __DIR__ . '/../Services/FileSystemService.php';
require_once __DIR__ . '/../Services/MediaAnalysisService.php';
require_once __DIR__ . '/../Services/ProjectService.php';
require_once __DIR__ . '/../Services/AdsOverviewService.php';

/**
 * ProjectsController - Refactored and modularized
 * Main controller for project-related API endpoints
 */
class ProjectsController {
    
    /**
     * List projects for a specific client
     */
    public static function listForClient($clientDir) {
        AuthorizationService::requireClientAccess($clientDir);
        
        $result = ProjectService::getProjectsForClient($clientDir);
        
        if (!$result['success']) {
            http_response_code(404);
        }
        
        header('Content-Type: application/json');
        echo json_encode($result);
    }
    
    /**
     * Save project order for a client
     */
    public static function saveProjectOrder($clientDir) {
        AuthorizationService::requireClientAccess($clientDir);
        $clientDir = rawurldecode($clientDir);
        
        // Read JSON body
        $input = file_get_contents('php://input');
        $data = json_decode($input, true);
        
        if (!isset($data['order']) || !is_array($data['order'])) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'error' => [
                    'code' => 'INVALID_DATA',
                    'message' => 'Ungültige Daten. "order" Array erwartet.'
                ]
            ]);
            return;
        }
        
        $result = ProjectService::saveProjectOrder($clientDir, $data);
        
        if (!$result['success']) {
            http_response_code($result['error']['code'] === 'NOT_FOUND' ? 404 : 500);
        }
        
        header('Content-Type: application/json');
        echo json_encode($result);
    }
    
    /**
     * Get project details (poster, logo, etc.)
     */
    public static function projectDetails($clientDir, $projectName) {
        AuthorizationService::requireClientAccess($clientDir);
        $clientDir = rawurldecode($clientDir);
        $projectName = rawurldecode($projectName);
        
        $result = ProjectService::getProjectDetails($clientDir, $projectName);
        
        header('Content-Type: application/json');
        echo json_encode($result);
    }
    
    /**
     * Get ads folders for a project
     */
    public static function adsFolders($clientDir, $projectName) {
        AuthorizationService::requireClientAccess($clientDir);
        $clientDir = rawurldecode($clientDir);
        $projectName = rawurldecode($projectName);
        
        $adsPath = __DIR__ . FileSystemService::getAreaPath() . '/' . $clientDir . '/' . $projectName . '/ads';
        $folders = [];
        
        if (is_dir($adsPath)) {
            foreach (scandir($adsPath) as $entry) {
                if ($entry === '.' || $entry === '..') continue;
                if (is_dir($adsPath . '/' . $entry)) {
                    $folders[] = $entry;
                }
            }
        }
        
        header('Content-Type: application/json');
        echo json_encode(['folders' => $folders]);
    }
    
    /**
     * Get subfolders within ads
     */
    public static function adsSubfolders($clientDir, $projectName, ...$adsFolders) {
        AuthorizationService::requireClientAccess($clientDir);
        $adsFolders = array_map('rawurldecode', $adsFolders);
        
        $base = __DIR__ . FileSystemService::getAreaPath() . '/' . $clientDir . '/' . $projectName . '/ads';
        if (!empty($adsFolders)) {
            $base .= '/' . implode('/', $adsFolders);
        }
        
        $real = realpath($base);
        $folders = [];
        
        if (FileSystemService::validatePath($real, $clientDir) && is_dir($real)) {
            foreach (scandir($real) as $entry) {
                if ($entry === '.' || $entry === '..') continue;
                if (is_dir($real . '/' . $entry)) {
                    $folders[] = $entry;
                }
            }
        }
        
        header('Content-Type: application/json');
        echo json_encode(['folders' => $folders]);
    }
    
    /**
     * Get files within ads folder (any depth)
     */
    public static function adsFolderFiles($clientDir, $projectName, ...$adsFolders) {
        AuthorizationService::requireClientAccess($clientDir);
        $adsFolders = array_map('rawurldecode', $adsFolders);
        
        $base = __DIR__ . FileSystemService::getAreaPath() . '/' . $clientDir . '/' . $projectName . '/ads';
        if (!empty($adsFolders)) {
            $base .= '/' . implode('/', $adsFolders);
        }
        
        $real = realpath($base);
        $files = [];
        
        if (FileSystemService::validatePath($real, $clientDir) && is_dir($real)) {
            foreach (scandir($real) as $entry) {
                if ($entry === '.' || $entry === '..') continue;
                $full = $real . '/' . $entry;
                
                if (is_file($full)) {
                    // Skip ignored files
                    if (FileSystemService::shouldIgnoreFile($entry)) {
                        continue;
                    }
                    
                    $type = FileSystemService::getFileType($entry);
                    $url = FileSystemService::createFileUrl($clientDir, $projectName, $adsFolders, $entry);
                    
                    $files[] = [
                        'name' => $entry,
                        'type' => $type,
                        'url' => $url
                    ];
                }
            }
        }
        
        header('Content-Type: application/json');
        echo json_encode(['files' => $files]);
    }
    
    /**
     * Get both folders and files within ads folder (any depth)
     */
    public static function adsFolderContent($clientDir, $projectName, ...$adsFolders) {
        AuthorizationService::requireClientAccess($clientDir);
        $adsFolders = array_map('rawurldecode', $adsFolders);
        
        $base = __DIR__ . FileSystemService::getAreaPath() . '/' . $clientDir . '/' . $projectName . '/ads';
        if (!empty($adsFolders)) {
            $base .= '/' . implode('/', $adsFolders);
        }
        
        $real = realpath($base);
        $folders = [];
        $files = [];
        
        if (FileSystemService::validatePath($real, $clientDir) && is_dir($real)) {
            foreach (scandir($real) as $entry) {
                if ($entry === '.' || $entry === '..') continue;
                $full = $real . '/' . $entry;
                
                if (is_dir($full)) {
                    $folders[] = $entry;
                } elseif (is_file($full)) {
                    // Skip ignored files
                    if (FileSystemService::shouldIgnoreFile($entry)) {
                        continue;
                    }
                    
                    $type = FileSystemService::getFileType($entry);
                    $url = FileSystemService::createFileUrl($clientDir, $projectName, $adsFolders, $entry);
                    
                    $files[] = [
                        'name' => $entry,
                        'type' => $type,
                        'url' => $url
                    ];
                }
            }
        }
        
        header('Content-Type: application/json');
        echo json_encode([
            'folders' => $folders,
            'files' => $files
        ]);
    }
    
    /**
     * Get config.yaml from any folder path
     */
    public static function getConfig($clientDir, $projectName, ...$adsFolders) {
        AuthorizationService::requireClientAccess($clientDir);
        $adsFolders = array_map('rawurldecode', $adsFolders);
        
        $base = __DIR__ . FileSystemService::getAreaPath() . '/' . $clientDir . '/' . $projectName . '/ads';
        if (!empty($adsFolders)) {
            $base .= '/' . implode('/', $adsFolders);
        }
        
        $real = realpath($base);
        
        if (FileSystemService::validatePath($real, $clientDir) && is_dir($real)) {
            $configFile = $real . '/config.yaml';
            if (file_exists($configFile)) {
                header('Content-Type: text/plain; charset=utf-8');
                readfile($configFile);
                return;
            }
        }
        
        http_response_code(404);
        header('Content-Type: application/json');
        echo json_encode([
            'success' => false,
            'error' => [
                'code' => 'NOT_FOUND',
                'message' => 'config.yaml nicht gefunden'
            ]
        ]);
    }
    
    /**
     * Get recursive ads overview as structured tree with metadata
     */
    public static function adsOverview($clientDir, $projectName) {
        AuthorizationService::requireClientAccess($clientDir);
        $clientDir = rawurldecode($clientDir);
        $projectName = rawurldecode($projectName);
        
        $result = AdsOverviewService::generateOverview($clientDir, $projectName);
        
        header('Content-Type: application/json');
        echo json_encode($result['data'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
    }
    
    /**
     * Get project→client mapping for admin smart URL resolution
     */
    public static function getProjectClientMapping() {
        $user = AuthorizationService::requireAdminAccess();
        
        // Load admin data for client permissions
        $adminData = AuthorizationService::getAdminData($user['username']);
        $disallowedClients = $adminData['disallowedClients'] ?? [];
        
        $areaPath = __DIR__ . FileSystemService::getAreaPath();
        $mapping = [];
        
        // Scan all client directories
        if (is_dir($areaPath)) {
            $clientDirs = scandir($areaPath);
            foreach ($clientDirs as $clientDir) {
                if ($clientDir === '.' || $clientDir === '..' || !is_dir($areaPath . '/' . $clientDir)) {
                    continue;
                }
                
                // Check if admin has access to this client
                if (in_array($clientDir, $disallowedClients)) {
                    continue;
                }
                
                $clientPath = $areaPath . '/' . $clientDir;
                if (is_dir($clientPath)) {
                    $projects = scandir($clientPath);
                    foreach ($projects as $project) {
                        if ($project === '.' || $project === '..' || !is_dir($clientPath . '/' . $project)) {
                            continue;
                        }
                        
                        // Ignore special files
                        if (in_array($project, ['project_order.json', 'logins.json'])) {
                            continue;
                        }
                        
                        // Add project→client mapping
                        $mapping[$project] = $clientDir;
                    }
                }
            }
        }
        
        header('Content-Type: application/json');
        echo json_encode([
            'success' => true,
            'mapping' => $mapping,
            'adminInfo' => [
                'username' => $user['username'],
                'disallowedClients' => $disallowedClients
            ]
        ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    }
}
