<?php
declare(strict_types=1);

namespace App\Controllers;

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

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

final class AdminDecisionBoardTenantController extends Controller
{
    private function colExists($db,string $t,string $c): bool {
        $st=$db->prepare("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name=:t AND column_name=:c");
        $st->execute([':t'=>$t,':c'=>$c]);
        return (int)$st->fetchColumn()>0;
    }

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

        $db=Database::getInstance();
        $orgId=(int)current_org_id();

        $st=$db->prepare("SELECT id,title_en,title_ar FROM conferences WHERE org_id=:o ORDER BY id DESC");
        $st->execute([':o'=>$orgId]);
        $confs=$st->fetchAll()?:[];
        $confId=(int)($_GET['conference_id'] ?? ($confs[0]['id'] ?? 0));
        if($confId>0) require_conference_of_org($confId);

        // list submissions for decision
        $st=$db->prepare("
          SELECT s.id, s.title_en, s.title_ar, s.status
          FROM submissions s
          JOIN conferences c ON c.id=s.conference_id
          WHERE c.org_id=:o AND s.conference_id=:c
          ORDER BY s.id DESC
          LIMIT 400
        ");
        $st->execute([':o'=>$orgId,':c'=>$confId]);
        $subs=$st->fetchAll()?:[];

        $this->view('admin/decision_board_tenant/index', compact('confs','confId','subs'));
    }

    public function decide(): void
    {
        require_admin_or_chair();
        require_org_context();
        if(($_SERVER['REQUEST_METHOD']??'GET')!=='POST'){ http_response_code(405); return; }

        $db=Database::getInstance();
        $orgId=(int)current_org_id();

        $confId=(int)($_POST['conference_id']??0);
        $sid=(int)($_POST['submission_id']??0);
        $decision=trim((string)($_POST['decision']??''));
        $notes=trim((string)($_POST['notes']??''));

        require_conference_of_org($confId);

        // validate submission belongs to org
        $st=$db->prepare("
          SELECT s.id
          FROM submissions s JOIN conferences c ON c.id=s.conference_id
          WHERE s.id=:sid AND s.conference_id=:cid AND c.org_id=:o
          LIMIT 1
        ");
        $st->execute([':sid'=>$sid,':cid'=>$confId,':o'=>$orgId]);
        if(!(int)$st->fetchColumn()){
          http_response_code(400); echo "Invalid submission"; exit;
        }

        // insert decision (schema-aware)
        $hasComments = $this->colExists($db,'decisions','chair_comments') || $this->colExists($db,'decisions','comments') || $this->colExists($db,'decisions','notes');
        $commentCol = $this->colExists($db,'decisions','chair_comments') ? 'chair_comments' : ($this->colExists($db,'decisions','comments') ? 'comments' : ($this->colExists($db,'decisions','notes') ? 'notes' : null));
        $hasMadeBy = $this->colExists($db,'decisions','made_by');
        $hasAt = $this->colExists($db,'decisions','created_at');

        $cols = "submission_id, decision";
        $vals = ":sid, :d";
        $params = [':sid'=>$sid, ':d'=>$decision];

        if($hasComments && $commentCol){
          $cols .= ", {$commentCol}";
          $vals .= ", :n";
          $params[':n']=$notes;
        }
        if($hasMadeBy){
          $cols .= ", made_by";
          $vals .= ", :mb";
          $params[':mb']=(int)(function_exists('auth_id')?auth_id():0);
        }
        if($hasAt){
          $cols .= ", created_at";
          $vals .= ", NOW()";
        }

        $db->prepare("INSERT INTO decisions ($cols) VALUES ($vals)")->execute($params);

        // update submission status if status col exists
        if($this->colExists($db,'submissions','status') && $decision!==''){
          $db->prepare("UPDATE submissions SET status=:s WHERE id=:id")->execute([':s'=>$decision,':id'=>$sid]);
        }

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