<?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;

/**
 * Pack203.4A: Stabilized + tenant-isolated workflow board.
 * Shows submissions for current org only.
 */
final class AdminSubmissionsWorkflowController extends Controller
{
    private function hasCol($db, string $table, string $col): 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'=>$table, ':c'=>$col]);
        return (int)$st->fetchColumn() > 0;
    }

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

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

        // Decide which status column exists
        $statusCol = $this->hasCol($db,'submissions','status') ? 'status' : null;

        // Basic workflow columns (safe defaults)
        $sql = "
          SELECT s.*, c.title_en AS conf_title_en, c.title_ar AS conf_title_ar
          FROM submissions s
          JOIN conferences c ON c.id=s.conference_id
          WHERE c.org_id=:org_id
          ORDER BY s.id DESC
          LIMIT 300
        ";
        $st = $db->prepare($sql);
        $st->execute([':org_id'=>$orgId]);
        $rows = $st->fetchAll() ?: [];

        // If you have workflow stages column, keep it; otherwise view can show status as fallback
        $this->view('admin/submissions_workflow/index', [
            'rows' => $rows,
            'statusCol' => $statusCol,
        ]);
    }
}
