<?php
declare(strict_types=1);

namespace App\Controllers;

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

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

final class AdminDecisionBoardStableController extends Controller
{
    private function cols($db, string $t): array {
        $st=$db->prepare("SELECT column_name, column_type FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name=:t");
        $st->execute([':t'=>$t]);
        $rows=$st->fetchAll()?:[];
        $m=[];
        foreach($rows as $r){ $m[(string)$r['column_name']] = (string)($r['column_type']??''); }
        return $m;
    }
    private function tableExists($db,string $t):bool{
        $st=$db->prepare("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name=:t");
        $st->execute([':t'=>$t]); return (int)$st->fetchColumn()>0;
    }
    private function normalizeDecision(?string $colType, string $val): string {
        $val=trim($val);
        $map=['accept'=>'accepted','accepted'=>'accepted','reject'=>'rejected','rejected'=>'rejected','minor'=>'minor_revision','major'=>'major_revision','revision'=>'revision','pending'=>'pending'];
        $v=$map[strtolower($val)] ?? strtolower($val);
        if($colType && str_starts_with($colType,"enum(")){
            preg_match_all("/'([^']+)'/",$colType,$m);
            $allowed=$m[1]??[];
            if($allowed && in_array($v,$allowed,true)) return $v;
            if($allowed) return (string)$allowed[0];
        }
        return $v===''?'pending':$v;
    }

    public function decide(): void
    {
        require_admin_area();
        $db=Database::getInstance();

        if(($_SERVER['REQUEST_METHOD']??'GET')!=='POST'){ http_response_code(405); return; }

        $submissionId=(int)($_POST['submission_id']??$_POST['id']??0);
        $decisionRaw=(string)($_POST['decision']??'');
        $notes=trim((string)($_POST['chair_comments']??$_POST['notes']??''));

        if($submissionId<=0){
            if(function_exists('flash_set')) flash_set('danger','Missing submission_id');
            header('Location: '.base_path('admin/decision-board')); exit;
        }

        if(!$this->tableExists($db,'decisions')){
            $db->exec("
              CREATE TABLE IF NOT EXISTS decisions (
                id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
                submission_id BIGINT UNSIGNED NOT NULL,
                decision VARCHAR(40) NOT NULL,
                chair_comments LONGTEXT NULL,
                decided_by BIGINT UNSIGNED NULL,
                decided_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
                created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                PRIMARY KEY(id),
                KEY idx_sub (submission_id)
              ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
            ");
        }

        $dc=$this->cols($db,'decisions');
        $decision=$this->normalizeDecision($dc['decision']??null,$decisionRaw);
        $uid=function_exists('auth_id')?(int)auth_id():null;

        $st=$db->prepare("SELECT id FROM decisions WHERE submission_id=:sid ORDER BY id DESC LIMIT 1");
        $st->execute([':sid'=>$submissionId]);
        $did=(int)($st->fetchColumn()?:0);

        if($did>0){
            $set=[]; $p=[':id'=>$did];
            if(isset($dc['decision'])){ $set[]="decision=:d"; $p[':d']=$decision; }
            if(isset($dc['chair_comments'])){ $set[]="chair_comments=:c"; $p[':c']=($notes!==''?$notes:null); }
            if(isset($dc['decided_by'])){ $set[]="decided_by=:u"; $p[':u']=$uid; }
            if(isset($dc['decided_at'])){ $set[]="decided_at=NOW()"; }
            if($set){ $db->prepare("UPDATE decisions SET ".implode(',',$set)." WHERE id=:id")->execute($p); }
        } else {
            $cols=[]; $vals=[]; $p=[];
            if(isset($dc['submission_id'])){ $cols[]='submission_id'; $vals[]=':sid'; $p[':sid']=$submissionId; }
            if(isset($dc['decision'])){ $cols[]='decision'; $vals[]=':d'; $p[':d']=$decision; }
            if(isset($dc['chair_comments'])){ $cols[]='chair_comments'; $vals[]=':c'; $p[':c']=($notes!==''?$notes:null); }
            if(isset($dc['decided_by'])){ $cols[]='decided_by'; $vals[]=':u'; $p[':u']=$uid; }
            if(isset($dc['decided_at'])){ $cols[]='decided_at'; $vals[]='NOW()'; }
            $db->prepare("INSERT INTO decisions(".implode(',',$cols).") VALUES(".implode(',',$vals).")")->execute($p);
        }

        if(function_exists('flash_set')) flash_set('success','Decision saved');
        header('Location: '.base_path('admin/decision-board')); exit;
    }
}
