<?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 AdminSettingsActionsTenantController 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
        ");
    }

    private function guard(): array {
        require_admin_or_chair_tenant();
        require_org_context();
        if(($_SERVER['REQUEST_METHOD']??'GET')!=='POST'){ http_response_code(405); exit; }
        $db=Database::getInstance();
        $orgId=(int)current_org_id();
        $this->ensureTable($db);
        return [$db,$orgId];
    }

    public function save(): void
    {
        [$db,$orgId]=$this->guard();

        $keys=[
          'default_lang',
          'brand_name_en','brand_name_ar',
          'smtp_enabled',
          'smtp_from_email','smtp_from_name_en','smtp_from_name_ar',
        ];

        foreach($keys as $k){
            $v=(string)($_POST[$k] ?? '');
            $st=$db->prepare("
              INSERT INTO org_settings(org_id,setting_key,setting_value)
              VALUES(:o,:k,:v)
              ON DUPLICATE KEY UPDATE setting_value=VALUES(setting_value)
            ");
            $st->execute([':o'=>$orgId,':k'=>$k,':v'=>$v]);
        }

        if(function_exists('flash_set')) flash_set('success','Saved');
        header('Location: '.base_path('admin/settings')); exit;
    }
}
