<?php
namespace App\Controllers;

use App\Core\Database;

class AdminCertificateController
{
    protected function db()
    {
        return Database::getInstance();
    }

    private function startSession(): void
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }
    }

    private function role(): string
    {
        return (string)($_SESSION['conference_role'] ?? $_SESSION['role'] ?? $_SESSION['user_role'] ?? '');
    }

    private function requireAccess(): void
    {
        $this->startSession();

        if (empty($_SESSION['user_id'])) {
            header("Location: /easychair/login");
            exit;
        }

        if (empty($_SESSION['conference_id'])) {
            header("Location: /easychair/select-conference");
            exit;
        }

        if (!in_array($this->role(), ['super_admin','org_admin','admin','organizer','conference_chair','track_chair'], true)) {
            http_response_code(403);
            exit(function_exists('t') ? t('msg.access_denied', 'Access denied.') : 'Access denied.');
        }
    }

    private function conference(): array
    {
        $stmt = $this->db()->prepare("SELECT * FROM conferences WHERE id=? LIMIT 1");
        $stmt->execute([(int)$_SESSION['conference_id']]);
        $c = $stmt->fetch(\PDO::FETCH_ASSOC);

        if (!$c) {
            exit("Conference not found.");
        }

        if ($this->role() !== 'super_admin' && (int)$c['org_id'] !== (int)($_SESSION['org_id'] ?? 0)) {
            http_response_code(403);
            exit(function_exists('t') ? t('msg.access_denied', 'Access denied.') : 'Access denied.');
        }

        return $c;
    }

    public function index()
    {
        $this->requireAccess();
        $conference = $this->conference();

        $db = $this->db();

        $certificates = [];
        try {
            $stmt = $db->prepare("
                SELECT cc.*,
                       u.email,
                       u.first_name,
                       u.last_name,
                       s.submission_no,
                       s.title,
                       s.title_ar
                FROM conference_certificates cc
                LEFT JOIN users u ON u.id = cc.user_id
                LEFT JOIN submissions s ON s.id = cc.submission_id
                WHERE cc.conference_id = ?
                  AND cc.org_id = ?
                ORDER BY cc.id DESC
                LIMIT 300
            ");
            $stmt->execute([(int)$conference['id'], (int)$conference['org_id']]);
            $certificates = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        } catch (\Throwable $e) {
            $certificates = [];
        }

        $eligible = [];
        try {
            $stmt = $db->prepare("
                SELECT
                    s.id AS submission_id,
                    s.submission_no,
                    s.title,
                    s.title_ar,
                    s.author_id AS user_id,
                    u.email,
                    u.first_name,
                    u.last_name,
                    'author' AS certificate_type
                FROM submissions s
                LEFT JOIN users u ON u.id=s.author_id
                WHERE s.conference_id=?
                  AND s.org_id=?
                  AND s.status IN ('accepted','camera_ready','published')
                ORDER BY s.id DESC
                LIMIT 200
            ");
            $stmt->execute([(int)$conference['id'], (int)$conference['org_id']]);
            $eligible = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        } catch (\Throwable $e) {
            $eligible = [];
        }

        ob_start();
        require BASE_PATH . '/app/views/admin/certificates/index.php';
        $content = ob_get_clean();

        require BASE_PATH . '/app/views/layouts/admin_layout.php';
    }

    public function generate()
    {
        $this->requireAccess();
        $conference = $this->conference();

        $submissionId = (int)($_POST['submission_id'] ?? 0);
        $userId = (int)($_POST['user_id'] ?? 0);
        $type = trim((string)($_POST['certificate_type'] ?? 'author'));

        if (!in_array($type, ['author','reviewer','chair','tpc','participant','committee'], true)) {
            $type = 'author';
        }

        if ($userId <= 0) {
            $_SESSION['flash_error'] = 'User is required.';
            header("Location: /easychair/admin/certificates");
            exit;
        }

        $certificateNo = 'CERT-' . (int)$conference['id'] . '-' . date('YmdHis') . '-' . $userId;

        try {
            $stmt = $this->db()->prepare("
                INSERT INTO conference_certificates
                (org_id, conference_id, submission_id, user_id, certificate_type, certificate_no, status, issued_by, issued_at, created_at)
                VALUES (?, ?, NULLIF(?,0), ?, ?, ?, 'issued', ?, NOW(), NOW())
            ");
            $stmt->execute([
                (int)$conference['org_id'],
                (int)$conference['id'],
                $submissionId,
                $userId,
                $type,
                $certificateNo,
                (int)$_SESSION['user_id']
            ]);

            $_SESSION['flash_success'] = 'Certificate generated.';
        } catch (\Throwable $e) {
            $_SESSION['flash_error'] = 'Could not generate certificate: ' . $e->getMessage();
        }

        header("Location: /easychair/admin/certificates");
        exit;
    }
}
