<?php
namespace App\Controllers;

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

use App\Core\Database;

class AdminDictionaryScanController
{
    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 h($v): string
    {
        return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
    }

    private function dictionaryTexts(): array
    {
        $stmt = $this->db()->query("
            SELECT translation_key, text_en, text_ar
            FROM dictionary_translations
        ");

        $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        $known = [];

        foreach ($rows as $r) {
            foreach (['translation_key', 'text_en', 'text_ar'] as $col) {
                $v = trim((string)($r[$col] ?? ''));
                if ($v !== '') {
                    $known[mb_strtolower($v)] = true;
                }
            }
        }

        return $known;
    }

    private function isCandidate(string $text): bool
    {
        $text = trim($text);

        if ($text === '') return false;
        if (mb_strlen($text) < 3) return false;
        if (mb_strlen($text) > 180) return false;

        $skip = [
            'UTF-8', 'POST', 'GET', 'PDO', 'NULL', 'true', 'false',
            'container', 'row', 'col-md', 'form-control', 'btn',
            'card', 'table', 'badge', 'alert', 'selected', 'checked',
            'easychair', 'localhost', 'http', 'https', 'font-awesome',
            'Cairo', 'bootstrap', 'stylesheet', 'script', 'style'
        ];

        foreach ($skip as $s) {
            if (stripos($text, $s) !== false && mb_strlen($text) < 35) {
                return false;
            }
        }

        $hasArabic = preg_match('/\p{Arabic}/u', $text);
        $hasLetters = preg_match('/[A-Za-z]{3,}/', $text);

        if (!$hasArabic && !$hasLetters) return false;

        if (preg_match('/^[a-z0-9_\-\/\.\?\=\&]+$/i', $text)) return false;

        return true;
    }

    private function makeKey(string $text, string $group): string
    {
        $base = $text;

        $base = preg_replace('/[^\p{Arabic}A-Za-z0-9 ]+/u', ' ', $base);
        $base = trim($base);

        if (preg_match('/\p{Arabic}/u', $base)) {
            $base = 'label_' . substr(md5($text), 0, 10);
        } else {
            $base = strtolower($base);
            $base = preg_replace('/[^a-z0-9]+/', '_', $base);
            $base = trim($base, '_');
            $base = substr($base, 0, 80);
            if ($base === '') {
                $base = 'label_' . substr(md5($text), 0, 10);
            }
        }

        return $group . '.' . $base;
    }

    private function scanFiles(): array
    {
        $base = BASE_PATH;

        $roots = [
            $base . '/app/views',
            $base . '/app/controllers',
        ];

        $known = $this->dictionaryTexts();
        $found = [];

        foreach ($roots as $root) {
            if (!is_dir($root)) continue;

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

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

                $path = $file->getPathname();

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

                $rel = str_replace($base . '/', '', $path);
                $content = @file_get_contents($path);
                if ($content === false) continue;

                $matches = [];

                // Text between HTML tags: >Text<
                if (preg_match_all('/>([^<>]{3,180})</u', $content, $m)) {
                    foreach ($m[1] as $txt) {
                        $matches[] = $txt;
                    }
                }

                // Quoted Arabic strings or title-like English strings.
                if (preg_match_all('/[\'"]([^\'"]{3,180})[\'"]/u', $content, $m)) {
                    foreach ($m[1] as $txt) {
                        if (preg_match('/\p{Arabic}/u', $txt) || preg_match('/\b[A-Z][A-Za-z]+(?:\s+[A-Z][A-Za-z]+){0,5}\b/', $txt)) {
                            $matches[] = $txt;
                        }
                    }
                }

                foreach ($matches as $txt) {
                    $txt = trim(html_entity_decode(strip_tags($txt), ENT_QUOTES, 'UTF-8'));
                    $txt = preg_replace('/\s+/u', ' ', $txt);

                    if (!$this->isCandidate($txt)) continue;

                    $lower = mb_strtolower($txt);

                    if (isset($known[$lower])) continue;

                    $group = 'custom';
                    if (str_contains($rel, '/author/')) $group = 'author';
                    elseif (str_contains($rel, '/reviewer/')) $group = 'reviewer';
                    elseif (str_contains($rel, '/admin/')) $group = 'admin';
                    elseif (str_contains($rel, 'email')) $group = 'email';
                    elseif (str_contains($rel, 'certificate')) $group = 'certificates';
                    elseif (str_contains($rel, 'production')) $group = 'production';
                    elseif (str_contains($rel, 'issue')) $group = 'issues';
                    elseif (str_contains($rel, 'profile')) $group = 'profile';

                    $key = $this->makeKey($txt, $group);

                    $found[$key] = [
                        'suggested_key' => $key,
                        'group_key' => $group,
                        'text' => $txt,
                        'file_path' => $rel,
                    ];
                }
            }
        }

        usort($found, function ($a, $b) {
            return strcmp($a['group_key'] . $a['text'], $b['group_key'] . $b['text']);
        });

        return array_slice($found, 0, 500);
    }

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

        $suggestions = $this->scanFiles();

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

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

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

        $rows = $_POST['rows'] ?? [];
        $created = 0;

        foreach ($rows as $r) {
            if (empty($r['selected'])) {
                continue;
            }

            $key = trim((string)($r['translation_key'] ?? ''));
            $group = trim((string)($r['group_key'] ?? 'custom'));
            $text = trim((string)($r['text'] ?? ''));

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

            $hasArabic = preg_match('/\p{Arabic}/u', $text);

            $textAr = $hasArabic ? $text : '';
            $textEn = $hasArabic ? '' : $text;

            if (!empty($r['text_ar'])) {
                $textAr = trim((string)$r['text_ar']);
            }

            if (!empty($r['text_en'])) {
                $textEn = trim((string)$r['text_en']);
            }

            $stmt = $this->db()->prepare("
                INSERT INTO dictionary_translations
                (translation_key, group_key, text_en, text_ar, description, is_active, updated_by)
                VALUES (?, ?, ?, ?, ?, 1, ?)
                ON DUPLICATE KEY UPDATE
                    group_key=VALUES(group_key),
                    text_en=IF(VALUES(text_en) <> '', VALUES(text_en), text_en),
                    text_ar=IF(VALUES(text_ar) <> '', VALUES(text_ar), text_ar),
                    description=VALUES(description),
                    is_active=1,
                    updated_by=VALUES(updated_by),
                    updated_at=NOW()
            ");
            $stmt->execute([
                $key,
                $group,
                $textEn,
                $textAr,
                'Auto-suggested from dictionary scanner',
                (int)$_SESSION['user_id'],
            ]);

            $created++;
        }

        $_SESSION['flash_success'] = "Dictionary suggestions saved: {$created}";
        header("Location: /easychair/admin/dictionary-scan");
        exit;
    }
}
