<?php
declare(strict_types=1);

namespace App\Controllers;

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

final class AdminWorkflowActionsTenantController 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();

        $min=(int)($_POST['min_reviewers'] ?? 2);
        $max=(int)($_POST['max_reviewers'] ?? 3);
        if($min<1) $min=1;
        if($max<$min) $max=$min;

        $allow2 = ((int)($_POST['allow_second_round'] ?? 0)) ? 1 : 0;

        $keys = (array)($_POST['stage_key'] ?? []);
        $en   = (array)($_POST['stage_en']  ?? []);
        $ar   = (array)($_POST['stage_ar']  ?? []);

        $stages=[];
        for($i=0;$i<count($keys);$i++){
            $k=trim((string)($keys[$i] ?? ''));
            $le=trim((string)($en[$i] ?? ''));
            $la=trim((string)($ar[$i] ?? ''));
            if($k==='' || $le==='') continue;
            $stages[]=['key'=>$k,'label_en'=>$le,'label_ar'=>$la];
        }

        if(empty($stages)){
            if(function_exists('flash_set')) flash_set('danger','At least one stage required');
            header('Location: '.base_path('admin/workflow')); exit;
        }

        $wf=[
          'stages'=>$stages,
          'defaults'=>[
            'min_reviewers'=>$min,
            'max_reviewers'=>$max,
            'allow_second_round'=>$allow2
          ]
        ];

        $json=json_encode($wf, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);

        $st=$db->prepare("
          INSERT INTO org_settings(org_id,setting_key,setting_value)
          VALUES(:o,'workflow_json',:v)
          ON DUPLICATE KEY UPDATE setting_value=VALUES(setting_value)
        ");
        $st->execute([':o'=>$orgId,':v'=>$json]);

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