<?php
namespace App\Controllers;

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

use App\Core\Database;

class AdminDictionaryController
{
    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("Only super admin can manage dictionary.");
        }
    }

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

        $q = trim((string)($_GET['q'] ?? ''));
        $group = trim((string)($_GET['group'] ?? ''));

        $where = "WHERE 1=1";
        $params = [];

        if ($q !== '') {
            $where .= " AND (translation_key LIKE ? OR text_en LIKE ? OR text_ar LIKE ?)";
            $like = '%' . $q . '%';
            array_push($params, $like, $like, $like);
        }

        if ($group !== '') {
            $where .= " AND group_key=?";
            $params[] = $group;
        }

        $stmt = $this->db()->prepare("
            SELECT *
            FROM dictionary_translations
            {$where}
            ORDER BY group_key, translation_key
            LIMIT 700
        ");
        $stmt->execute($params);
        $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        $groups = $this->db()->query("
            SELECT DISTINCT group_key
            FROM dictionary_translations
            WHERE group_key IS NOT NULL AND group_key <> ''
            ORDER BY group_key
        ")->fetchAll(\PDO::FETCH_COLUMN);

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

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

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

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

        foreach ($rows as $id => $r) {
            $stmt = $this->db()->prepare("
                UPDATE dictionary_translations
                SET text_en=?,
                    text_ar=?,
                    group_key=?,
                    description=?,
                    is_active=?,
                    updated_by=?,
                    updated_at=NOW()
                WHERE id=?
            ");
            $stmt->execute([
                (string)($r['text_en'] ?? ''),
                (string)($r['text_ar'] ?? ''),
                trim((string)($r['group_key'] ?? '')),
                trim((string)($r['description'] ?? '')),
                !empty($r['is_active']) ? 1 : 0,
                (int)$_SESSION['user_id'],
                (int)$id
            ]);
        }

        $_SESSION['flash_success'] = t('dictionary.saved', 'Dictionary saved successfully.');
        header("Location: /easychair/admin/dictionary?saved=1");
        exit;
    }

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

        $key = strtolower(trim((string)($_POST['translation_key'] ?? '')));
        $key = preg_replace('/[^a-z0-9_.-]+/', '_', $key);
        $key = trim($key, '._-');

        if ($key === '') {
            $_SESSION['flash_error'] = 'Translation key is required.';
            header("Location: /easychair/admin/dictionary");
            exit;
        }

        $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=VALUES(text_en),
                text_ar=VALUES(text_ar),
                description=VALUES(description),
                is_active=1,
                updated_by=VALUES(updated_by),
                updated_at=NOW()
        ");
        $stmt->execute([
            $key,
            trim((string)($_POST['group_key'] ?? 'custom')),
            (string)($_POST['text_en'] ?? ''),
            (string)($_POST['text_ar'] ?? ''),
            trim((string)($_POST['description'] ?? '')),
            (int)$_SESSION['user_id']
        ]);

        $_SESSION['flash_success'] = 'Dictionary key saved.';
        header("Location: /easychair/admin/dictionary?q=" . urlencode($key));
        exit;
    }

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

        $stmt = $this->db()->prepare("DELETE FROM dictionary_translations WHERE id=?");
        $stmt->execute([(int)($_GET['id'] ?? 0)]);

        $_SESSION['flash_success'] = 'Dictionary key deleted.';
        header("Location: /easychair/admin/dictionary?deleted=1");
        exit;
    }
}
