<?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 AdminJobsTenantController extends Controller
{
    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;
    }

    public function index(): void
    {
        require_org_admin(); // org_admin أو superadmin فقط
        $db = Database::getInstance();
        $orgId = (int) current_org_id();

        // Detect table
        $table = null;
        foreach(['jobs','job_queue','jobs_queue','background_jobs','cron_jobs'] as $t){
            if($this->tableExists($db,$t)){ $table=$t; break; }
        }
        if(!$table){
            throw new \RuntimeException("Jobs table not found");
        }

        // Minimal safe columns: show whole row as assoc
        $st = $db->prepare("SELECT * FROM {$table} WHERE org_id=:o ORDER BY id DESC LIMIT 300");
        $st->execute([':o'=>$orgId]);
        $rows = $st->fetchAll() ?: [];

        $this->view('admin/jobs_tenant/index', ['rows'=>$rows,'table'=>$table]);
    }
}
