<?php
declare(strict_types=1);

namespace App\Controllers;

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

use App\Core\Controller;
use App\Core\Database;
use PDO;

final class AdminSettingsTenantController extends Controller
{
    private function ensureTable(PDO $db): void {
        $st=$db->prepare("SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='org_settings'");
        $st->execute();
        if((int)$st->fetchColumn()>0) return;

        $db->exec("
          CREATE TABLE IF NOT EXISTS org_settings(
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            org_id BIGINT UNSIGNED NOT NULL,
            setting_key VARCHAR(120) NOT NULL,
            setting_value LONGTEXT NULL,
            created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY(id),
            UNIQUE KEY uk_org_key(org_id,setting_key),
            KEY idx_org(org_id)
          ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
    }

    public function index(): void
    {
        require_admin_or_chair_tenant();
        require_org_context();

        $db=Database::getInstance();
        $orgId=(int)current_org_id();
        $this->ensureTable($db);

        $st=$db->prepare("SELECT setting_key, setting_value FROM org_settings WHERE org_id=:o");
        $st->execute([':o'=>$orgId]);
        $rows=$st->fetchAll(PDO::FETCH_ASSOC)?:[];

        $settings=[];
        foreach($rows as $r){
            $settings[(string)$r['setting_key']] = (string)($r['setting_value'] ?? '');
        }

        // defaults
        $settings += [
          'default_lang' => 'ar',
          'brand_name_en' => 'EasyChair Portal',
          'brand_name_ar' => 'بوابة المؤتمرات',
          'smtp_enabled' => '1',
          'smtp_from_email' => 'no-reply@jpu.edu.jo',
          'smtp_from_name_en' => 'Conference Portal',
          'smtp_from_name_ar' => 'بوابة المؤتمرات',
        ];

        $this->view('admin/settings/index', compact('settings'));
    }
}
