<?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 AdminWorkflowTenantController 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 defaultWorkflow(): array {
        return [
          'stages'=>[
            ['key'=>'submission','label_en'=>'Submission','label_ar'=>'الاستلام'],
            ['key'=>'review','label_en'=>'Review','label_ar'=>'التحكيم'],
            ['key'=>'decision','label_en'=>'Decision','label_ar'=>'القرار'],
            ['key'=>'production','label_en'=>'Production','label_ar'=>'الإنتاج'],
            ['key'=>'copyediting','label_en'=>'Copyediting','label_ar'=>'التحرير'],
            ['key'=>'publishing','label_en'=>'Publishing','label_ar'=>'النشر'],
          ],
          'defaults'=>[
            'min_reviewers'=>2,
            'max_reviewers'=>3,
            'allow_second_round'=>1
          ]
        ];
    }

    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_value FROM org_settings WHERE org_id=:o AND setting_key='workflow_json' LIMIT 1");
        $st->execute([':o'=>$orgId]);
        $json=(string)($st->fetchColumn() ?: '');

        $wf = $this->defaultWorkflow();
        if($json!==''){
            $arr=json_decode($json,true);
            if(is_array($arr)){
                $wf = array_replace_recursive($wf,$arr);
            }
        }

        $this->view('admin/workflow/index', [
          'wf'=>$wf,
        ]);
    }
}
