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

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

final class AdminCertificatesActionsTenantController extends Controller
{
  private function guard(): array {
    require_admin_or_chair_tenant();
    require_org_context();
    if(($_SERVER['REQUEST_METHOD']??'GET')!=='POST'){ http_response_code(405); exit; }
    $db=Database::getInstance();
    $orgId=(int)current_org_id();
    return [$db,$orgId];
  }

  public function saveRule(): void {
    [$db,$orgId]=$this->guard();

    // ensure table exists
    $st=$db->prepare("SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='certificate_rules'");
    $st->execute();
    if((int)$st->fetchColumn()<=0){
      $db->exec("
        CREATE TABLE IF NOT EXISTS certificate_rules(
          id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
          org_id BIGINT UNSIGNED DEFAULT NULL,
          conference_id BIGINT UNSIGNED NOT NULL,
          role_code VARCHAR(50) NOT NULL,
          min_reviews INT NOT NULL DEFAULT 0,
          min_attendance INT NOT NULL DEFAULT 0,
          is_active TINYINT(1) NOT NULL DEFAULT 1,
          created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
          updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
          PRIMARY KEY(id),
          KEY idx_org_id(org_id),
          KEY idx_conf(conference_id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
      ");
    }

    $confId=(int)($_POST['conference_id'] ?? 0);
    $st=$db->prepare("SELECT id FROM conferences WHERE id=:c AND org_id=:o LIMIT 1");
    $st->execute([':c'=>$confId,':o'=>$orgId]);
    if(!(int)$st->fetchColumn()){ http_response_code(404); echo "Conference not found"; exit; }

    $role=trim((string)($_POST['role_code'] ?? 'reviewer'));
    $minR=(int)($_POST['min_reviews'] ?? 0);
    $minA=(int)($_POST['min_attendance'] ?? 0);

    $db->prepare("
      INSERT INTO certificate_rules(org_id,conference_id,role_code,min_reviews,min_attendance,is_active)
      VALUES(:o,:c,:r,:mr,:ma,1)
    ")->execute([':o'=>$orgId,':c'=>$confId,':r'=>$role,':mr'=>$minR,':ma'=>$minA]);

    if(function_exists('flash_set')) flash_set('success','Saved');
    header('Location: '.base_path('admin/certificates?conference_id='.$confId)); exit;
  }
}
