<?php
declare(strict_types=1);

namespace App\Controllers;

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

final class AdminCertificatesRulesController extends Controller
{
    private function cid($db): int {
        $cid=function_exists('default_conference_id')?(int)default_conference_id():0;
        if($cid>0) return $cid;
        return (int)($db->query("SELECT id FROM conferences WHERE (is_active=1 OR is_active IS NULL) ORDER BY id DESC LIMIT 1")->fetchColumn() ?: 0);
    }

    public function index(): void
    {
        require_login();
        if(!can_admin() && !can_chair()){ http_response_code(403); echo "Forbidden"; return; }

        $db=Database::getInstance();
        $cid=$this->cid($db);

        // candidates: reviewers + committee members + anyone with attendance
        $users = $db->query("
          SELECT DISTINCT u.id,u.email,u.first_name,u.last_name,u.role_id
          FROM users u
          LEFT JOIN attendance_logs a ON a.user_id=u.id
          WHERE u.is_active=1
          ORDER BY u.id DESC
          LIMIT 500
        ")->fetchAll() ?: [];

        $logs = $db->query("SELECT * FROM certificate_logs ORDER BY id DESC LIMIT 200")->fetchAll() ?: [];

        $this->view('admin/certificates/rules', ['users'=>$users,'logs'=>$logs,'conference_id'=>$cid]);
    }

    public function generate(): void
    {
        require_login();
        if(!can_admin() && !can_chair()){ http_response_code(403); echo "Forbidden"; return; }
        csrf_check();

        $db=Database::getInstance();
        $cid=$this->cid($db);
        $uid=(int)($_POST['user_id']??0);
        $type=trim((string)($_POST['cert_type']??'attendance'));
        if(!in_array($type,['attendance','reviewer','tpc','chair','demo'],true)) $type='demo';

        $st=$db->prepare("SELECT email,first_name,last_name FROM users WHERE id=:id LIMIT 1");
        $st->execute([':id'=>$uid]);
        $u=$st->fetch();
        if(!$u){ header('Location: '.base_path('admin/certificates-rules')); exit; }

        $name=trim((string)$u['first_name'].' '.(string)$u['last_name']);
        if($name==='') $name=(string)$u['email'];

        // Rule checks (simple):
        $ok=true;
        if($type==='attendance'){
            $q=$db->prepare("SELECT COUNT(*) FROM attendance_logs WHERE conference_id=:c AND user_id=:u");
            $q->execute([':c'=>$cid,':u'=>$uid]);
            $ok=((int)$q->fetchColumn() > 0);
        }
        if($type==='reviewer'){
            // completed reviews count
            $q=$db->prepare("
              SELECT COUNT(*)
              FROM reviews r
              JOIN review_assignments ra ON ra.id = r.assignment_id
              JOIN submissions s ON s.id = ra.submission_id
              WHERE s.conference_id=:c AND ra.reviewer_id=:u
            ");
            try { $q->execute([':c'=>$cid,':u'=>$uid]); $ok=((int)$q->fetchColumn() > 0); }
            catch(\Throwable $e){ $ok=false; }
        }

        if(!$ok){
            if(session_status()!==PHP_SESSION_ACTIVE) session_start();
            $_SESSION['flash_error'] = 'Rule not satisfied for this certificate type.';
            header('Location: '.base_path('admin/certificates-rules')); exit;
        }

        $dir=BASE_PATH.'/public/assets/uploads/certificates/'.$cid;
        if(!is_dir($dir)) @mkdir($dir,0775,true);
        $fname='cert_'.$type.'_'.$uid.'_'.date('Ymd_His').'.pdf';
        $path=$dir.'/'.$fname;
        $rel='assets/uploads/certificates/'.$cid.'/'.$fname;

        $html="<h1>Certificate</h1><p><b>".htmlspecialchars($name)."</b></p><p>Type: ".$type."</p><p>Conference: ".$cid."</p><p>Date: ".date('Y-m-d')."</p>";
        file_put_contents($path,$html);

        $db->prepare("INSERT INTO certificate_logs(user_id,conference_id,cert_type,file_path,status) VALUES(:u,:c,:t,:p,'generated')")
           ->execute([':u'=>$uid,':c'=>$cid,':t'=>$type,':p'=>$rel]);

        if(session_status()!==PHP_SESSION_ACTIVE) session_start();
        $_SESSION['flash_success'] = 'Certificate generated.';
        header('Location: '.base_path('admin/certificates-rules')); exit;
    }
}
