<?php
declare(strict_types=1);
namespace App\Controllers;

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

final class AdminCertificatesTenantController extends Controller
{
  public function index(): void {
    require_admin_or_chair_tenant();
    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(PDO::FETCH_ASSOC)?:[];
    $confId=(int)($_GET['conference_id'] ?? ($confs[0]['id'] ?? 0));

    // rules table optional: certificate_rules
    $rules=[];
    $st=$db->prepare("SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='certificate_rules'");
    $st->execute();
    $has=((int)$st->fetchColumn()>0);
    if($has && $confId>0){
      $st=$db->prepare("SELECT * FROM certificate_rules r JOIN conferences c ON c.id=r.conference_id WHERE c.org_id=:o AND r.conference_id=:c ORDER BY r.id DESC");
      $st->execute([':o'=>$orgId,':c'=>$confId]);
      $rules=$st->fetchAll(PDO::FETCH_ASSOC)?:[];
    }

    $this->view('admin/certificates/index', compact('confs','confId','rules','has'));
  }
}
