<?php
namespace App\Controllers;

require_once BASE_PATH . '/app/helpers/permissions.php';

use App\Core\Database;

class AdminDictionaryReplaceController
{
    protected function db()
    {
        return Database::getInstance();
    }

    private function startSession(): void
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }
    }

    private function role(): string
    {
        return (string)($_SESSION['conference_role'] ?? $_SESSION['role'] ?? $_SESSION['user_role'] ?? '');
    }

    private function requireSuperAdmin(): void
    {
        $this->startSession();

        if (empty($_SESSION['user_id'])) {
            header("Location: /easychair/login");
            exit;
        }

        if (!ec_is_superadmin()) {
            http_response_code(403);
            exit(function_exists('t') ? t('msg.access_denied', 'Access denied.') : 'Access denied.');
        }
    }

    private function allowedRoots(): array
    {
        return [
            realpath(BASE_PATH . '/app/views'),
            realpath(BASE_PATH . '/app/controllers'),
        ];
    }

    private function normalizeRelativePath(string $path): string
    {
        $path = trim($path);
        $path = str_replace('\\', '/', $path);
        $path = ltrim($path, '/');

        if (str_starts_with($path, 'var/www/html/easychair/')) {
            $path = substr($path, strlen('var/www/html/easychair/'));
        }

        if (str_starts_with($path, 'app/')) {
            return $path;
        }

        if (str_starts_with($path, 'views/')) {
            return 'app/' . $path;
        }

        if (str_starts_with($path, 'controllers/')) {
            return 'app/' . $path;
        }

        return $path;
    }

    private function resolveFile(string $relative): ?string
    {
        $relative = $this->normalizeRelativePath($relative);

        if ($relative === '') {
            return null;
        }

        if (!preg_match('/\.(php|phtml)$/i', $relative)) {
            return null;
        }

        if (str_contains($relative, '..')) {
            return null;
        }

        $full = realpath(BASE_PATH . '/' . $relative);
        if (!$full || !is_file($full)) {
            return null;
        }

        $allowed = false;
        foreach ($this->allowedRoots() as $root) {
            if ($root && str_starts_with($full, $root . DIRECTORY_SEPARATOR)) {
                $allowed = true;
                break;
            }
        }

        return $allowed ? $full : null;
    }

    private function dictionaryRows(): array
    {
        $stmt = $this->db()->query("
            SELECT translation_key, group_key, text_en, text_ar
            FROM dictionary_translations
            WHERE is_active=1
            ORDER BY LENGTH(text_ar) DESC, LENGTH(text_en) DESC
        ");

        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }

    private function candidateFiles(): array
    {
        $files = [];

        foreach ([BASE_PATH . '/app/views', BASE_PATH . '/app/controllers'] as $root) {
            if (!is_dir($root)) continue;

            $it = new \RecursiveIteratorIterator(
                new \RecursiveDirectoryIterator($root, \FilesystemIterator::SKIP_DOTS)
            );

            foreach ($it as $file) {
                if (!$file->isFile()) continue;

                $path = $file->getPathname();

                if (!preg_match('/\.(php|phtml)$/i', $path)) continue;

                $rel = str_replace(BASE_PATH . '/', '', $path);

                $files[] = $rel;
            }
        }

        sort($files);
        return $files;
    }

    private function buildSuggestions(string $filePath): array
    {
        $full = $this->resolveFile($filePath);
        if (!$full) {
            return [];
        }

        $content = file_get_contents($full);
        if ($content === false) {
            return [];
        }

        $suggestions = [];
        $seen = [];

        foreach ($this->dictionaryRows() as $r) {
            $key = trim((string)($r['translation_key'] ?? ''));
            $textEn = trim((string)($r['text_en'] ?? ''));
            $textAr = trim((string)($r['text_ar'] ?? ''));

            if ($key === '') continue;

            foreach ([$textAr, $textEn] as $text) {
                $text = trim($text);

                if ($text === '') continue;
                if (mb_strlen($text) < 3) continue;
                if (mb_strlen($text) > 160) continue;
                if (isset($seen[$key . '|' . $text])) continue;

                // Skip if already translated around this key.
                if (str_contains($content, "ec_t('" . $key . "'") || str_contains($content, 'ec_t("' . $key . '"')) {
                    continue;
                }

                $count = substr_count($content, $text);
                if ($count <= 0) continue;

                $seen[$key . '|' . $text] = true;

                $safeFallback = str_replace("'", "\\'", $text);
                $replacement = "<?php echo ec_h(ec_t('{$key}','{$safeFallback}')); ?>";

                $suggestions[] = [
                    'translation_key' => $key,
                    'group_key' => $r['group_key'] ?? '',
                    'text' => $text,
                    'replacement' => $replacement,
                    'count' => $count,
                    'file_path' => str_replace(BASE_PATH . '/', '', $full),
                ];
            }
        }

        return array_slice($suggestions, 0, 300);
    }

    private function applySuggestions(string $filePath, array $selected): array
    {
        $full = $this->resolveFile($filePath);
        if (!$full) {
            return ['ok' => false, 'message' => 'Invalid file path.'];
        }

        $content = file_get_contents($full);
        if ($content === false) {
            return ['ok' => false, 'message' => 'Could not read file.'];
        }

        $backupDir = BASE_PATH . '/backups/dictionary_replace_' . date('Ymd_His');
        if (!is_dir($backupDir)) {
            mkdir($backupDir, 0775, true);
        }

        copy($full, $backupDir . '/' . basename($full) . '.bak');

        $changed = 0;

        foreach ($selected as $row) {
            $text = (string)($row['text'] ?? '');
            $key = (string)($row['translation_key'] ?? '');

            if ($text === '' || $key === '') continue;

            $safeFallback = str_replace("'", "\\'", $text);
            $replacement = "<?php echo ec_h(ec_t('{$key}','{$safeFallback}')); ?>";

            // Safe replacements: only plain visible HTML contexts and basic labels.
            $patterns = [
                '>' . $text . '<' => '>' . $replacement . '<',
                $text . '</th>' => $replacement . '</th>',
                $text . '</label>' => $replacement . '</label>',
                $text . '</button>' => $replacement . '</button>',
                $text . '</a>' => $replacement . '</a>',
                $text . '</h1>' => $replacement . '</h1>',
                $text . '</h2>' => $replacement . '</h2>',
                $text . '</h3>' => $replacement . '</h3>',
                $text . '</h4>' => $replacement . '</h4>',
                $text . '</option>' => $replacement . '</option>',
            ];

            foreach ($patterns as $from => $to) {
                $before = $content;
                $content = str_replace($from, $to, $content);
                if ($content !== $before) {
                    $changed++;
                }
            }
        }

        if ($changed > 0) {
            file_put_contents($full, $content);
        }

        return [
            'ok' => true,
            'message' => "Applied {$changed} replacement group(s). Backup: {$backupDir}",
        ];
    }

    public function index()
    {
        $this->requireSuperAdmin();

        $files = $this->candidateFiles();
        $file = trim((string)($_GET['file'] ?? ''));
        $suggestions = $file !== '' ? $this->buildSuggestions($file) : [];

        ob_start();
        require BASE_PATH . '/app/views/admin/dictionary_replace/index.php';
        $content = ob_get_clean();

        require BASE_PATH . '/app/views/layouts/admin_layout.php';
    }

    public function apply()
    {
        $this->requireSuperAdmin();

        $file = trim((string)($_POST['file'] ?? ''));
        $rows = $_POST['rows'] ?? [];

        $selected = [];
        foreach ($rows as $row) {
            if (!empty($row['selected'])) {
                $selected[] = $row;
            }
        }

        if (!$selected) {
            $_SESSION['flash_error'] = 'No replacements selected.';
            header("Location: /easychair/admin/dictionary-replace?file=" . urlencode($file));
            exit;
        }

        $result = $this->applySuggestions($file, $selected);

        if ($result['ok']) {
            $_SESSION['flash_success'] = $result['message'];
        } else {
            $_SESSION['flash_error'] = $result['message'];
        }

        header("Location: /easychair/admin/dictionary-replace?file=" . urlencode($file));
        exit;
    }
}
