<?php
namespace App\Controllers;

require_once BASE_PATH . '/app/helpers/view_compat.php';

require_once BASE_PATH . '/app/helpers/permissions.php';

use App\Core\Database;

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

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

    private function role(): string
{
    $role =
        strtolower(
            trim(
                (string)(
                    $_SESSION['role']
                    ?? $_SESSION['user_role']
                    ?? ''
                )
            )
        );

    /*
     * Normalize all legacy variants
     */
    if (
        in_array(
            $role,
            [
                'superadmin',
                'super admin',
                'superadmin'
            ],
            true
        )
    ) {
        return 'superadmin';
    }

    return $role;
}

private function requireSuperAdmin()
{
    $role =
        strtolower(
            trim(
                (string)(
                    $_SESSION['role']
                    ?? $_SESSION['user_role']
                    ?? ''
                )
            )
        );

    if (
        !in_array(
            $role,
            [
                'superadmin',
                'superadmin',
                'super admin'
            ],
            true
        )
    ) {

        http_response_code(403);

        die('Access denied.');
    }
}
    private function requireAccess(): void
    {
        $this->startSession();

        if (empty($_SESSION['user_id'])) {
            $this->redirect("/easychair/login");
        }

        if (!in_array($this->role(), [
            'superadmin',
            'org_admin',
            'admin',
            'organizer',
            'conference_chair'
        ], true)) {
            http_response_code(403);
            exit("Access denied.");
        }

        if (empty($_SESSION['conference_id'])) {
            $this->redirect("/easychair/select-conference");
        }
    }

    private function tableExists(string $table): bool
    {
        try {
            $stmt = $this->db()->prepare("SHOW TABLES LIKE ?");
            $stmt->execute([$table]);
            return (bool)$stmt->fetchColumn();
        } catch (\Throwable $e) {
            return false;
        }
    }

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

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

        if (!ec_is_superadmin()) {
            if ((int)$conference['org_id'] !== (int)($_SESSION['org_id'] ?? 0)) {
                http_response_code(403);
                exit("Invalid organization conference access.");
            }
        }

        return $conference;
    }

    private function rows(string $sql, array $params = []): array
    {
        try {
            $stmt = $this->db()->prepare($sql);
            $stmt->execute($params);
            return $stmt->fetchAll(\PDO::FETCH_ASSOC) ?: [];
        } catch (\Throwable $e) {
            return [];
        }
    }

    private function one(string $sql, array $params = []): ?array
    {
        try {
            $stmt = $this->db()->prepare($sql);
            $stmt->execute($params);
            $row = $stmt->fetch(\PDO::FETCH_ASSOC);
            return $row ?: null;
        } catch (\Throwable $e) {
            return null;
        }
    }

   public function index()
{
    $this->startSession();

   // if (
   //     ec_is_superadmin()
    //) {

// PACK197 FIX: render index instead of force sections
// return $this->sections();
    //}
        $this->requireAccess();
// PACK197 FIX: render index instead of force sections
// return $this->sections();


        $conference = $this->conference();
        $cid = (int)$conference['id'];
        $orgId = (int)$conference['org_id'];

        $policy = $this->one("
            SELECT *
            FROM org_conference_policy
            WHERE org_id = ?
            LIMIT 1
        ", [$orgId]);

        $orgConferences = $this->rows("
            SELECT *
            FROM conferences
            WHERE org_id = ?
            ORDER BY id DESC
        ", [$orgId]);

        $blocks = $this->rows("
           SELECT *
    FROM conference_homepage_blocks
    WHERE conference_id = ?
    ORDER BY sort_order ASC, id DESC
", [$cid]);

        /*
        ---------------------------------------------------------
        HOMEPAGE SECTIONS GOVERNANCE
        ---------------------------------------------------------
        */

        $sections = $this->rows("
            SELECT *
            FROM conference_home_sections
            WHERE conference_id = ?
            ORDER BY
                sort_order ASC,
                id ASC
        ", [$cid]);

        $committees = $this->rows("
            SELECT *
            FROM conference_committees
            WHERE conference_id = ?
              AND (org_id = ? OR org_id IS NULL)
            ORDER BY committee_type ASC, sort_order ASC, id DESC
        ", [$cid, $orgId]);

        $templates = $this->rows("
            SELECT *
            FROM conference_email_templates
            WHERE conference_id = ?
              AND (org_id = ? OR org_id IS NULL)
            ORDER BY COALESCE(template_key,event_key) ASC
        ", [$cid, $orgId]);

        $logs = $this->rows("
            SELECT *
            FROM conference_import_logs
            WHERE conference_id = ?
              AND (org_id = ? OR org_id IS NULL)
            ORDER BY id DESC
            LIMIT 10
        ", [$cid, $orgId]);

        $sections = $sections ?? [];
        ob_start();
        require BASE_PATH . '/app/views/admin/conference_home/index.php';
        $content = ob_get_clean();

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

    public function setPolicy()
    {
        $this->requireAccess();

        if (!in_array($this->role(), ['superadmin','org_admin'], true)) {
            http_response_code(403);
            exit("Only superadmin or organization admin can set policy.");
        }

        $conference = $this->conference();
        $orgId = (int)$conference['org_id'];
        $conferenceId = (int)($_POST['conference_id'] ?? $conference['id']);

        $stmt = $this->db()->prepare("
            SELECT id
            FROM conferences
            WHERE id = ?
              AND org_id = ?
            LIMIT 1
        ");
        $stmt->execute([$conferenceId, $orgId]);

        if (!$stmt->fetchColumn()) {
            exit("Invalid conference for this organization.");
        }

        $stmt = $this->db()->prepare("
            INSERT INTO org_conference_policy (org_id, conference_id, policy_note, created_by)
            VALUES (?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE
                conference_id = VALUES(conference_id),
                policy_note = VALUES(policy_note),
                updated_at = NOW()
        ");
        $stmt->execute([
            $orgId,
            $conferenceId,
            trim($_POST['policy_note'] ?? 'Updated from smart home'),
            (int)$_SESSION['user_id']
        ]);

        $this->redirect("/easychair/admin/conference-home/sections");
    }

    public function storeBlock()
    {
        $this->requireAccess();

        $conference = $this->conference();
        $imagePath = null;

        if (!empty($_FILES['image']['name']) && is_uploaded_file($_FILES['image']['tmp_name'])) {
            $dir = BASE_PATH . '/public/storage/home/' . (int)$conference['id'];

            if (!is_dir($dir)) {
                mkdir($dir, 0775, true);
            }

            $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
            $ext = preg_replace('/[^a-z0-9]/', '', $ext);
            $file = 'block_' . time() . '_' . rand(1000,9999) . '.' . $ext;

            if (move_uploaded_file($_FILES['image']['tmp_name'], $dir . '/' . $file)) {
                $imagePath = 'home/' . (int)$conference['id'] . '/' . $file;
            }
        }

$stmt = $this->db()->prepare("
    INSERT INTO conference_homepage_blocks
    (
        conference_id,
        block_type,
        title_ar,
        title_en,
        body_ar,
        body_en,
        image_path,
        link_url,
        sort_order,
        is_active,
        block_key,
        org_id
    )
    VALUES
    (
        ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?
    )
");
       
 
$stmt->execute([

    (int)$conference['id'],

    (
        in_array(
            ($_POST['block_type'] ?? 'section_html'),
            [
                'hero_slide',
                'panel',
                'topic',
                'section_html',
                'important_date'
            ],
            true
        )
            ? $_POST['block_type']
            : 'section_html'
    ),

    trim($_POST['title_ar'] ?? ''),
    trim($_POST['title_en'] ?? ''),

    trim($_POST['body_ar'] ?? ''),
    trim($_POST['body_en'] ?? ''),

    $imagePath,

    trim($_POST['link_url'] ?? ''),

    (int)($_POST['sort_order'] ?? 1),

    'block_' . time(),

    (int)$conference['org_id']
]);

        $this->redirect("/easychair/admin/conference-home/sections");
    }

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

        
$stmt = $this->db()->prepare("
    UPDATE conference_homepage_blocks
    SET is_active = IF(is_active=1,0,1)
    WHERE id = ?
      AND conference_id = ?
");

$stmt->execute([
    (int)($_GET['id'] ?? 0),
    (int)$conference['id']
]);

        $this->redirect("/easychair/admin/conference-home/sections");
    }

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

$stmt = $this->db()->prepare("
    DELETE FROM conference_homepage_blocks
    WHERE id = ?
      AND conference_id = ?
");
   

$stmt->execute([
    (int)($_GET['id'] ?? 0),
    (int)$conference['id']
]);

        $this->redirect("/easychair/admin/conference-home/sections");
    }

    
    private function csvRows(string $file): array
    {
        $rows = [];

        if (($h = fopen($file, 'r')) === false) {
            return $rows;
        }

        $header = fgetcsv($h);

        if (!$header) {
            fclose($h);
            return $rows;
        }

        $header = array_map(fn($v) => trim(strtolower((string)$v)), $header);

        while (($data = fgetcsv($h)) !== false) {
            $row = [];
            foreach ($header as $i => $key) {
                $row[$key] = $data[$i] ?? '';
            }
            $rows[] = $row;
        }

        fclose($h);
        return $rows;
    }

    public function uploadReviewersCsv()
    {
        $this->requireAccess();

        $conference = $this->conference();

        if (empty($_FILES['csv']['tmp_name'])) {
            exit("CSV file required.");
        }

        $rows = $this->csvRows($_FILES['csv']['tmp_name']);

        $stmt = $this->db()->prepare("SELECT id FROM roles WHERE code='reviewer' LIMIT 1");
        $stmt->execute();
        $reviewerRoleId = (int)$stmt->fetchColumn();

        $inserted = 0;
        $updated = 0;
        $skipped = 0;
        $errors = [];

        foreach ($rows as $idx => $r) {
            $email = trim($r['email'] ?? '');

            if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $skipped++;
                $errors[] = "Row " . ($idx + 2) . ": invalid email";
                continue;
            }

            $first = trim($r['first_name'] ?? $r['firstname'] ?? $r['name'] ?? 'Reviewer');
            $last = trim($r['last_name'] ?? $r['lastname'] ?? '');
            $mobile = trim($r['mobile'] ?? $r['phone'] ?? '');
            $job = trim($r['job_title'] ?? $r['title'] ?? 'Reviewer');
            $expertise = trim($r['expertise'] ?? '');

            $stmt = $this->db()->prepare("SELECT id FROM users WHERE email=? LIMIT 1");
            $stmt->execute([$email]);
            $userId = (int)$stmt->fetchColumn();

            if ($userId > 0) {
                $stmt = $this->db()->prepare("
                    UPDATE users
                    SET org_id = ?,
                        role_id = ?,
                        first_name = COALESCE(NULLIF(?,''), first_name),
                        last_name = COALESCE(NULLIF(?,''), last_name),
                        mobile = COALESCE(NULLIF(?,''), mobile),
                        job_title = COALESCE(NULLIF(?,''), job_title),
                        expertise = COALESCE(NULLIF(?,''), expertise),
                        is_active = 1
                    WHERE id = ?
                ");
                $stmt->execute([(int)$conference['org_id'], $reviewerRoleId, $first, $last, $mobile, $job, $expertise, $userId]);
                $updated++;
            } else {
                $password = trim($r['password'] ?? 'Test@12345');

                $stmt = $this->db()->prepare("
                    INSERT INTO users
                    (org_id, role_id, first_name, last_name, email, password_hash, mobile, job_title, preferred_lang, is_active, expertise, created_at)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'en', 1, ?, NOW())
                ");
                $stmt->execute([
                    (int)$conference['org_id'],
                    $reviewerRoleId,
                    $first ?: 'Reviewer',
                    $last,
                    $email,
                    password_hash($password, PASSWORD_BCRYPT),
                    $mobile,
                    $job,
                    $expertise
                ]);
                $userId = (int)$this->db()->lastInsertId();
                $inserted++;
            }

            $stmt = $this->db()->prepare("
                SELECT id
                FROM user_conferences
                WHERE user_id = ?
                  AND conference_id = ?
                LIMIT 1
            ");
            $stmt->execute([$userId, (int)$conference['id']]);

            if ($stmt->fetchColumn()) {
                $stmt = $this->db()->prepare("
                    UPDATE user_conferences
                    SET role_id = ?
                    WHERE user_id = ?
                      AND conference_id = ?
                ");
                $stmt->execute([$reviewerRoleId, $userId, (int)$conference['id']]);
            } else {
                $stmt = $this->db()->prepare("
                    INSERT INTO user_conferences (user_id, conference_id, role_id)
                    VALUES (?, ?, ?)
                ");
                $stmt->execute([$userId, (int)$conference['id'], $reviewerRoleId]);
            }
        }

        $stmt = $this->db()->prepare("
            INSERT INTO conference_import_logs
            (org_id, conference_id, import_type, filename, total_rows, inserted_rows, updated_rows, skipped_rows, errors, created_by)
            VALUES (?, ?, 'reviewers_csv', ?, ?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([
            (int)$conference['org_id'],
            (int)$conference['id'],
            $_FILES['csv']['name'] ?? '',
            count($rows),
            $inserted,
            $updated,
            $skipped,
            implode("\n", $errors),
            (int)$_SESSION['user_id']
        ]);

        $this->redirect("/easychair/admin/conference-home#imports");
    }

    public function uploadCommitteesCsv()
    {
        $this->requireAccess();

        $conference = $this->conference();

        if (empty($_FILES['csv']['tmp_name'])) {
            exit("CSV file required.");
        }

        $rows = $this->csvRows($_FILES['csv']['tmp_name']);

        $inserted = 0;
        $updated = 0;
        $skipped = 0;
        $errors = [];

        foreach ($rows as $idx => $r) {
            $email = trim($r['email'] ?? '');
            $nameAr = trim($r['full_name_ar'] ?? $r['name_ar'] ?? '');
            $nameEn = trim($r['full_name_en'] ?? $r['name_en'] ?? $r['name'] ?? '');

            if (!$nameAr && !$nameEn && !$email) {
                $skipped++;
                $errors[] = "Row " . ($idx + 2) . ": missing name/email";
                continue;
            }

            $type = trim($r['committee_type'] ?? 'committee');

            $stmt = $this->db()->prepare("
                SELECT id
                FROM conference_committees
                WHERE conference_id = ?
                  AND (org_id = ? OR org_id IS NULL)
                  AND email = ?
                  AND email <> ''
                LIMIT 1
            ");
            $stmt->execute([(int)$conference['id'], (int)$conference['org_id'], $email]);
            $id = (int)$stmt->fetchColumn();

            if ($id > 0) {
                $stmt = $this->db()->prepare("
                    UPDATE conference_committees
                    SET committee_type = ?,
                        full_name_ar = ?,
                        full_name_en = ?,
                        title_ar = ?,
                        title_en = ?,
                        affiliation_ar = ?,
                        affiliation_en = ?,
                        sort_order = ?,
                        is_active = 1,
                        org_id = ?
                    WHERE id = ?
                ");
                $stmt->execute([
                    $type,
                    $nameAr,
                    $nameEn,
                    trim($r['title_ar'] ?? ''),
                    trim($r['title_en'] ?? ''),
                    trim($r['affiliation_ar'] ?? ''),
                    trim($r['affiliation_en'] ?? ''),
                    (int)($r['sort_order'] ?? 1),
                    (int)$conference['org_id'],
                    $id
                ]);
                $updated++;
            } else {
                $stmt = $this->db()->prepare("
                    INSERT INTO conference_committees
                    (org_id, conference_id, committee_type, full_name_ar, full_name_en, title_ar, title_en, affiliation_ar, affiliation_en, email, sort_order, is_active, created_by)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?)
                ");
                $stmt->execute([
                    (int)$conference['org_id'],
                    (int)$conference['id'],
                    $type,
                    $nameAr,
                    $nameEn,
                    trim($r['title_ar'] ?? ''),
                    trim($r['title_en'] ?? ''),
                    trim($r['affiliation_ar'] ?? ''),
                    trim($r['affiliation_en'] ?? ''),
                    $email,
                    (int)($r['sort_order'] ?? 1),
                    (int)$_SESSION['user_id']
                ]);
                $inserted++;
            }
        }

        $stmt = $this->db()->prepare("
            INSERT INTO conference_import_logs
            (org_id, conference_id, import_type, filename, total_rows, inserted_rows, updated_rows, skipped_rows, errors, created_by)
            VALUES (?, ?, 'committees_csv', ?, ?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([
            (int)$conference['org_id'],
            (int)$conference['id'],
            $_FILES['csv']['name'] ?? '',
            count($rows),
            $inserted,
            $updated,
            $skipped,
            implode("\n", $errors),
            (int)$_SESSION['user_id']
        ]);

        $this->redirect("/easychair/admin/conference-home#imports");
    }

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

        $key = trim($_POST['template_key'] ?? '');

        if ($key === '') {
            exit("Template key required.");
        }

        $stmt = $this->db()->prepare("
            INSERT INTO conference_email_templates
            (org_id, conference_id, event_key, template_key, subject_ar, subject_en, body_ar, body_en, is_active)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1)
            ON DUPLICATE KEY UPDATE
                subject_ar = VALUES(subject_ar),
                subject_en = VALUES(subject_en),
                body_ar = VALUES(body_ar),
                body_en = VALUES(body_en),
                updated_at = NOW()
        ");

        $stmt->execute([
            (int)$conference['org_id'],
            (int)$conference['id'],
            $key,
            $key,
            trim($_POST['subject_ar'] ?? ''),
            trim($_POST['subject_en'] ?? ''),
            trim($_POST['body_ar'] ?? ''),
            trim($_POST['body_en'] ?? '')
        ]);

        $this->redirect("/easychair/admin/conference-home#email-templates");
    }

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

        $id = (int)($_GET['id'] ?? 0);

        $stmt = $this->db()->prepare("
            UPDATE conference_email_templates
            SET is_active = IF(is_active=1,0,1)
            WHERE id = ?
              AND conference_id = ?
              AND (org_id = ? OR org_id IS NULL)
        ");
        $stmt->execute([$id, (int)$conference['id'], (int)$conference['org_id']]);

        $this->redirect("/easychair/admin/conference-home#email-templates");
    }

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

        $id = (int)($_GET['id'] ?? 0);

        $stmt = $this->db()->prepare("
            DELETE FROM conference_email_templates
            WHERE id = ?
              AND conference_id = ?
              AND (org_id = ? OR org_id IS NULL)
        ");
        $stmt->execute([$id, (int)$conference['id'], (int)$conference['org_id']]);

        $this->redirect("/easychair/admin/conference-home#email-templates");
    }

    public function toggleSection()
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        if (empty($_SESSION['user_id'])) {

            $this->redirect("/easychair/login");
        }

        $db = Database::getInstance();

        $id =
            (int)($_GET['id'] ?? 0);

        if ($id <= 0) {

            $_SESSION['error'] =
                'Invalid section id';

            $this->redirect("/easychair/admin/conference-home/sections");
        }

        try {

            $stmt = $db->prepare("
                UPDATE conference_home_sections

                SET enabled =
                    CASE
                        WHEN enabled = 1 THEN 0
                        ELSE 1
                    END

                WHERE id = ?
                LIMIT 1
            ");

            $stmt->execute([$id]);

            $_SESSION['success'] =
                'Homepage section updated successfully';

        } catch (\Throwable $e) {

            $_SESSION['error'] =
                $e->getMessage();

            error_log(
                'SECTION TOGGLE ERROR: '
                . $e->getMessage()
            );
        }

        $this->redirect("/easychair/admin/conference-home/sections");
    }


public function toggleSectionAjax()
{
    //$this->requireSuperAdmin();

    header('Content-Type: application/json');

    $db = Database::getInstance();

    $id =
        (int)($_POST['id'] ?? 0);

    $stmt = $db->prepare("

        UPDATE conference_home_sections

        SET enabled =
            CASE
                WHEN enabled = 1 THEN 0
                ELSE 1
            END

        WHERE id = ?
        LIMIT 1

    ");

    $ok = $stmt->execute([$id]);

    echo json_encode([
        'success' => $ok
    ]);

    exit;
}


public function reorderSectionsAjax()
{
    header('Content-Type: application/json');

    $db = Database::getInstance();

    $items =
        $_POST['items'] ?? [];

    if (!is_array($items)) {

        echo json_encode([
            'success' => false
        ]);

        exit;
    }

    $stmt = $db->prepare("

        UPDATE conference_home_sections

        SET sort_order = ?

        WHERE id = ?

    ");

    $sort = 1;

    foreach ($items as $id) {

        $stmt->execute([
            $sort,
            (int)$id
        ]);

        $sort++;
    }

    echo json_encode([
        'success' => true
    ]);

    exit;
}

public function sections()
{

ec_admin_require_url_action(
'/easychair/admin/conference-home/sections',
'view'
);

    $db = Database::getInstance();

    $conferenceId =
        (int)($_SESSION['conference_id'] ?? 0);

    $stmt = $db->prepare("

        SELECT *
        FROM conference_home_sections
        WHERE conference_id = ?
        ORDER BY sort_order ASC, id ASC

    ");

    $stmt->execute([
        $conferenceId
    ]);

    $sections =
        $stmt->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/sections.php';

    $content =
        ob_get_clean();

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

public function editSection()
{
    $db = Database::getInstance();

    $id =
        (int)($_GET['id'] ?? 0);

    $stmt = $db->prepare("

        SELECT *
        FROM conference_home_sections
        WHERE id = ?
        LIMIT 1

    ");

    $stmt->execute([$id]);

    $section =
        $stmt->fetch(\PDO::FETCH_ASSOC);

    if (!$section) {
        die('Section not found');
    }

    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/edit_section.php';

    $content =
        ob_get_clean();

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

public function updateSection()
{
    $db = Database::getInstance();

    $id =
        (int)($_POST['id'] ?? 0);

$backgroundImage =
    $_POST['existing_background_image']
    ?? '';

if (
    !empty($_FILES['background_image']['name'])
) {

    $dir =
        BASE_PATH .
        '/public/uploads/section_backgrounds/';

    if (!is_dir($dir)) {
        mkdir($dir, 0775, true);
    }

    $ext =
        pathinfo(
            $_FILES['background_image']['name'],
            PATHINFO_EXTENSION
        );

    $file =
        'section_' .
        time() .
        '_' .
        rand(1000,9999) .
        '.' .
        $ext;

    move_uploaded_file(
        $_FILES['background_image']['tmp_name'],
        $dir . $file
    );

    $backgroundImage =
        $file;
}

/*
|--------------------------------------------------------------------------
| Countdown Section Support
|--------------------------------------------------------------------------
*/

if (
    isset($_POST['countdown_date'])
    &&
    trim((string)$_POST['countdown_date']) !== ''
) {

    $settingsJson =
        trim(
            (string)(
                $_POST['settings_json']
                ?? '{}'
            )
        );

    $settings =
        json_decode(
            $settingsJson,
            true
        );

    if (!is_array($settings)) {
        $settings = [];
    }

    $settings['countdown_date'] =
        str_replace(
            'T',
            ' ',
            trim(
                (string)$_POST['countdown_date']
            )
        ) . ':00';

    $_POST['settings_json'] =
        json_encode(
            $settings,
            JSON_UNESCAPED_UNICODE
        );
}
    $stmt = $db->prepare("

        UPDATE conference_home_sections

        SET

            section_title_en = ?,
            section_title_ar = ?,

            title_en = ?,
            title_ar = ?,

            subtitle_en = ?,
            subtitle_ar = ?,
content_en = ?,
content_ar = ?,

            icon_class = ?,

designer_json = ?,

theme_name = ?,
animation_name = ?,
background_type = ?,
background_value = ?,
settings_json = ?,
generated_json = ?,
custom_css_class = ?,
background_image = ?,
            sort_order = ?,
            enabled = ?

        WHERE id = ?
        LIMIT 1

    ");

    $stmt->execute([

        trim($_POST['section_title_en'] ?? ''),
        trim($_POST['section_title_ar'] ?? ''),

        trim($_POST['title_en'] ?? ''),
        trim($_POST['title_ar'] ?? ''),

       trim($_POST['subtitle_en'] ?? ''),
trim($_POST['subtitle_ar'] ?? ''),

trim($_POST['content_en'] ?? ''),
trim($_POST['content_ar'] ?? ''),

trim($_POST['icon_class'] ?? ''),

json_encode([

    'badge_en' =>
        trim($_POST['badge_en'] ?? ''),

    'badge_ar' =>
        trim($_POST['badge_ar'] ?? ''),

    'overlay_strength' =>
        (int)($_POST['overlay_strength'] ?? 40),

    'container_width' =>
        trim($_POST['container_width'] ?? 'container'),

    'card_style' =>
        trim($_POST['card_style'] ?? 'enterprise')

], JSON_UNESCAPED_UNICODE),

trim($_POST['theme_name'] ?? 'enterprise-gradient'),

trim($_POST['animation_name'] ?? 'fade-up'),
trim($_POST['background_type'] ?? 'gradient'),

trim($_POST['background_value'] ?? ''),

trim($_POST['settings_json'] ?? ''),

trim($_POST['generated_json'] ?? ''),
trim($_POST['custom_css_class'] ?? ''),
        
$backgroundImage,
(int)($_POST['sort_order'] ?? 0),

        !empty($_POST['enabled']) ? 1 : 0,

        $id

    ]);

    $_SESSION['success'] =
        'Homepage section updated successfully';

    $this->redirect("/easychair/admin/conference-home/sections");
}

public function sectionLibrary()
{
    $this->requireAccess();

    $library =
        require BASE_PATH .
        '/app/views/partials/_section_registry.php';

    $conferenceId =
        (int)($_SESSION['conference_id'] ?? 0);

    $db = Database::getInstance();

    $stmt = $db->prepare("
        SELECT section_key
        FROM conference_home_sections
        WHERE conference_id=?
    ");

    $stmt->execute([$conferenceId]);

    $installed =
        array_column(
            $stmt->fetchAll(\PDO::FETCH_ASSOC),
            'section_key'
        );

    require BASE_PATH .
        '/app/views/admin/conference_home/library.php';
}

public function createSection()
{
    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/create_section.php';

    $content =
        ob_get_clean();

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

public function storeSection()
{
    $db = Database::getInstance();

    $conferenceId =
        (int)($_SESSION['conference_id'] ?? 0);

    $settingsJson =
        trim((string)($_POST['settings_json'] ?? ''));

    $generatedJson =
        trim((string)($_POST['generated_json'] ?? ''));

    if ($settingsJson === '') {
        $settingsJson = null;
    }

    if ($generatedJson === '') {
        $generatedJson = null;
    }

    $stmt = $db->prepare("
        INSERT INTO conference_home_sections
        (
            conference_id,
            section_key,
            section_title_en,
            section_title_ar,
            title_en,
            title_ar,
            subtitle_en,
            subtitle_ar,
            content_en,
            content_ar,
            icon_class,
            theme_name,
            animation_name,
            background_type,
            background_value,
            settings_json,
            generated_json,
            sort_order,
            enabled,
            publish_status
        )
        VALUES
        (
            ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'published'
        )
    ");

    $stmt->execute([

        $conferenceId,

        trim($_POST['section_key'] ?? ''),

        trim($_POST['section_title_en'] ?? ''),
        trim($_POST['section_title_ar'] ?? ''),

        trim($_POST['title_en'] ?? ''),
        trim($_POST['title_ar'] ?? ''),

        trim($_POST['subtitle_en'] ?? ''),
        trim($_POST['subtitle_ar'] ?? ''),

        trim($_POST['content_en'] ?? ''),
        trim($_POST['content_ar'] ?? ''),

        trim($_POST['icon_class'] ?? 'fa-cube'),

        trim($_POST['theme_name'] ?? 'enterprise-gradient'),

        trim($_POST['animation_name'] ?? 'fade-up'),

        trim($_POST['background_type'] ?? 'gradient'),
        trim($_POST['background_value'] ?? ''),

        $settingsJson,
        $generatedJson,

        (int)($_POST['sort_order'] ?? 100),

        !empty($_POST['enabled']) ? 1 : 0
    ]);

    $_SESSION['success'] =
        'Homepage section created successfully';

    $this->redirect(
        "/easychair/admin/conference-home/sections"
    );
}


public function installSection()
{
    $db = Database::getInstance();

    $conferenceId =
        (int)($_SESSION['conference_id'] ?? 0);

    $type =
        trim($_GET['type'] ?? '');

    if ($type === '') {

        $this->redirect(
            "/easychair/admin/conference-home/sections"
        );
    }

   $stmt = $db->prepare("
INSERT INTO conference_home_sections
(
    conference_id,

    section_key,

    section_title_en,
    section_title_ar,

    title_en,
    title_ar,

    icon_class,

    theme_name,

    settings_json,
    generated_json,

    content_en,
    content_ar,

    publish_status,

    enabled,

    sort_order
)
VALUES
(
    ?, ?, ?, ?, ?, ?,
    'fa-cube',
    'enterprise-gradient',
    ?,
    ?,
    ?,
    ?,
    'published',
    1,
    999
)
");

$defaultSettings = null;

if ($type === 'conference_dates') {

    $defaultSettings = json_encode([
        'layout_type' => 'timeline_cards',
        'items' => [
            [
                'icon' => 'fa-calendar-days',
                'title_ar' => 'المرحلة الأولى',
                'title_en' => 'First Phase',
                'body_ar' => 'بداية الاستلام',
                'body_en' => 'Submission Opens'
            ]
        ]
    ], JSON_UNESCAPED_UNICODE);
}

elseif ($type === 'important_links') {

    $defaultSettings = json_encode([
        'layout_type' => 'resource_links',
        'items' => []
    ], JSON_UNESCAPED_UNICODE);
}

elseif ($type === 'contact_cards') {

    $defaultSettings = json_encode([
        'layout_type' => 'contact_cards',
        'items' => []
    ], JSON_UNESCAPED_UNICODE);
}

$stmt->execute([

    $conferenceId,

    $type,

    ucfirst($type),

    ucfirst($type),

    ucfirst($type),

    ucfirst($type),

    $defaultSettings,

    null,

    null,

    null
]);

    $_SESSION['success'] =
        'Section installed successfully';

    $this->redirect(
        "/easychair/admin/conference-home/sections"
    );
}

public function deleteSection()
{
    $db = Database::getInstance();

    $id =
        (int)($_GET['id'] ?? 0);

    $stmt = $db->prepare("

        DELETE FROM conference_home_sections
        WHERE id = ?
        LIMIT 1

    ");

    $stmt->execute([$id]);

    $_SESSION['success'] =
        'Homepage section deleted';

    $this->redirect("/easychair/admin/conference-home/sections");
}

public function moveSectionUp()
{
    $this->moveSection(-1);
}

public function moveSectionDown()
{
    $this->moveSection(1);
}

private function moveSection(int $direction)
{
    $db = Database::getInstance();

    $id =
        (int)($_GET['id'] ?? 0);

    $stmt = $db->prepare("

        SELECT *
        FROM conference_home_sections
        WHERE id = ?
        LIMIT 1

    ");

    $stmt->execute([$id]);

    $current =
        $stmt->fetch(\PDO::FETCH_ASSOC);

    if (!$current) {
        die('Section not found');
    }

    $operator =
        $direction < 0 ? '<' : '>';

    $sort =
        (int)$current['sort_order'];

    $stmt = $db->prepare("

        SELECT *
        FROM conference_home_sections

        WHERE conference_id = ?
        AND sort_order {$operator} ?

        ORDER BY sort_order " .
        ($direction < 0 ? 'DESC' : 'ASC') . "

        LIMIT 1

    ");

    $stmt->execute([

        $current['conference_id'],
        $sort

    ]);

    $swap =
        $stmt->fetch(\PDO::FETCH_ASSOC);

    if ($swap) {

        $stmt = $db->prepare("

            UPDATE conference_home_sections
            SET sort_order = ?
            WHERE id = ?

        ");

        $stmt->execute([
            $swap['sort_order'],
            $current['id']
        ]);

        $stmt->execute([
            $sort,
            $swap['id']
        ]);
    }

    $this->redirect("/easychair/admin/conference-home/sections");
}
public function duplicateSection()
{
    $db = Database::getInstance();

    $id =
        (int)($_GET['id'] ?? 0);

    $stmt = $db->prepare("

        SELECT *
        FROM conference_home_sections
        WHERE id = ?
        LIMIT 1

    ");

    $stmt->execute([$id]);

    $section =
        $stmt->fetch(\PDO::FETCH_ASSOC);

    if (!$section) {

        $_SESSION['error'] =
            'Section not found';

        $this->redirect("/easychair/admin/conference-home/sections");
    }

    unset($section['id']);
    unset($section['created_at']);

    $section['section_key'] =
        $section['section_key'] .
        '_copy_' .
        time();

    $section['section_title_en'] =
        ($section['section_title_en'] ?? '')
        . ' Copy';

    $section['sort_order'] =
        ((int)$section['sort_order']) + 1;

    $columns =
        array_keys($section);

    $sql = "

        INSERT INTO conference_home_sections
        (" . implode(',', $columns) . ")

        VALUES
        (" . implode(',', array_fill(0, count($columns), '?')) . ")

    ";

    $stmt = $db->prepare($sql);

    $stmt->execute(
        array_values($section)
    );

    $_SESSION['success'] =
        'Section duplicated successfully';

    $this->redirect("/easychair/admin/conference-home/sections");
}

public function favoriteSection()
{
    $db =
        Database::getInstance();

    $id =
        (int)($_GET['id'] ?? 0);

    $stmt =
        $db->prepare("

            SELECT
            settings_json

            FROM conference_home_sections

            WHERE id=?

            LIMIT 1

        ");

    $stmt->execute([$id]);

    $row =
        $stmt->fetch(
            \PDO::FETCH_ASSOC
        );

    if (!$row) {
        $this->redirect(
            "/easychair/admin/conference-home/sections"
        );
    }

    $settings =
        json_decode(
            $row['settings_json']
            ?? '{}',
            true
        );

    $settings['favorite'] =
        !empty($settings['favorite'])
        ? 0
        : 1;

    $db->prepare("

        UPDATE
        conference_home_sections

        SET
        settings_json=?

        WHERE id=?

    ")
    ->execute([

        json_encode($settings),

        $id

    ]);

    $this->redirect(
        "/easychair/admin/conference-home/sections"
    );
}

/* =========================================================
 * HOMEPAGE BLOCK CMS
 * ========================================================= */

public function blocks()
{

ec_admin_require_url_action(
'/easychair/admin/conference-home/blocks',
'view'
);

    $db = Database::getInstance();

    $conferenceId =
        (int)($_SESSION['conference_id'] ?? 0);

    $stmt = $db->prepare("

        SELECT *
        FROM conference_homepage_blocks

        WHERE conference_id = ?

        ORDER BY sort_order ASC, id ASC

    ");

    $stmt->execute([$conferenceId]);

    $blocks =
        $stmt->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/blocks.php';

    $content =
        ob_get_clean();

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

public function createBlock()
{
    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/create_block.php';

    $content =
        ob_get_clean();

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

public function storeBlockCms()
{
    $db = Database::getInstance();

    $conferenceId =
        (int)($_SESSION['conference_id'] ?? 0);

    $orgId =
        (int)($_SESSION['org_id'] ?? 0);

    $stmt = $db->prepare("

        INSERT INTO conference_homepage_blocks
        (

            conference_id,
            org_id,

            block_type,
            block_key,

            title_en,
            title_ar,

            body_en,
            body_ar,

            button_text_en,
            button_text_ar,

            button_url,

            sort_order,

            is_active

        )

        VALUES
        (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

    ");

    $stmt->execute([

        $conferenceId,
        $orgId,

        trim($_POST['block_type'] ?? 'panel'),

        trim($_POST['block_key'] ?? ''),

        trim($_POST['title_en'] ?? ''),
        trim($_POST['title_ar'] ?? ''),

        trim($_POST['body_en'] ?? ''),
        trim($_POST['body_ar'] ?? ''),

        trim($_POST['button_text_en'] ?? ''),
        trim($_POST['button_text_ar'] ?? ''),

        trim($_POST['button_url'] ?? ''),

        (int)($_POST['sort_order'] ?? 0),

        !empty($_POST['is_active']) ? 1 : 0

    ]);

    $_SESSION['success'] =
        'Homepage block created successfully';

    $this->redirect("/easychair/admin/conference-home/blocks");
}

public function editBlock()
{
    $db = Database::getInstance();

    $id =
        (int)($_GET['id'] ?? 0);

    $stmt = $db->prepare("

        SELECT *
        FROM conference_homepage_blocks

        WHERE id = ?
        LIMIT 1

    ");

    $stmt->execute([$id]);

    $block =
        $stmt->fetch(\PDO::FETCH_ASSOC);

    if (!$block) {
        die('Block not found');
    }

    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/edit_block.php';

    $content =
        ob_get_clean();

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

public function updateBlock()
{
    $db = Database::getInstance();

    $id =
        (int)($_POST['id'] ?? 0);

    $stmt = $db->prepare("

        UPDATE conference_homepage_blocks

        SET

            block_type = ?,
            block_key = ?,

            title_en = ?,
            title_ar = ?,

            body_en = ?,
            body_ar = ?,

            button_text_en = ?,
            button_text_ar = ?,

            button_url = ?,

            sort_order = ?,

            is_active = ?

        WHERE id = ?
        LIMIT 1

    ");

    $stmt->execute([

        trim($_POST['block_type'] ?? 'panel'),

        trim($_POST['block_key'] ?? ''),

        trim($_POST['title_en'] ?? ''),
        trim($_POST['title_ar'] ?? ''),

        trim($_POST['body_en'] ?? ''),
        trim($_POST['body_ar'] ?? ''),

        trim($_POST['button_text_en'] ?? ''),
        trim($_POST['button_text_ar'] ?? ''),

        trim($_POST['button_url'] ?? ''),

        (int)($_POST['sort_order'] ?? 0),

        !empty($_POST['is_active']) ? 1 : 0,

        $id

    ]);

    $_SESSION['success'] =
        'Homepage block updated successfully';

    $this->redirect("/easychair/admin/conference-home/blocks");
}

public function deleteBlockCms()
{
    $db = Database::getInstance();

    $id =
        (int)($_GET['id'] ?? 0);

    $stmt = $db->prepare("

        DELETE FROM conference_homepage_blocks

        WHERE id = ?
        LIMIT 1

    ");

    $stmt->execute([$id]);

    $_SESSION['success'] =
        'Homepage block deleted';

    $this->redirect("/easychair/admin/conference-home/blocks");
}

public function toggleBlockCms()
{
    $db = Database::getInstance();

    $id =
        (int)($_GET['id'] ?? 0);

    $stmt = $db->prepare("

        UPDATE conference_homepage_blocks

        SET is_active =
            CASE
                WHEN is_active = 1 THEN 0
                ELSE 1
            END

        WHERE id = ?
        LIMIT 1

    ");

    $stmt->execute([$id]);

    $_SESSION['success'] =
        'Homepage block updated';

    $this->redirect("/easychair/admin/conference-home/blocks");
}

public function moveBlockUp()
{
    $this->moveBlock(-1);
}

public function moveBlockDown()
{
    $this->moveBlock(1);
}

private function moveBlock(int $direction)
{
    $db = Database::getInstance();

    $id =
        (int)($_GET['id'] ?? 0);

    $stmt = $db->prepare("

        SELECT *
        FROM conference_homepage_blocks

        WHERE id = ?
        LIMIT 1

    ");

    $stmt->execute([$id]);

    $current =
        $stmt->fetch(\PDO::FETCH_ASSOC);

    if (!$current) {
        die('Block not found');
    }

    $operator =
        $direction < 0 ? '<' : '>';

    $sort =
        (int)$current['sort_order'];

    $stmt = $db->prepare("

        SELECT *
        FROM conference_homepage_blocks

        WHERE conference_id = ?
        AND sort_order {$operator} ?

        ORDER BY sort_order " .
        ($direction < 0 ? 'DESC' : 'ASC') . "

        LIMIT 1

    ");

    $stmt->execute([
        (int)$current['conference_id'],
        $sort
    ]);

    $swap =
        $stmt->fetch(\PDO::FETCH_ASSOC);

    if (!$swap) {

        $this->redirect("/easychair/admin/conference-home/blocks");
    }

    $stmt = $db->prepare("

        UPDATE conference_homepage_blocks
        SET sort_order = ?
        WHERE id = ?

    ");

    $stmt->execute([
        (int)$swap['sort_order'],
        (int)$current['id']
    ]);

    $stmt->execute([
        $sort,
        (int)$swap['id']
    ]);

    $_SESSION['success'] =
        'Homepage block reordered';

    $this->redirect("/easychair/admin/conference-home/blocks");
}

public function studio()
{
    $this->requireAccess();

ec_admin_require_url_action(
'/easychair/admin/conference-home/studio',
'view'
);

    $db =
        Database::getInstance();

    $conference =
        $this->conference();

    $conferenceId =
        (int)$conference['id'];

    $sections = [];

    $blocks = [];

    try {

        $stmt =
            $db->prepare("

SELECT *
FROM conference_home_sections
WHERE conference_id=?
ORDER BY sort_order,id

");

        $stmt->execute([
            $conferenceId
        ]);

        $sections =
            $stmt->fetchAll(
                \PDO::FETCH_ASSOC
            );

    } catch (\Throwable $e) {}

    try {

        $stmt =
            $db->prepare("

SELECT *
FROM conference_homepage_blocks
WHERE conference_id=?
ORDER BY sort_order,id

");

        $stmt->execute([
            $conferenceId
        ]);

        $blocks =
            $stmt->fetchAll(
                \PDO::FETCH_ASSOC
            );

    } catch (\Throwable $e) {}

$stats = [

'sections'=>
count($sections),

'blocks'=>
count($blocks),

'active_sections'=>
count(
array_filter(
$sections,
fn($x)=>
!empty($x['enabled'])
)
),

'active_blocks'=>
count(
array_filter(
$blocks,
fn($x)=>
!empty(
$x['is_active']
?? 1
)
)
),

'last_publish'=>
'-',

'score'=>0

];

$score=0;

if(
count(
array_filter(
$sections,
fn($s)=>
($s['section_key']??'')
==='hero'
)
)
){
$score+=20;
}

if(
count($blocks)>5
){
$score+=20;
}

if(
count($sections)>5
){
$score+=20;
}

if(
array_filter(
$sections,
fn($s)=>
!empty(
$s['title_ar']
)
)
){
$score+=20;
}

if(
array_filter(
$blocks,
fn($b)=>
!empty(
$b['title_ar']
)
)
){
$score+=20;
}

$stats['score']=$score;

$health=0;

if(
count(
$sections
)>=10
){
$health+=25;
}

if(
count(
$blocks
)>=8
){
$health+=25;
}

if(
array_filter(
$sections,
fn($x)=>
!empty(
$x[
'title_ar'
]
)
)
){
$health+=25;
}

if(
array_filter(
$blocks,
fn($x)=>
!empty(
$x[
'subtitle_en'
]
?? ''
)
)
){
$health+=25;
}

$healthLabel=

$health>=90

? 'Excellent'

:

(

$health>=70

? 'Good'

:

'Needs Work'

);


/*
Homepage Governance
*/

$governance = 0;

if (
count(
$sections ?? []
) >= 12
){
$governance += 20;
}

if (
count(
$blocks ?? []
) >= 10
){
$governance += 20;
}

if (
count(
array_filter(
$sections,
fn($x)=>
!empty(
$x[
'title_ar'
]
?? ''
)
)
)
>= 5
){
$governance += 20;
}

if (
count(
array_filter(
$blocks,
fn($x)=>
!empty(
$x[
'title_ar'
]
?? ''
)
)
)
>= 5
){
$governance += 20;
}

if (
($health ?? 0)
>= 80
){
$governance += 20;
}

$governanceLabel =

$governance >= 90

? 'Enterprise'

:

(

$governance >= 70

? 'Professional'

:

'Developing'

);

try{

$stmt=
$db
->prepare("

SELECT

section_key,

SUM(
views
) views,

SUM(
clicks
) clicks

FROM
conference_home_heatmap

WHERE conference_id=?

GROUP BY section_key

");

$stmt
->execute([

$conferenceId

]);

$heatmap=
$stmt
->fetchAll();

}

catch(
Throwable $e
){

$heatmap=[];

}

    ob_start();
if(
!headers_sent()
){

    require
BASE_PATH .
'/app/views/admin/conference_home/studio.php';

    $content =
        ob_get_clean();

    require
BASE_PATH .
'/app/views/layouts/admin_layout.php';
}
}
public function publish()
{
$this->requireAccess();

$db =
Database::getInstance();

$conf =
$this->conference();

$id =
(int)$conf['id'];

$sections =
$db->query("

SELECT *
FROM conference_home_sections

")->fetchAll(
\PDO::FETCH_ASSOC
);

$blocks =
$db->query("

SELECT *
FROM conference_homepage_blocks

")->fetchAll(
\PDO::FETCH_ASSOC
);

$stmt =
$db->prepare("

INSERT INTO
conference_home_versions(

conference_id,

version_name,

version_type,

sections_json,

blocks_json,

created_by

)

VALUES(

?,

?,

'published',

?,

?,

?

)

");

$stmt->execute([

$id,

'Published '
.
date('Y-m-d H:i'),

json_encode(
$sections
),

json_encode(
$blocks
),

$_SESSION['user_id']

]);

$this->redirect("/easychair/admin/conference-home/studio");
}

public function versions1()
{
    $this->requireAccess();

    $db =
        Database::getInstance();

    $conference =
        $this->conference();

    $conferenceId =
        (int)$conference['id'];

    $stmt =
        $db->prepare("

SELECT *

FROM conference_home_versions

WHERE conference_id=?

ORDER BY id DESC

");

    $stmt->execute([
        $conferenceId
    ]);

    $versions =
        $stmt->fetchAll(
            \PDO::FETCH_ASSOC
        );

    ob_start();

    require
BASE_PATH .
'/app/views/admin/conference_home/versions.php';

    $content =
        ob_get_clean();

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

public function restore()
{
    $this->requireAccess();

    $db =
        Database::getInstance();

    $conference =
        $this->conference();

    $conferenceId =
        (int)$conference['id'];

    $id =
        (int)(
            $_GET['id']
            ?? 0
        );

    $stmt =
        $db->prepare("

SELECT *

FROM conference_home_versions

WHERE id=?

AND conference_id=?

LIMIT 1

");

    $stmt->execute([
        $id,
        $conferenceId
    ]);

    $version =
        $stmt->fetch(
            \PDO::FETCH_ASSOC
        );

    if (
        !$version
    ) {

        exit(
            'Version not found'
        );
    }

    $sections =
        json_decode(
            $version[
                'sections_json'
            ],
            true
        );

    if (
        is_array(
            $sections
        )
    ) {

        $db->prepare(
"

DELETE
FROM conference_home_sections
WHERE conference_id=?

"
)->execute([
$conferenceId
]);

foreach(
$sections
as $s
){

unset(
$s['id']
);

$cols =
array_keys(
$s
);

$sql =
"

INSERT INTO
conference_home_sections(

"
.
implode(
',',
$cols
)
.
")

VALUES(

"
.
implode(
',',
array_fill(
0,
count(
$cols
),
'?'
)
)
.
")

";

$db
->prepare(
$sql
)
->execute(
array_values(
$s
)
);

}

}

$this->redirect("/easychair/admin/conference-home/studio");
}

public function cloneHomepage()
{
$this->requireAccess();

$db =
Database::getInstance();

$conference =
$this->conference();

$id =
(int)$conference['id'];

$sections =
$db
->query("
SELECT *
FROM conference_home_sections
WHERE conference_id={$id}
")
->fetchAll(
\PDO::FETCH_ASSOC
);

$blocks =
$db
->query("
SELECT *
FROM conference_homepage_blocks
WHERE conference_id={$id}
")
->fetchAll(
\PDO::FETCH_ASSOC
);

$stmt =
$db->prepare("

INSERT INTO
conference_home_templates(

name,

org_id,

sections_json,

blocks_json,

created_by

)

VALUES(

?,

?,

?,

?,

?

)

");

$stmt->execute([

'Template '
.
date('YmdHis'),

$_SESSION['org_id'],

json_encode(
$sections
),

json_encode(
$blocks
),

$_SESSION['user_id']

]);

$this->redirect("/easychair/admin/conference-home/studio");

}

public function exportHomepage()
{
$this->requireAccess();

$db =
Database::getInstance();

$conf =
$this->conference();

$id =
(int)$conf['id'];

$out=[

'sections'=>

$db
->query(
"

SELECT *

FROM conference_home_sections

WHERE conference_id={$id}

"
)
->fetchAll(
\PDO::FETCH_ASSOC
),

'blocks'=>

$db
->query(
"

SELECT *

FROM conference_homepage_blocks

WHERE conference_id={$id}

"
)
->fetchAll(
\PDO::FETCH_ASSOC
)

];

header('Content-Type: application/json');

header('Content-Disposition: attachment; filename=homepage.json');

echo json_encode(
$out,
JSON_PRETTY_PRINT
);

exit;
}

public function importHomepage()
{
    $this->requireAccess();

    $db =
        Database::getInstance();

    $conference =
        $this->conference();

    $conferenceId =
        (int)$conference['id'];

    /*
     * Upload UI
     */

    if (
        $_SERVER['REQUEST_METHOD']
        !== 'POST'
    ) {

        ob_start();

        require
BASE_PATH .
'/app/views/admin/conference_home/import.php';

        $content =
            ob_get_clean();

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

        return;
    }

    if (
        empty(
            $_FILES['homepage']
        )
    ) {

        exit(
            'No file uploaded'
        );
    }

    $json =
        file_get_contents(
            $_FILES[
                'homepage'
            ][
                'tmp_name'
            ]
        );

    $data =
        json_decode(
            $json,
            true
        );

    if (
        !is_array(
            $data
        )
    ) {

        exit(
            'Invalid JSON'
        );
    }

    $sections =
        $data[
            'sections'
        ]
        ?? [];

    $blocks =
        $data[
            'blocks'
        ]
        ?? [];

    $db
    ->prepare(
"

DELETE
FROM conference_home_sections
WHERE conference_id=?

"
)->execute([
$conferenceId
]);

    $db
    ->prepare(
"

DELETE
FROM conference_homepage_blocks
WHERE conference_id=?

"
)->execute([
$conferenceId
]);

    foreach(
        $sections
        as $s
    ){

        unset(
            $s['id']
        );

        $s[
            'conference_id'
        ] =
        $conferenceId;

        $cols =
            array_keys(
                $s
            );

        $sql =
"

INSERT INTO
conference_home_sections(

"
.
implode(
',',
$cols
)
.
")

VALUES(

"
.
implode(
',',
array_fill(
0,
count(
$cols
),
'?'
)
)
.
")

";

        $db
        ->prepare(
            $sql
        )
        ->execute(
            array_values(
                $s
            )
        );
    }

    foreach(
        $blocks
        as $b
    ){

        unset(
            $b['id']
        );

        $b[
            'conference_id'
        ] =
        $conferenceId;

        $cols =
            array_keys(
                $b
            );

        $sql =
"

INSERT INTO
conference_homepage_blocks(

"
.
implode(
',',
$cols
)
.
")

VALUES(

"
.
implode(
',',
array_fill(
0,
count(
$cols
),
'?'
)
)
.
")

";

        $db
        ->prepare(
            $sql
        )
        ->execute(
            array_values(
                $b
            )
        );
    }

    $this->redirect("/easychair/admin/conference-home/studio");
}

public function templates()
{
$this->requireAccess();

$db =
Database::getInstance();

$templates =
$db
->query("

SELECT
t.*,

m.title,

m.category

FROM conference_home_templates t

LEFT JOIN conference_home_marketplace m

ON m.template_id=t.id

ORDER BY t.id DESC

")
->fetchAll(
\PDO::FETCH_ASSOC
);

ob_start();

require
BASE_PATH .
'/app/views/admin/conference_home/templates.php';

$content =
ob_get_clean();

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



public function aiGenerateHomepage()
{
$this->requireAccess();

$db=
Database::getInstance();

$conference=
$this->conference();

$conferenceId=
(int)$conference['id'];

$title=

$conference[
'title_en'
]

??

'Conference';

$sections=[

'hero',

'conference_facts',

'themes',

'speakers',

'program',

'venue',

'stats',

'timeline',

'proceedings',

'partners',

'sponsors',

'networking',

'ai_research',

'operations_center',

'cta'

];

/*
SECTION MERGE
*/

foreach(
$sections
as $i=>$key
){

$q=
$db
->prepare("

SELECT id

FROM conference_home_sections

WHERE conference_id=?

AND section_key=?

LIMIT 1

");

$q
->execute([

$conferenceId,

$key

]);

if(
$q->fetch()
){
continue;
}

$db
->prepare("

INSERT INTO
conference_home_sections(

conference_id,

section_key,

section_title_en,

section_title_ar,

title_en,

title_ar,

enabled,

sort_order,

theme_name

)

VALUES(

?,

?,

?,

?,

?,

?,

1,

?,

?

)

")

->execute([

$conferenceId,

$key,

ucwords(
str_replace(
'_',
' ',
$key
)
),

str_replace(
'_',
' ',
$key
),

ucwords(
str_replace(
'_',
' ',
$key
)
),

str_replace(
'_',
' ',
$key
),

$i+1,

'enterprise-gradient'

]);

}

/*
AI WRITER
*/

$writer=[

'hero'=>[

'International Conference on Health Sciences',

'المؤتمر الدولي للعلوم الصحية',

'Research • Innovation • Collaboration',

'البحث • الابتكار • التعاون',

'hero_slide'

],

'speakers'=>[

'Distinguished Speakers',

'المتحدثون',

'Global experts and researchers',

'خبراء وباحثون دوليون',

'feature'

],

'program'=>[

'Conference Program',

'برنامج المؤتمر',

'Interactive scientific sessions',

'جلسات علمية تفاعلية',

'panel'

],

'venue'=>[

'Conference Venue',

'مكان انعقاد المؤتمر',

'Modern experience',

'بيئة مؤتمرات متقدمة',

'travel'

],

'stats'=>[

'Conference Statistics',

'إحصائيات المؤتمر',

'Participants • Sessions',

'المشاركون • الجلسات',

'analytics'

],

'proceedings'=>[

'Proceedings',

'وقائع المؤتمر',

'Indexed publications',

'نشر وفهرسة',

'proceedings'

],

'cta'=>[

'Register Now',

'سجل الآن',

'Join researchers worldwide',

'انضم للباحثين',

'cta'

]

];

$order=1;

foreach(
$writer
as $key=>$w
){

$q=
$db
->prepare("

SELECT id

FROM conference_homepage_blocks

WHERE conference_id=?

AND block_key=?

LIMIT 1

");

$q
->execute([

$conferenceId,

$key

]);

if(
$q->fetch()
){
continue;
}

$db
->prepare("

INSERT INTO
conference_homepage_blocks(

conference_id,

block_key,

title_en,

title_ar,

subtitle_en,

subtitle_ar,

block_type,

sort_order,

is_active

)

VALUES(

?,

?,

?,

?,

?,

?,

?,

?,

1

)

")

->execute([

$conferenceId,

$key,

$w[0],

$w[1],

$w[2],

$w[3],

$w[4],

$order++

]);

}

$this->redirect("/easychair/admin/conference-home/studio");
}

public function aiImport()
{
$this->requireAccess();

$db=
Database::getInstance();

$conference=
$this->conference();

$conferenceId=
(int)$conference['id'];

if(
$_SERVER['REQUEST_METHOD']
!=='POST'
){

ob_start();

require
BASE_PATH.
'/app/views/admin/conference_home/ai_import.php';

$content=
ob_get_clean();

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

return;

}

if(
empty(
$_FILES[
'brochure_file'
][
'tmp_name'
]
)
){

exit(
'Upload brochure first'
);

}

$text=
trim(
file_get_contents(
$_FILES[
'brochure_file'
][
'tmp_name'
]
)
);

if(
!$text
){

exit(
'Brochure empty'
);

}

/*
PRIMARY SECTION SET
*/

$baseSections=[

'hero',

'home_blocks',

'speakers',

'themes',

'program',

'venue',

'stats',

'conference_facts',

'timeline',

'proceedings',

'partners',

'sponsors',

'networking',

'ai_research',

'operations_center',

'cta'

];

/*
BROCHURE BONUS
*/

$bonus=[];

$map=[

'speaker'=>'speakers',

'theme'=>'themes',

'venue'=>'venue',

'program'=>'program',

'partner'=>'partners',

'proceedings'=>'proceedings',

'sponsor'=>'sponsors',

'contact'=>'cta'

];

foreach(
$map
as $w=>$k
){

if(
stripos(
$text,
$w
)!==false
){

$bonus[]=
$k;

}

}

$sections=
array_unique(
array_merge(
$baseSections,
$bonus
)
);

/*
MERGE SECTIONS
*/

foreach(
$sections
as $i=>$key
){

$q=
$db
->prepare("

SELECT id

FROM conference_home_sections

WHERE conference_id=?

AND section_key=?

LIMIT 1

");

$q
->execute([

$conferenceId,

$key

]);

if(
$q
->fetch()
){

continue;

}

$db
->prepare("

INSERT INTO
conference_home_sections(

conference_id,

section_key,

title_en,

enabled,

sort_order

)

VALUES(

?,

?,

?,

1,

?

)

")

->execute([

$conferenceId,

$key,

ucwords(
str_replace(
'_',
' ',
$key
)
),

$i+1

]);

}

/*
SAFE BLOCKS
*/

$blocks=[

[
'hero',
$conference[
'title_en'
]
?? 'Conference',
'hero_slide'
],

[
'program',
'Conference Program',
'panel'
],

[
'speakers',
'Keynote Speakers',
'feature'
],

[
'venue',
'Venue',
'travel'
],

[
'stats',
'Conference Statistics',
'analytics'
],

[
'sponsors',
'Sponsors',
'media'
],

[
'partners',
'Partners',
'feature'
],

[
'proceedings',
'Proceedings',
'proceedings'
],

[
'register',
'Register Now',
'cta'
]

];

foreach(
$blocks
as $i=>$b
){

$q=
$db
->prepare("

SELECT id

FROM conference_homepage_blocks

WHERE conference_id=?

AND block_key=?

LIMIT 1

");

$q
->execute([

$conferenceId,

$b[0]

]);

if(
$q
->fetch()
){

continue;

}

$db
->prepare("

INSERT INTO
conference_homepage_blocks(

conference_id,

block_key,

title_en,

block_type,

sort_order,

is_active

)

VALUES(

?,

?,

?,

?,

?,

1

)

")

->execute([

$conferenceId,

$b[0],

$b[1],

$b[2],

$i+1

]);

}

$this->redirect("/easychair/admin/conference-home/studio");

}

public function snapshot()
{
$this->requireAccess();

$c=
$this->conference();

\App\Services\HomepageStateService::capture(

(int)
$c[
'id'
],

(int)
$_SESSION[
'user_id'
]

);

$this->redirect(
'/easychair/admin/conference-home/studio'
);
}

public function snapshotStatus()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\HomepageStateService::latest(

(int)
$c[
'id'
]

)

);

exit;
}

public function reorder()
{
$this->requireAccess();

$order=
$_POST[
'order'
]
?? [];

$db=
Database::getInstance();

foreach(
$order
as $i=>$id
){

$db
->prepare(
"

UPDATE
conference_home_sections

SET sort_order=?

WHERE id=?

"

)

->execute([

$i+1,

$id

]);

}

echo 'OK';

exit;
}

public function preview()
{
    $this->requireAccess();

    $conference =
        $this->conference();

    $slug =
        $conference[
            'slug'
        ]
        ??
        (
            $_SESSION[
                'conference_slug'
            ]
            ?? ''
        );

    if (
        !$slug
    ) {

        exit(
            'Conference slug missing'
        );
    }

    header(
        'Location: /easychair/conference/'
        .
        urlencode(
            $slug
        )
    );

    exit;
}

public function operations()
{
$this->requireAccess();

$db=
Database::getInstance();

$conference=
$this->conference();

$id=
(int)$conference['id'];

$sections=

$db
->query(
"

SELECT *

FROM conference_home_sections

WHERE conference_id=$id

ORDER BY sort_order

"

)

->fetchAll();

$stats=[

'total'=>
count(
$sections
),

'published'=>

count(
array_filter(
$sections,
fn($x)=>

(
$x[
'publish_status'
]
?? ''
)

==='published'
)
),

'draft'=>

count(
array_filter(
$sections,
fn($x)=>

(
$x[
'publish_status'
]
?? ''
)

==='draft'
)
)

];

ob_start();

require
BASE_PATH
.
'/app/views/admin/conference_home/operations.php';

$content=
ob_get_clean();

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

public function aiWriteHomepage()
{
$this->requireAccess();

$db=
Database::getInstance();

$conference=
$this->conference();

$id=
(int)$conference['id'];

$sections=
$db
->prepare("

SELECT
id,
section_key

FROM
conference_home_sections

WHERE conference_id=?

");

$sections
->execute([
$id
]);

foreach(
$sections
->fetchAll()
as $s
){

$en=
match(
$s[
'section_key'
]
){

'hero'=>

'Explore global collaboration and innovation in health sciences.',

'speakers'=>

'Meet distinguished international keynote speakers.',

'program'=>

'Discover interactive sessions and scientific activities.',

'venue'=>

'Experience a modern and collaborative environment.',

default=>

'Learn more about this conference section.'

};

$ar=
match(
$s[
'section_key'
]
){

'hero'=>

'اكتشف الابتكار والتعاون العالمي في العلوم الصحية',

'speakers'=>

'تعرف على المتحدثين والخبراء الدوليين',

'program'=>

'استكشف البرنامج العلمي والجلسات',

'venue'=>

'بيئة مؤتمرات حديثة',

default=>

'اكتشف المزيد عن هذا القسم'

};

$db
->prepare("

UPDATE
conference_home_sections

SET

content_en=?,

content_ar=?

WHERE id=?

")

->execute([

$en,

$ar,

$s[
'id'
]

]);

}

$this->redirect("/easychair/admin/conference-home/studio");

}

public function aiConferenceComposer()
{
$this->requireAccess();

$db=
Database::getInstance();

$conference=
$this->conference();

$conferenceId=
(int)$conference['id'];

/*
Speakers
*/

$speakers=[

[
'name'=>'Prof. Global Health Expert',
'country'=>'UK'
],

[
'name'=>'Dr. Innovation Leader',
'country'=>'USA'
]

];

/*
Program
*/

$program=[

[
'time'=>'09:00',

'title'=>
'Opening Ceremony'

],

[
'time'=>'10:30',

'title'=>
'Keynote Session'

],

[
'time'=>'13:00',

'title'=>
'Research Tracks'

]

];

/*
Proceedings
*/

$proceedings=[

'indexed'=>

true,

'publisher'=>

'Conference Proceedings',

'tracks'=>

6

];

$data=[

'speakers'=>
$speakers,

'program'=>
$program,

'proceedings'=>
$proceedings

];

$db
->prepare("

UPDATE
conference_home_sections

SET

generated_json=?

WHERE conference_id=?

AND section_key IN(

'speakers',

'program',

'proceedings'

)

")

->execute([

json_encode(
$data,
JSON_UNESCAPED_UNICODE
),

$conferenceId

]);

$_SESSION[
'flash_success'
]=

'AI Conference Content Generated';

$this->redirect("/easychair/admin/conference-home/studio");

}

public function marketplace()
{
    $this->requireAccess();

    $c = $this->conference();

    if (
        isset($_GET['publish'])
    ) {

        \App\Services\HomepageMarketplaceService::publish(

            (int)$c['id'],

            (int)($c['org_id'] ?? 0),

            (int)($_SESSION['user_id'] ?? 0)

        );
    }

    $templates =
        \App\Services\HomepageMarketplaceService::catalog(
            (int)($c['org_id'] ?? 0)
        );

    $title =
        'Homepage Marketplace';

    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/marketplace.php';

    $content =
        ob_get_clean();

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

public function saveTemplate()
{
$this->requireAccess();

$db=
Database::getInstance();

$conference=
$this->conference();

$conferenceId=
(int)$conference['id'];

$orgId=
(int)(
$conference[
'org_id'
]
??
$_SESSION[
'org_id'
]
??
0
);

$name=

trim(
$_GET[
'name'
]
??
''
);

if(
!$name
){

$name=
'Template '
.
date(
'YmdHis'
);

}

/*
SECTIONS
*/

$stmt=
$db
->prepare("

SELECT *

FROM
conference_home_sections

WHERE conference_id=?

ORDER BY sort_order

");

$stmt
->execute([

$conferenceId

]);

$sections=
$stmt
->fetchAll(
\PDO::FETCH_ASSOC
);

/*
BLOCKS
*/

$stmt=
$db
->prepare("

SELECT *

FROM
conference_homepage_blocks

WHERE conference_id=?

ORDER BY sort_order

");

$stmt
->execute([

$conferenceId

]);

$blocks=
$stmt
->fetchAll(
\PDO::FETCH_ASSOC
);

$db
->prepare("

INSERT INTO
conference_home_templates(

name,

org_id,

sections_json,

blocks_json,

created_by

)

VALUES(

?,

?,

?,

?,

?

)

")

->execute([

$name,

$orgId,

json_encode(
$sections,
JSON_UNESCAPED_UNICODE
),

json_encode(
$blocks,
JSON_UNESCAPED_UNICODE
),

$_SESSION[
'user_id'
]

]);

$this->redirect("/easychair/admin/conference-home/marketplace");

}

public function applyTemplate()
{
$this->requireAccess();

$db=
Database::getInstance();

$id=
(int)(
$_GET[
'id'
]
??
0
);

$conference=
$this->conference();

$conferenceId=
(int)$conference['id'];

$stmt=
$db
->prepare("

SELECT *

FROM
conference_home_templates

WHERE id=?

LIMIT 1

");

$stmt
->execute([

$id

]);

$template=
$stmt
->fetch(
\PDO::FETCH_ASSOC
);

if(
!$template
){

exit(
'Template not found'
);

}

$sections=

json_decode(

$template[
'sections_json'
]
??

'[]',

true

);

$blocks=

json_decode(

$template[
'blocks_json'
]
??

'[]',

true

);

/*
merge only
*/

foreach(
$sections
as $s
){

$q=
$db
->prepare("

SELECT id

FROM conference_home_sections

WHERE conference_id=?

AND section_key=?

");

$q
->execute([

$conferenceId,

$s[
'section_key'
]

]);

if(
$q->fetch()
){

continue;

}

unset(
$s[
'id'
]
);

$s[
'conference_id'
]
=
$conferenceId;

$cols=
array_keys(
$s
);

$db
->prepare(

"

INSERT INTO conference_home_sections(

"

.
implode(
',',
$cols
)

.

")

VALUES(

"

.
implode(
',',
array_fill(
0,
count(
$cols
),
'?'
)
)

.

")

"

)

->execute(

array_values(
$s
)

);

}

$this->redirect("/easychair/admin/conference-home/studio");

}

public function duplicateTemplate()
{
$this->requireAccess();

$db=
Database::getInstance();

$id=
(int)(
$_GET['id']
?? 0
);

$stmt=
$db
->prepare("

SELECT *

FROM conference_home_templates

WHERE id=?

");

$stmt
->execute([
$id
]);

$t=
$stmt
->fetch(
\PDO::FETCH_ASSOC
);

if(
!$t
){

exit(
'Template not found'
);

}

$db
->prepare("

INSERT INTO
conference_home_templates(

name,

org_id,

sections_json,

blocks_json,

created_by,

version_no

)

VALUES(

?,

?,

?,

?,

?,

?

)

")

->execute([

$t['name']
.' Copy',

$t['org_id'],

$t['sections_json'],

$t['blocks_json'],

$_SESSION['user_id'],

(
(int)(
$t[
'version_no'
]
?? 1
)
+1
)

]);

$this->redirect("/easychair/admin/conference-home/marketplace");

}

public function favoriteTemplate()
{
$this->requireAccess();

$db=
Database::getInstance();

$id=
(int)(
$_GET[
'id'
]
?? 0
);

$db
->prepare("

UPDATE
conference_home_templates

SET

is_favorite=
1-is_favorite

WHERE id=?

")

->execute([

$id

]);

$this->redirect("/easychair/admin/conference-home/marketplace");
}

public function exportBlueprint()
{
$this->requireAccess();

$db=
Database::getInstance();

$c=
$this->conference();

$cid=
(int)$c['id'];

$org=
(int)(
$c['org_id']
??
$_SESSION['org_id']
??
0
);

$s=
$db
->prepare("

SELECT *

FROM conference_home_sections

WHERE conference_id=?

ORDER BY sort_order

");

$s->execute([
$cid
]);

$sections=
$s
->fetchAll(
\PDO::FETCH_ASSOC
);

$b=
$db
->prepare("

SELECT *

FROM conference_homepage_blocks

WHERE conference_id=?

ORDER BY sort_order

");

$b->execute([
$cid
]);

$blocks=
$b
->fetchAll(
\PDO::FETCH_ASSOC
);

$db
->prepare("

INSERT INTO
conference_home_blueprints(

name,

org_id,

source_conference_id,

sections_json,

blocks_json,

theme_json,

created_by

)

VALUES(

?,

?,

?,

?,

?,

?,

?

)

")

->execute([

'Blueprint '
.
date(
'Y-m-d H:i'
),

$org,

$cid,

json_encode(
$sections,
JSON_UNESCAPED_UNICODE
),

json_encode(
$blocks,
JSON_UNESCAPED_UNICODE
),

json_encode([

'theme'=>

'enterprise'

]),

$_SESSION[
'user_id'
]

]);

$this->redirect("/easychair/admin/conference-home/blueprints");
}

public function blueprints()
{
$this->requireAccess();

$db=
Database::getInstance();

$list=

$db
->query("

SELECT *

FROM
conference_home_blueprints

ORDER BY id DESC

")

->fetchAll();

ob_start();

require
BASE_PATH
.
'/app/views/admin/conference_home/blueprints.php';

$content=
ob_get_clean();

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

public function autosave()
{
$this->requireAccess();

header(
'Content-Type: application/json'
);

$db=
Database::getInstance();

$conference=
$this->conference();

$conferenceId=
(int)$conference['id'];

$data=

json_decode(

file_get_contents(
'php://input'
),

true

);

$key=

$data[
'key'
]

??

'studio';

$payload=

json_encode(
$data,
JSON_UNESCAPED_UNICODE
);

$db
->prepare("

INSERT INTO
conference_home_drafts(

conference_id,

user_id,

draft_key,

payload_json

)

VALUES(

?,

?,

?,

?

)

ON DUPLICATE KEY UPDATE

payload_json=

VALUES(
payload_json
)

")

->execute([

$conferenceId,

$_SESSION[
'user_id'
],

$key,

$payload

]);

echo
json_encode([

'ok'=>1

]);

exit;
}

public function checkDraft()
{
$this->requireAccess();

header(
'Content-Type: application/json'
);

$db=
Database::getInstance();

$c=
$this->conference();

$stmt=
$db
->prepare("

SELECT

user_id,

updated_at

FROM
conference_home_drafts

WHERE conference_id=?

ORDER BY updated_at DESC

LIMIT 1

");

$stmt
->execute([

$c[
'id'
]

]);

echo
json_encode(

$stmt
->fetch()

);

exit;
}

public function heartbeat()
{
$this->requireAccess();

header(
'Content-Type: application/json'
);

$db=
Database::getInstance();

$c=
$this->conference();

$db
->prepare("

INSERT INTO
conference_home_activity(

conference_id,

user_id,

event_type,

payload_json

)

VALUES(

?,

?,

'presence',

?

)

")

->execute([

$c['id'],

$_SESSION['user_id'],

json_encode([

'time'=>
time()

])

]);

echo json_encode([

'ok'=>1

]);

exit;

}

public function activity()
{
$this->requireAccess();

header(
'Content-Type: application/json'
);

$db=
Database::getInstance();

$c=
$this->conference();

$stmt=
$db
->prepare("

SELECT

event_type,

created_at,

user_id

FROM
conference_home_activity

WHERE conference_id=?

ORDER BY id DESC

LIMIT 20

");

$stmt
->execute([

$c['id']

]);

echo json_encode(

$stmt->fetchAll()

);

exit;
}

public function submitWorkflow()
{
$this->requireAccess();

$db=
Database::getInstance();

$c=
$this->conference();

$db
->prepare("

INSERT INTO
conference_home_workflow(

conference_id,

version_label,

workflow_state,

requested_by

)

VALUES(

?,

?,

'review',

?

)

")

->execute([

$c[
'id'
],

'Studio '
.
date(
'Ymd_His'
),

$_SESSION[
'user_id'
]

]);

$this->redirect("/easychair/admin/conference-home/studio");

}

public function approveWorkflow()
{
$this->requireAccess();

$db=
Database::getInstance();

$id=
(int)(
$_GET[
'id'
]
??
0
);

$db
->prepare("

UPDATE
conference_home_workflow

SET

workflow_state='approved',

approved_by=?,

approved_at=NOW()

WHERE id=?

")

->execute([

$_SESSION[
'user_id'
],

$id

]);

$this->redirect("/easychair/admin/conference-home/timeline");

}

public function timeline()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\HomepageReviewService::latest(

(int)
$c[
'id'
]

)

);

exit;
}

public function createRelease()
{
$this->requireAccess();

$db=
Database::getInstance();

$c=
$this->conference();

$sections=
$db
->prepare("

SELECT *

FROM conference_home_sections

WHERE conference_id=?

");

$sections
->execute([

$c['id']

]);

$blocks=
$db
->prepare("

SELECT *

FROM conference_homepage_blocks

WHERE conference_id=?

");

$blocks
->execute([

$c['id']

]);

$data=[

'sections'=>
$sections
->fetchAll(),

'blocks'=>
$blocks
->fetchAll()

];

$db
->prepare("

INSERT INTO
conference_home_releases(

conference_id,

release_name,

snapshot_json,

created_by

)

VALUES(

?,

?,

?,

?

)

")

->execute([

$c['id'],

'Release '
.
date(
'Ymd_His'
),

json_encode(
$data,
JSON_UNESCAPED_UNICODE
),

$_SESSION[
'user_id'
]

]);

$this->redirect("/easychair/admin/conference-home/releases");

}

public function publishRelease()
{
$this->requireAccess();

$db=
Database::getInstance();

$id=
(int)(
$_GET['id']
?? 0
);

$db
->prepare("

UPDATE
conference_home_releases

SET

release_status='published',

published_at=NOW()

WHERE id=?

")

->execute([

$id

]);

$this->redirect("/easychair/admin/conference-home/releases");

}

public function rollbackRelease()
{
$this->requireAccess();

$db=
Database::getInstance();

$id=
(int)(
$_GET[
'id'
]
??
0
);

$stmt=
$db
->prepare("

SELECT snapshot_json

FROM conference_home_releases

WHERE id=?

");

$stmt
->execute([

$id

]);

$r=
$stmt
->fetch();

if(
!$r
){

exit(
'Release not found'
);

}

$_SESSION[
'flash_success'
]=

'Rollback prepared';

$this->redirect("/easychair/admin/conference-home/studio");

}

public function releases()
{
$this->requireAccess();

$db=
Database::getInstance();

$c=
$this->conference();

$stmt=
$db
->prepare("

SELECT *

FROM conference_home_releases

WHERE conference_id=?

ORDER BY id DESC

");

$stmt
->execute([

$c['id']

]);

$releases=
$stmt
->fetchAll();

ob_start();

$this->redirect(
'/easychair/admin/conference-home/releases'
);

$content=
ob_get_clean();

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


private function redirect(
string $url
): void
{

if(
headers_sent()
){

echo
'<script>

location.href='

.

json_encode(
$url
)

.

';

</script>';

exit;

}

header(
'Location: '
.
trim(
$url
)
);

exit;

}

public function clearCache()
{
    $this->requireAccess();

    $conference =
        $this->conference();

    $conferenceId =
        (int)(
            $conference['id']
            ?? 0
        );

    \App\Services\HomepageCacheService::clear(
        $conferenceId
    );

    $this->redirect(
        '/easychair/admin/conference-home/studio'
    );
}

public function health()
{
$this->requireAccess();

$c=
$this->conference();

if(
isset(
$_GET[
'recover'
]
)
){

\App\Services\HomepageHealthService::recover(

(int)
$c[
'id'
]

);

}

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\HomepageHealthService::dashboard(

(int)
$c[
'id'
]

)

);

exit;
}

public function recommendations()
{
$this->requireAccess();

$c=
$this->conference();

$data=

\App\Services\HomepageRecommendationService::analyze(

(int)
$c[
'id'
]

);

header(
'Content-Type: application/json'
);

echo
json_encode(
$data);

exit;

}

public function governance()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\HomepageGovernanceService::dashboard(

(int)
$c[
'id'
],

(int)
(
$c[
'org_id'
]
??
0
)

)

);

exit;
}

public function certify()
{
$this->requireAccess();

$c=
$this->conference();

$data=

\App\Services\HomepageCertificationService::certify(

(int)
$c[
'id'
]

);

header(
'Content-Type: application/json'
);

echo
json_encode(
$data
);

exit;
}

public function commandCenter()
{
$this->requireAccess();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\CommandCenterService::actions()

);

exit;
}

public function policy()
{
$this->requireAccess();

$c=
$this->conference();

$data=

\App\Services\HomepagePolicyService::validate(

(int)
$c[
'id'
],

(int)(
$c[
'org_id'
]
??
0
)

);

header(
'Content-Type: application/json'
);

echo
json_encode(
$data
);

exit;
}

public function archiveHomepage()
{
$this->requireAccess();

$c=
$this->conference();

\App\Services\HomepageLifecycleService::archive(

(int)
$c[
'id'
],

(int)
$_SESSION[
'user_id'
]

);

$this->redirect(

'/easychair/admin/conference-home/studio'

);
}

public function lifecycle()
{
$this->requireAccess();

$c=
$this->conference();

$data=

\App\Services\HomepageLifecycleService::status(

(int)
$c[
'id'
]

);

header(
'Content-Type: application/json'
);

echo
json_encode(
$data
);

exit;
}

public function simulate()
{
$this->requireAccess();

$c=
$this->conference();

\App\Services\HomepageSimulationService::create(

(int)
$c[
'id'
],

(int)
$_SESSION[
'user_id'
]

);

$this->redirect(
'/easychair/admin/conference-home/studio'
);
}

public function simulation()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\HomepageSimulationService::latest(

(int)
$c[
'id'
]

)

);

exit;
}

public function optimize()
{
$this->requireAccess();

$c=
$this->conference();

\App\Services\HomepageOrchestratorService::enqueue(

(int)
$c[
'id'
],

'optimize',

(int)
$_SESSION[
'user_id'
]

);

$this->redirect(
'/easychair/admin/conference-home/studio'
);
}

public function queue()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\HomepageOrchestratorService::latest(

(int)
$c[
'id'
]

)

);

exit;
}

public function schedulePublish()
{
$this->requireAccess();

$c=
$this->conference();

$when=

date(
'Y-m-d H:i:s',
strtotime(
'+1 hour'
)

);

\App\Services\HomepageSchedulerService::schedule(

(int)
$c['id'],

'publish',

$when,

(int)
$_SESSION[
'user_id'
]

);

$this->redirect(
'/easychair/admin/conference-home/studio'
);
}

public function scheduleStatus()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\HomepageSchedulerService::next(

(int)
$c['id']

)

);

exit;
}

public function experiment()
{
$this->requireAccess();

$c=
$this->conference();

\App\Services\HomepageExperimentService::create(

(int)
$c[
'id'
],

(int)
$_SESSION[
'user_id'
]

);

$this->redirect(
'/easychair/admin/conference-home/studio'
);
}

public function experimentStatus()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\HomepageExperimentService::latest(

(int)
$c[
'id'
]

)

);

exit;
}

public function intelligence()
{
$this->requireAccess();

$c=
$this->conference();

$data=

\App\Services\HomepageIntelligenceService::analyze(

(int)
$c[
'id'
]

);

header(
'Content-Type: application/json'
);

echo
json_encode(
$data
);

exit;
}

public function command()
{
$this->requireAccess();

$c=
$this->conference();

$cmd=

$_GET[
'cmd'
]

??

'refresh';

\App\Services\HomepageCommandBus::dispatch(

(int)
$c[
'id'
],

$cmd,

[],

(int)
$_SESSION[
'user_id'
]

);

$this->redirect(
'/easychair/admin/conference-home/studio'
);
}

public function timelineEvents()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\HomepageEventStoreService::latest(

(int)
$c[
'id'
]

)

);

exit;
}

public function replicate()
{
$this->requireAccess();

$c=
$this->conference();

$target=

(int)
(
$_GET[
'target'
]

??

0

);

if(
$target
){

\App\Services\HomepageReplicationService::replicate(

(int)
$c[
'id'
],

$target

);

}

$this->redirect(
'/easychair/admin/conference-home/studio'
);
}

public function catalog()
{
$this->requireAccess();

$c=
$this->conference();

$orgId=

(int)
(
$c[
'org_id'
]

??

0
);

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\HomepageFederationService::catalog(

$orgId

)

);

exit;
}

public function mesh()
{
$this->requireAccess();

$c=
$this->conference();

$orgId=

(int)
(
$c[
'org_id'
]

??

0
);

header(
'Content-Type: application/json'
);

echo
json_encode([

'components'=>

\App\Services\HomepageMeshService::registry(
$orgId
),

'themes'=>

\App\Services\HomepageMeshService::themes(
$orgId
)

]);

exit;
}

public function workspace()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\HomepageWorkspaceService::latest(

(int)
$c[
'id'
]

)

);

exit;
}

public function saveWorkspace()
{
$this->requireAccess();

$c=
$this->conference();

$layout=

file_get_contents(
'php://input'
);

\App\Services\HomepageWorkspaceService::save(

(int)
$c[
'id'
],

$layout,

(int)
$_SESSION[
'user_id'
]

);

echo
'ok';

exit;
}

public function commands()
{
$this->requireAccess();

$db=
\App\Core\Database::getInstance();

header(
'Content-Type: application/json'
);

echo
json_encode(

$db
->query("

SELECT *

FROM
conference_home_commands_registry

WHERE is_active=1

ORDER BY id

")

->fetchAll()

);

exit;
}

public function collaboration()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\HomepageCollaborationService::dashboard(

(int)
$c[
'id'
]

)

);

exit;
}

public function presence()
{
$this->requireAccess();

$c=
$this->conference();

\App\Services\HomepagePresenceService::ping(

(int)
$c[
'id'
],

(int)
$_SESSION[
'user_id'
],

$_SESSION[
'user_name'
]
??
'Editor'

);

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\HomepagePresenceService::active(

(int)
$c[
'id'
]

)

);

exit;
}

public function branch()
{
$this->requireAccess();

$c=
$this->conference();

\App\Services\HomepageBranchService::create(

(int)
$c[
'id'
],

(int)
$_SESSION[
'user_id'
]

);

$this->redirect(

'/easychair/admin/conference-home/studio'

);
}

public function branches1()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\HomepageBranchService::latest(

(int)
$c[
'id'
]

)

);

exit;
}

public function deploy()
{
$this->requireAccess();

$c=
$this->conference();

\App\Services\HomepageDeploymentService::deploy(

(int)
$c[
'id'
],

(int)
$_SESSION[
'user_id'
]

);

$this->redirect(
'/easychair/admin/conference-home/studio'
);
}

public function deployment()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\HomepageDeploymentService::latest(

(int)
$c[
'id'
]

)

);

exit;
}

public function missionControl()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\HomepageMissionControlService::dashboard(

(int)
$c[
'id'
]

)

);

exit;
}

public function controlTower()
{
$this->requireAccess();

$c=
$this->conference();

if(
isset(
$_GET[
'maintain'
]
)
){

\App\Services\HomepageControlTowerService::maintain(

(int)
$c[
'id'
]

);

}

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\HomepageControlTowerService::dashboard(

(int)
$c[
'id'
]

)

);

exit;
}

public function reliability()
{
$this->requireAccess();

$c=
$this->conference();

if(
isset(
$_GET[
'heal'
]
)
){

\App\Services\HomepageReliabilityService::heal(

(int)
$c[
'id'
]

);

}

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\HomepageReliabilityService::dashboard(

(int)
$c[
'id'
]

)

);

exit;
}

public function portfolio()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\HomepagePortfolioService::dashboard(

(int)
(
$c[
'org_id'
]
??
0
)

)

);

exit;
}

public function knowledge()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\HomepageKnowledgeService::insights(

(int)
$c[
'id'
],

(int)
(
$c[
'org_id'
]
??
0
)

)

);

exit;
}

public function digitalTwin()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\HomepageDigitalTwinService::simulate(

(int)
$c[
'id'
]

)

);

exit;
}


public function graph()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\HomepageGraphService::summary(

(int)
$c[
'id'
]

)

);

exit;
}

public function strategy()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\HomepageStrategyService::dashboard(

(int)
$c[
'id'
]

)

);

exit;
}

public function programOffice()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\HomepageProgramOfficeService::dashboard(

(int)
$c[
'id'
]

)

);

exit;
}

public function scorecard()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\HomepageScorecardService::dashboard(

(int)
$c[
'id'
]

)

);

exit;
}

public function enterpriseBrain()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\HomepageEnterpriseBrainService::analyze(

(int)
$c[
'id'
]

)

);

exit;
}

public function shell()
{
$this->requireAccess();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\WorkspaceShellService::navigation()

);

exit;
}

public function operatingSystem()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\PlatformOperatingSystemService::dashboard(

(int)
$c['id'],

(int)
(
$c['org_id']
??
0
)

)

);

exit;
}

public function kernel()
{
$this->requireAccess();

$c=
$this->conference();

if(
isset(
$_GET[
'snapshot'
]
)
){

\App\Services\PlatformKernelService::snapshot(

(int)
$c[
'id'
],

(int)
$_SESSION[
'user_id'
]

);

}

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\PlatformKernelService::dashboard(

(int)
$c[
'id'
]

)

);

exit;
}

public function hypervisor()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\PlatformHypervisorService::dashboard(

(int)
(
$c[
'org_id'
]
??
0
),

(int)
$c[
'id'
]

)

);

exit;
}

public function fabric()
{
    $this->requireAccess();

    $c = $this->conference();

    header('Content-Type: application/json');

    echo json_encode(
        \App\Services\PlatformFabricService::dashboard(
            (int)($c['org_id'] ?? 0),
            (int)$c['id']
        )
    );

    exit;
}


public function copilot()
{
$this->requireAccess();

header(
'Content-Type: application/json'
);

$input=

json_decode(

file_get_contents(
'php://input'
),

true

);

echo
json_encode(

\App\Services\HomepageCopilotService::interpret(

$input[
'prompt'
]

??

''

)

);

exit;
}

public function agents()
{
$this->requireAccess();

header(
'Content-Type: application/json'
);

$body=

json_decode(

file_get_contents(
'php://input'
),

true

);

$c=
$this->conference();

echo
json_encode(

\App\Services\HomepageAgentService::plan(

(int)
$c[
'id'
],

(int)
$_SESSION[
'user_id'
],

(string)
(
$body[
'goal'
]
??
''
)

)

);

exit;
}

public function memory()
{
$this->requireAccess();

$c=
$this->conference();

if(
isset(
$_GET[
'remember'
]
)
){

\App\Services\PlatformMemoryService::remember(

(int)
(
$c[
'org_id'
]
??
0
),

(int)
$c[
'id'
],

(int)
$_SESSION[
'user_id'
]

);

}

header(
'Content-Type: application/json');

echo
json_encode(

\App\Services\PlatformMemoryService::dashboard(

(int)
$c[
'id'
],

(int)
(
$c[
'org_id'
]
??
0
)

)

);

exit;
}

public function cognition()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\PlatformCognitiveService::dashboard(

(int)
$c[
'id'
]

)

);

exit;
}

public function neuralMesh()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\PlatformNeuralMeshService::dashboard(

(int)
$c[
'id'
]

)

);

exit;
}

public function conscious()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\PlatformConsciousService::dashboard(

(int)
$c[
'id'
]

)

);

exit;
}

public function meta()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\PlatformMetaService::dashboard(

(int)
$c[
'id'
]

)

);

exit;
}

public function universe()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\PlatformUniverseService::dashboard(

(int)
$c[
'id'
],

(int)
(
$c[
'org_id'
]
??
0
)

)

);

exit;
}

public function nexus()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\PlatformNexusService::dashboard(

(int)
(
$c[
'org_id'
]
??
0
)

)

);

exit;
}

public function centralNervous()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\PlatformCentralNervousService::dashboard(

(int)
$c[
'id'
],

(int)
(
$c[
'org_id'
]
??
0
)

)

);

exit;
}

public function executive()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\PlatformExecutiveCockpitService::dashboard(

(int)
(
$c[
'org_id'
]
??
0
)

)

);

exit;
}

public function strategic()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\PlatformStrategicCommandService::dashboard(

(int)
(
$c[
'org_id'
]
??
0
)

)

);

exit;
}

public function constitution()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\PlatformConstitutionService::dashboard(

(int)
(
$c[
'org_id'
]
??
0
),

(int)
$c[
'id'
]

)

);

exit;
}

public function cabinet()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\PlatformCabinetService::dashboard(

(int)
(
$c[
'org_id'
]
??
0
),

(int)
$c[
'id'
]

)

);

exit;
}

public function senate()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\PlatformSenateService::dashboard(

(int)
(
$c[
'org_id'
]
??
0
)

)

);

exit;
}

public function chancellor()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\PlatformChancellorOfficeService::dashboard(

(int)
(
$c[
'org_id'
]
??
0
)

)

);

exit;
}

public function observatory()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\PlatformNationalObservatoryService::dashboard(

(int)
(
$c[
'org_id'
]
??
0
)

)

);

exit;
}

public function ministry()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\PlatformMinistryService::dashboard(

(int)
(
$c[
'org_id'
]
??
0
)

)

);

exit;
}

public function sovereign()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\PlatformSovereignService::dashboard(

(int)
(
$c[
'org_id'
]
??
0
)

)

);

exit;
}

public function civilization()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\PlatformCivilizationService::dashboard(

(int)
(
$c[
'org_id'
]
??
0
)

)

);

exit;
}

public function singularity()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json');

echo
json_encode(

\App\Services\PlatformSingularityService::dashboard(

(int)
(
$c[
'org_id'
]
??
0
),

(int)
$c[
'id'
]

)

);

exit;
}

public function genesis()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo
json_encode(

\App\Services\PlatformGenesisService::dashboard(

(int)
(
$c[
'org_id'
]
??
0
),

(int)
$c[
'id'
]

)

);

exit;
}

public function horizon()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo json_encode(

\App\Services\PlatformHorizonService::dashboard(

(int)
(
$c[
'org_id'
]
??
0
)

)

);

exit;
}

public function legacy()
{
    $this->requireAccess();

    $c = $this->conference();

    header('Content-Type: application/json');

    echo json_encode(
        \App\Services\PlatformLegacyService::dashboard(
            (int)($c['org_id'] ?? 0),
            (int)$c['id']
        )
    );

    exit;
}

public function continuityBoard()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo json_encode(

\App\Services\PlatformContinuityBoardService::dashboard(

(int)
(
$c['org_id']
??
0
),

(int)
$c['id']

)

);

exit;
}

public function stewardship()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo json_encode(

\App\Services\PlatformStewardshipService::dashboard(

(int)
(
$c['org_id']
??
0
)

)

);

exit;
}

public function heritage()
{
    $this->requireAccess();

    $c = $this->conference();

    header('Content-Type: application/json');

    echo json_encode(
        \App\Services\PlatformHeritageService::dashboard(
            (int)($c['org_id'] ?? 0)
        )
    );

    exit;
}

public function archiveVault()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo json_encode(
\App\Services\PlatformArchiveVaultService::dashboard(
(int)($c['org_id'] ?? 0),
(int)$c['id']
)
);

exit;
}

public function trust()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo json_encode(
\App\Services\PlatformTrustService::dashboard(
(int)($c['org_id'] ?? 0),
(int)$c['id']
)
);

exit;
}

public function chronicle()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo json_encode(
\App\Services\PlatformChronicleService::dashboard(
(int)($c['org_id'] ?? 0),
(int)$c['id']
)
);

exit;
}

public function timeCapsule()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo json_encode(
\App\Services\PlatformTimeCapsuleService::dashboard(
(int)($c['org_id'] ?? 0),
(int)$c['id']
)
);

exit;
}

public function compass()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo json_encode(
\App\Services\PlatformCompassService::dashboard(
(int)($c['org_id'] ?? 0),
(int)$c['id']
)
);

exit;
}

public function beacon()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo json_encode(
\App\Services\PlatformBeaconService::dashboard(
(int)($c['org_id'] ?? 0),
(int)$c['id']
)
);

exit;
}

public function atlas()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo json_encode(
\App\Services\PlatformAtlasService::dashboard(
(int)($c['org_id'] ?? 0),
(int)$c['id']
)
);

exit;
}

public function orbit()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo json_encode(
\App\Services\PlatformOrbitService::dashboard(
(int)($c['org_id'] ?? 0),
(int)$c['id']
)
);

exit;
}

public function pulse()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo json_encode(
\App\Services\PlatformPulseService::dashboard(
(int)($c['org_id'] ?? 0),
(int)$c['id']
)
);

exit;
}

public function resonance()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo json_encode(
\App\Services\PlatformResonanceService::dashboard(
(int)($c['org_id'] ?? 0),
(int)$c['id']
)
);

exit;
}

public function gravity()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo json_encode(
\App\Services\PlatformGravityService::dashboard(
(int)($c['org_id'] ?? 0),
(int)$c['id']
)
);

exit;
}

public function aurora()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo json_encode(
\App\Services\PlatformAuroraService::dashboard(
(int)($c['org_id'] ?? 0),
(int)$c['id']
)
);

exit;
}

public function zenith()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo json_encode(
\App\Services\PlatformZenithService::dashboard(
(int)($c['org_id'] ?? 0),
(int)$c['id']
)
);

exit;
}

public function constellation()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo json_encode(
\App\Services\PlatformConstellationService::dashboard(
(int)($c['org_id'] ?? 0),
(int)$c['id']
)
);

exit;
}

public function lighthouse()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo json_encode(
\App\Services\PlatformLighthouseService::dashboard(
(int)($c['org_id'] ?? 0),
(int)$c['id']
)
);

exit;
}

public function observatoryPrime()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo json_encode(
\App\Services\PlatformObservatoryPrimeService::dashboard(
(int)($c['org_id'] ?? 0),
(int)$c['id']
)
);

exit;
}

public function frontier()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo json_encode(
\App\Services\PlatformFrontierService::dashboard(
(int)($c['org_id'] ?? 0),
(int)$c['id']
)
);

exit;
}

public function nexusPrime()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo json_encode(
\App\Services\PlatformNexusPrimeService::dashboard(
(int)($c['org_id'] ?? 0),
(int)$c['id']
)
);

exit;
}

public function continuum()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo json_encode(
\App\Services\PlatformContinuumService::dashboard(
(int)($c['org_id'] ?? 0),
(int)$c['id']
)
);

exit;
}

public function horizonPrime()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo json_encode(
\App\Services\PlatformHorizonPrimeService::dashboard(
(int)($c['org_id'] ?? 0),
(int)$c['id']
)
);

exit;
}

public function apex()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo json_encode(
\App\Services\PlatformApexService::dashboard(
(int)($c['org_id'] ?? 0),
(int)($c['id'] ?? 0)
)
);

exit;
}

public function crown()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo json_encode(
\App\Services\PlatformCrownService::dashboard(
(int)($c['org_id'] ?? 0),
(int)($c['id'] ?? 0)
)
);

exit;
}

public function summit()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo json_encode(
\App\Services\PlatformSummitService::dashboard(
(int)($c['org_id'] ?? 0),
(int)($c['id'] ?? 0)
)
);

exit;
}

public function infinity()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo json_encode(
\App\Services\PlatformInfinityService::dashboard(
(int)($c['org_id'] ?? 0),
(int)($c['id'] ?? 0)
)
);

exit;
}

public function origin()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo json_encode(
\App\Services\PlatformOriginService::dashboard(
(int)($c['org_id'] ?? 0),
(int)($c['id'] ?? 0)
)
);

exit;
}

public function legacyPrime()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo json_encode(
\App\Services\PlatformLegacyPrimeService::dashboard(
(int)($c['org_id'] ?? 0),
(int)($c['id'] ?? 0)
)
);

exit;
}

public function genesisPrime()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo json_encode(
\App\Services\PlatformGenesisPrimeService::dashboard(
(int)($c['org_id'] ?? 0),
(int)($c['id'] ?? 0)
)
);

exit;
}

public function omega()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo json_encode(
\App\Services\PlatformOmegaService::dashboard(
(int)($c['org_id'] ?? 0),
(int)($c['id'] ?? 0)
)
);

exit;
}

public function eternal()
{
$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo json_encode(
\App\Services\PlatformEternalService::dashboard(
(int)($c['org_id'] ?? 0),
(int)($c['id'] ?? 0)
)
);

exit;
}

public function metrics()
{

$this->requireAccess();

$c=
$this->conference();

header(
'Content-Type: application/json'
);

echo json_encode(

\App\Services\StudioMetricsService::metrics(

(int)(
$c['org_id']
??0
),

(int)(
$c['id']
??0
)

)

);

exit;

}

public function runtime()
{

$this->requireAccess();

header(
'Content-Type: application/json'
);

$list=

explode(
',',
$_GET['widgets']
??''
);

$out=[];

foreach(
$list
as $w
){

$out[
$w
]=[
'ok'=>1
];

}

echo json_encode(
$out
);

exit;

}

public function widgetPermissions()
{

header(
'Content-Type: application/json'
);

echo json_encode(

\App\Services\StudioWidgetRegistry::allowed()

);

exit;

}

public function compareTemplates()
{
    $this->requireAccess();

    $db =
        Database::getInstance();

    $a =
        (int)(
            $_GET['a']
            ?? 0
        );

    $b =
        (int)(
            $_GET['b']
            ?? 0
        );

    $templates =
        [];

    if (
        $a > 0
        &&
        $b > 0
    ) {

        $stmt =
            $db->prepare("

                SELECT
                    id,
                    name,
                    sections_json,
                    blocks_json,
                    created_at,
                    version_no

                FROM
                    conference_home_templates

                WHERE id IN (?,?)

                ORDER BY id ASC

            ");

        $stmt->execute([
            $a,
            $b
        ]);

        $templates =
            $stmt->fetchAll(
                \PDO::FETCH_ASSOC
            );
    }

    $allTemplates =
        [];

    try {

        $allTemplates =
            $db
            ->query("

                SELECT
                    id,
                    name,
                    created_at,
                    version_no

                FROM
                    conference_home_templates

                ORDER BY id DESC

                LIMIT 50

            ")
            ->fetchAll(
                \PDO::FETCH_ASSOC
            );

    } catch (\Throwable $e) {

        $allTemplates =
            [];
    }

    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/compare.php';

    $content =
        ob_get_clean();

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

public function publishCenter()
{
    $this->requireAccess();

    $db =
        Database::getInstance();

    $conf =
        $this->conference();

    $snapshotCount = 0;

    try {

        $stmt =
            $db->prepare("

                SELECT COUNT(*)

                FROM conference_home_templates

                WHERE org_id=?

            ");

        $stmt->execute([

            $_SESSION['org_id']

        ]);

        $snapshotCount =
            (int)
            $stmt->fetchColumn();

    } catch (\Throwable $e) {

        $snapshotCount = 0;

    }

    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/publish_center.php';

    $content =
        ob_get_clean();

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

public function publicationHistory()
{
    $this->requireAccess();

    $db =
        Database::getInstance();

    $conf =
        $this->conference();

    $stmt =
        $db->prepare("

            SELECT *

            FROM homepage_publications

            WHERE conference_id=?

            ORDER BY published_at DESC

        ");

    $stmt->execute([

        $conf['id']

    ]);

    $rows =
        $stmt->fetchAll(
            \PDO::FETCH_ASSOC
        );

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/publications.php';

    $content =
        ob_get_clean();

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


public function rollbackCenter()
{
    $this->requireAccess();

    $db =
        Database::getInstance();

    $conf =
        $this->conference();

    $stmt =
        $db->prepare("

            SELECT
                id,
                name,
                created_at,
                version_no

            FROM
                conference_home_templates

            WHERE
                org_id = ?

            ORDER BY
                id DESC

            LIMIT 50

        ");

    $stmt->execute([
        (int)($conf['org_id'] ?? $_SESSION['org_id'] ?? 0)
    ]);

    $snapshots =
        $stmt->fetchAll(
            \PDO::FETCH_ASSOC
        );

    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/rollback.php';

    $content =
        ob_get_clean();

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


public function restoreSnapshot()
{
    $this->requireAccess();

    $db =
        Database::getInstance();

    $conf =
        $this->conference();

    $conferenceId =
        (int)$conf['id'];

    $orgId =
        (int)($conf['org_id'] ?? $_SESSION['org_id'] ?? 0);

    $templateId =
        (int)($_POST['template_id'] ?? 0);

    if ($templateId <= 0) {

        $_SESSION['error'] =
            'Invalid snapshot selected.';

        $this->redirect(
            '/easychair/admin/conference-home/rollback'
        );
    }

    $stmt =
        $db->prepare("

            SELECT *

            FROM conference_home_templates

            WHERE id = ?
              AND org_id = ?

            LIMIT 1

        ");

    $stmt->execute([
        $templateId,
        $orgId
    ]);

    $template =
        $stmt->fetch(
            \PDO::FETCH_ASSOC
        );

    if (!$template) {

        $_SESSION['error'] =
            'Snapshot not found.';

        $this->redirect(
            '/easychair/admin/conference-home/rollback'
        );
    }

    $sections =
        json_decode(
            (string)($template['sections_json'] ?? '[]'),
            true
        );

    if (!is_array($sections)) {

        $_SESSION['error'] =
            'Snapshot sections are invalid.';

        $this->redirect(
            '/easychair/admin/conference-home/rollback'
        );
    }

    try {

        $db->beginTransaction();

        /*
        |--------------------------------------------------------------------------
        | Safety Backup Before Restore
        |--------------------------------------------------------------------------
        */

        $currentSectionsStmt =
            $db->prepare("

                SELECT *

                FROM conference_home_sections

                WHERE conference_id = ?

                ORDER BY sort_order ASC, id ASC

            ");

        $currentSectionsStmt->execute([
            $conferenceId
        ]);

        $currentSections =
            $currentSectionsStmt->fetchAll(
                \PDO::FETCH_ASSOC
            );

        $backupName =
            'Auto Backup Before Rollback '
            . date('Y-m-d H:i:s');

        $backupStmt =
            $db->prepare("

                INSERT INTO conference_home_templates
                (
                    name,
                    org_id,
                    sections_json,
                    blocks_json,
                    created_by,
                    version_no,
                    is_favorite
                )

                VALUES
                (
                    ?, ?, ?, ?, ?, 1, 0
                )

            ");

        $backupStmt->execute([

            $backupName,

            $orgId,

            json_encode(
                $currentSections,
                JSON_UNESCAPED_UNICODE
            ),

            json_encode(
                [],
                JSON_UNESCAPED_UNICODE
            ),

            (int)($_SESSION['user_id'] ?? 0)

        ]);

        /*
        |--------------------------------------------------------------------------
        | Load Existing Columns Safely
        |--------------------------------------------------------------------------
        */

        $colsStmt =
            $db->query("
                SHOW COLUMNS
                FROM conference_home_sections
            ");

        $allowedColumns =
            array_column(
                $colsStmt->fetchAll(\PDO::FETCH_ASSOC),
                'Field'
            );

        /*
        |--------------------------------------------------------------------------
        | Clear Current Homepage Sections
        |--------------------------------------------------------------------------
        */

        $deleteStmt =
            $db->prepare("

                DELETE FROM conference_home_sections

                WHERE conference_id = ?

            ");

        $deleteStmt->execute([
            $conferenceId
        ]);

        /*
        |--------------------------------------------------------------------------
        | Restore Snapshot Sections
        |--------------------------------------------------------------------------
        */

        foreach ($sections as $row) {

            if (!is_array($row)) {
                continue;
            }

            unset($row['id']);

            $row['conference_id'] =
                $conferenceId;

            if (
                in_array('org_id', $allowedColumns, true)
            ) {
                $row['org_id'] =
                    $orgId;
            }

            $clean = [];

            foreach ($row as $key => $value) {

                if (
                    in_array(
                        $key,
                        $allowedColumns,
                        true
                    )
                ) {
                    $clean[$key] =
                        $value;
                }
            }

            if (empty($clean)) {
                continue;
            }

            $columns =
                array_keys($clean);

            $placeholders =
                array_fill(
                    0,
                    count($columns),
                    '?'
                );

            $sql =
                "INSERT INTO conference_home_sections (" .
                implode(',', $columns) .
                ") VALUES (" .
                implode(',', $placeholders) .
                ")";

            $insert =
                $db->prepare($sql);

            $insert->execute(
                array_values($clean)
            );
        }

        /*
        |--------------------------------------------------------------------------
        | Publication/Rollback Log If Table Exists
        |--------------------------------------------------------------------------
        */

        try {

            $logStmt =
                $db->prepare("

                    INSERT INTO homepage_publications
                    (
                        conference_id,
                        snapshot_template_id,
                        published_by,
                        notes
                    )

                    VALUES
                    (
                        ?, ?, ?, ?
                    )

                ");

            $logStmt->execute([

                $conferenceId,

                $templateId,

                (int)($_SESSION['user_id'] ?? 0),

                'Emergency rollback restored from snapshot.'

            ]);

        } catch (\Throwable $e) {

            // Optional table may not exist. Ignore safely.
        }

        $db->commit();

        $_SESSION['success'] =
            'Homepage restored successfully from snapshot. A safety backup was created first.';

    } catch (\Throwable $e) {

        if ($db->inTransaction()) {
            $db->rollBack();
        }

        $_SESSION['error'] =
            'Rollback failed: '
            . $e->getMessage();
    }

    $this->redirect(
        '/easychair/admin/conference-home/sections'
    );
}

public function deploymentCenter()
{
    $this->requireAccess();

    $db =
        Database::getInstance();

    $conf =
        $this->conference();

    $stmt =
        $db->prepare("

            SELECT *

            FROM homepage_deployments

            WHERE conference_id=?

            ORDER BY id DESC

            LIMIT 1

        ");

    $stmt->execute([
        (int)$conf['id']
    ]);

    $deployment =
        $stmt->fetch(
            \PDO::FETCH_ASSOC
        );

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/deployment_center.php';

    $content =
        ob_get_clean();

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

public function updateHomepageWorkflow()
{
$this->requireAccess();


$newStatus =
    trim(
        $_POST['status']
        ?? ''
    );

$db =
    \App\Core\Database::getInstance();

$conf =
    $this->conference();

$stmt =
    $db->prepare("

        SELECT status

        FROM homepage_deployments

        WHERE conference_id = ?

        LIMIT 1

    ");

$stmt->execute([

    (int)$conf['id']

]);

$this->syncHomepageWorkflowOwnership(
    (int)$conf['id'],
    $newStatus
);

$currentStatus =
    (string)(
        $stmt->fetchColumn()
        ?: 'draft'
    );

$transitions =
    $this->homepageWorkflowTransitions();

$allowedNext =
    $transitions[
        $currentStatus
    ]
    ?? [];

if (
    !in_array(
        $newStatus,
        $allowedNext,
        true
    )
) {

    $_SESSION['error'] =
        'Workflow transition not allowed: '
        . $currentStatus
        . ' → '
        . $newStatus;

    $this->redirect(
        '/easychair/admin/conference-home/deployment'
    );
}

try {

    $db->beginTransaction();

    $db
    ->prepare("

        UPDATE homepage_deployments

        SET status = ?

        WHERE conference_id = ?

    ")

    ->execute([

        $newStatus,

        (int)$conf['id']

    ]);

    $db
    ->prepare("

        INSERT INTO
        homepage_workflow_history
        (

            conference_id,
            old_status,
            new_status,
            remarks,
            changed_by

        )

        VALUES
        (
            ?, ?, ?, ?, ?
        )

    ")

    ->execute([

        (int)$conf['id'],

        $currentStatus,

        $newStatus,

        'Workflow transition',

        (int)(
            $_SESSION['user_id']
            ?? 0
        )

    ]);

    $db->commit();

    $_SESSION['success'] =
        'Homepage workflow updated';

} catch (\Throwable $e) {

    if (
        $db->inTransaction()
    ) {
        $db->rollBack();
    }

    $_SESSION['error'] =
        $e->getMessage();
}

$this->redirect(
    '/easychair/admin/conference-home/deployment'
);


}


public function releaseNotes()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $conf =
        $this->conference();

    $stmt =
        $db->prepare("

            SELECT *

            FROM homepage_release_notes

            WHERE conference_id = ?

            ORDER BY id DESC

        ");

    $stmt->execute([

        (int)$conf['id']

    ]);

    $notes =
        $stmt->fetchAll(
            \PDO::FETCH_ASSOC
        );

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/release_notes.php';

    $content =
        ob_get_clean();

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

public function versions()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $conf =
        $this->conference();

    $stmt =
        $db->prepare("

            SELECT *

            FROM conference_home_templates

            WHERE org_id = ?

            ORDER BY id DESC

        ");

    $stmt->execute([

        (int)(
            $conf['org_id']
            ??
            $_SESSION['org_id']
            ??
            0
        )

    ]);

    $versions =
        $stmt->fetchAll(
            \PDO::FETCH_ASSOC
        );

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/versions.php';

    $content =
        ob_get_clean();

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

public function activateVersion()
{
    $this->requireAccess();

    $id =
        (int)(
            $_GET['id']
            ?? 0
        );

    $db =
        \App\Core\Database::getInstance();

    $stmt =
        $db->prepare("

            SELECT org_id

            FROM conference_home_templates

            WHERE id = ?

            LIMIT 1

        ");

    $stmt->execute([$id]);

    $row =
        $stmt->fetch(
            \PDO::FETCH_ASSOC
        );

    if (!$row) {

        $_SESSION['error'] =
            'Version not found';

        $this->redirect(
            '/easychair/admin/conference-home/versions'
        );
    }

    $db->prepare("

        UPDATE conference_home_templates

        SET is_active = 0

        WHERE org_id = ?

    ")

    ->execute([

        (int)$row['org_id']

    ]);

    $db->prepare("

        UPDATE conference_home_templates

        SET is_active = 1

        WHERE id = ?

    ")

    ->execute([$id]);

    $_SESSION['success'] =
        'Version activated';

    $this->redirect(
        '/easychair/admin/conference-home/versions'
    );
}

public function cloneVersion()
{
    $this->requireAccess();

    $id =
        (int)(
            $_GET['id']
            ?? 0
        );

    $db =
        \App\Core\Database::getInstance();

    $stmt =
        $db->prepare("

            SELECT *

            FROM conference_home_templates

            WHERE id = ?

            LIMIT 1

        ");

    $stmt->execute([$id]);

    $tpl =
        $stmt->fetch(
            \PDO::FETCH_ASSOC
        );

    if (!$tpl) {

        $_SESSION['error'] =
            'Version not found';

        $this->redirect(
            '/easychair/admin/conference-home/versions'
        );
    }

    $db->prepare("

        INSERT INTO
        conference_home_templates
        (

            name,
            org_id,
            sections_json,
            blocks_json,
            created_by,
            version_no,
            is_favorite,
            status,
            is_active,
            parent_template_id

        )

        VALUES
        (

            ?,?,?,?,?,?,?,?,?,?

        )

    ")

    ->execute([

        $tpl['name']
        . ' (Clone)',

        $tpl['org_id'],

        $tpl['sections_json'],

        $tpl['blocks_json'],

        $_SESSION['user_id'],

        ((int)$tpl['version_no']) + 1,

        0,

        'draft',

        0,

        $tpl['id']

    ]);

    $_SESSION['success'] =
        'Version cloned';

    $this->redirect(
        '/easychair/admin/conference-home/versions'
    );
}

public function branches()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $rows =
        $db->query("

            SELECT

            branch_name,
            COUNT(*) total

            FROM conference_home_templates

            GROUP BY branch_name

            ORDER BY branch_name

        ")

        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/branches.php';

    $content =
        ob_get_clean();

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

private function homepageWorkflowTransitions(): array
{
    return [

        'draft' => [
            'submitted',
            'withdrawn'
        ],

        'submitted' => [
            'screening',
            'withdrawn'
        ],

        'screening' => [
            'under_review',
            'rejected'
        ],

        /*
        --------------------------------------------------
        Track Chair Recommendation Layer
        --------------------------------------------------
        */

        'under_review' => [

            'recommend_revision',

            'recommend_accept',

            'recommend_reject'

        ],

        'recommend_revision' => [

            'revision_required'

        ],

        'recommend_accept' => [

            'accepted'

        ],

        'recommend_reject' => [

            'rejected'

        ],

        /*
        --------------------------------------------------
        Revision Cycle
        --------------------------------------------------
        */

        'revision_required' => [

            'revised',

            'withdrawn'

        ],

        'revised' => [

            'under_review'

        ],

        /*
        --------------------------------------------------
        Editorial Production
        --------------------------------------------------
        */

        'accepted' => [

            'production'

        ],

        'production' => [

            'galley'

        ],

        'galley' => [

            'assigned_to_issue'

        ],

        'assigned_to_issue' => [

            'published'

        ],

        /*
        --------------------------------------------------
        Terminal States
        --------------------------------------------------
        */

        'published' => [

            'archived'

        ],

        'rejected' => [],

        'withdrawn' => [],

        'archived' => []

    ];
}

private function canManageHomepageWorkflow(
    string $status
): bool
{
    $role =
        strtolower(
            (string)(
                $_SESSION['role']
                ?? ''
            )
        );

    if (
        in_array(
            $role,
            [
                'superadmin',
                'super_admin'
            ],
            true
        )
    ) {
        return true;
    }

    if (
        $role ===
        'conference_chair'
    ) {
        return true;
    }

    if (
        $role ===
        'track_chair'
    ) {

        return in_array(
            $status,
            [
                'under_review',
                'revision_required'
            ],
            true
        );
    }

    return false;
}

public function workflowInbox()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $role =
        strtolower(
            (string)(
                $_SESSION['role']
                ?? ''
            )
        );

    $sql = "

        SELECT

            c.id,

            c.short_name,

            d.status

        FROM conferences c

        INNER JOIN homepage_deployments d
            ON d.conference_id = c.id

    ";

    $rows =
        $db
        ->query($sql)
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    $items = [];

    foreach ($rows as $row) {

        $status =
            strtolower(
                (string)$row['status']
            );

        $action = null;

        if (
            $role ===
            'track_chair'
        ) {

            if (
                $status ===
                'under_review'
            ) {

                $action =
                    'Recommendation Required';
            }

        }
        else {

            if (
                in_array(
                    $status,
                    [
                        'recommend_accept',
                        'recommend_revision',
                        'recommend_reject'
                    ],
                    true
                )
            ) {

                $action =
                    'Final Decision Required';
            }
        }

        if ($action) {

            $items[] = [

                'conference_name' =>
                    $row['short_name'],

                'status' =>
                    $status,

                'action_required' =>
                    $action

            ];
        }
    }

$workflowNotifications =
    $this->homepageWorkflowNotifications();

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/workflow_inbox.php';

    $content =
        ob_get_clean();

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

private function homepageWorkflowNotifications(): array
{
    $db =
        \App\Core\Database::getInstance();

    $role =
        strtolower(
            (string)(
                $_SESSION['role']
                ?? ''
            )
        );

    $notifications = [];

    $rows =
        $db
        ->query("

            SELECT

                c.short_name,

                d.status

            FROM homepage_deployments d

            INNER JOIN conferences c
                ON c.id = d.conference_id

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    foreach($rows as $row)
    {
        $status =
            strtolower(
                (string)$row['status']
            );

        if(
            $role === 'track_chair'
            &&
            $status === 'under_review'
        )
        {
            $notifications[] = [

                'title' =>
                    'Recommendation Required',

                'message' =>
                    $row['short_name']
                    . ' is awaiting recommendation.'

            ];
        }

        if(
            in_array(
                $role,
                [
                    'conference_chair',
                    'super_admin',
                    'superadmin'
                ],
                true
            )
        )
        {
            if(
                in_array(
                    $status,
                    [
                        'recommend_accept',
                        'recommend_revision',
                        'recommend_reject'
                    ],
                    true
                )
            )
            {
                $notifications[] = [

                    'title' =>
                        'Final Decision Required',

                    'message' =>
                        $row['short_name']
                        . ' requires final workflow approval.'

                ];
            }
        }
    }

    return $notifications;
}

private function homepageWorkflowStats(): array
{
    $db =
        \App\Core\Database::getInstance();

    $stats = [

        'recommendations' => 0,
        'decisions'       => 0,
        'published'       => 0,
        'archived'        => 0

    ];

    $rows =
        $db
        ->query("

            SELECT status

            FROM homepage_deployments

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    foreach($rows as $row)
    {
        $status =
            strtolower(
                (string)$row['status']
            );

        if(
            in_array(
                $status,
                [
                    'under_review'
                ],
                true
            )
        ) {
            $stats['recommendations']++;
        }

        if(
            in_array(
                $status,
                [
                    'recommend_accept',
                    'recommend_revision',
                    'recommend_reject'
                ],
                true
            )
        ) {
            $stats['decisions']++;
        }

        if(
            $status === 'published'
        ) {
            $stats['published']++;
        }

        if(
            $status === 'archived'
        ) {
            $stats['archived']++;
        }
    }

    return $stats;
}

public function workflowKpiCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $kpis = [

        [
            'label' => 'Published',
            'value' => 0
        ],

        [
            'label' => 'Accepted',
            'value' => 0
        ],

        [
            'label' => 'Rejected',
            'value' => 0
        ],

        [
            'label' => 'Withdrawn',
            'value' => 0
        ]

    ];

    $rows =
        $db
        ->query("

            SELECT status

            FROM homepage_deployments

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    foreach($rows as $row)
    {
        $status =
            strtolower(
                (string)$row['status']
            );

        if($status === 'published')
            $kpis[0]['value']++;

        if($status === 'accepted')
            $kpis[1]['value']++;

        if($status === 'rejected')
            $kpis[2]['value']++;

        if($status === 'withdrawn')
            $kpis[3]['value']++;
    }

    $stmt =
        $db->query("

            SELECT

                c.short_name,
                d.status,
                d.created_at

            FROM homepage_deployments d

            INNER JOIN conferences c
                ON c.id = d.conference_id

            WHERE d.status IN
            (
                'under_review',
                'recommend_accept',
                'production',
                'galley'
            )

        ");

    $bottlenecks =
        $stmt->fetchAll(
            \PDO::FETCH_ASSOC
        );

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/workflow_kpi_center.php';

    $content =
        ob_get_clean();

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

public function approvalQueue()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $role =
        strtolower(
            (string)(
                $_SESSION['role']
                ?? ''
            )
        );

    $rows =
        $db
        ->query("

            SELECT

                c.short_name,
                d.status

            FROM homepage_deployments d

            INNER JOIN conferences c
                ON c.id = d.conference_id

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    $queue = [];

    foreach($rows as $row)
    {
        $status =
            strtolower(
                (string)$row['status']
            );

        $actions = [];

        if(
            $role === 'track_chair'
            &&
            $status === 'under_review'
        )
        {
            $actions[] = [
                'label'=>'Recommend Accept',
                'status'=>'recommend_accept',
                'class'=>'btn-success'
            ];

            $actions[] = [
                'label'=>'Recommend Revision',
                'status'=>'recommend_revision',
                'class'=>'btn-warning'
            ];

            $actions[] = [
                'label'=>'Recommend Reject',
                'status'=>'recommend_reject',
                'class'=>'btn-danger'
            ];
        }

        if(
            in_array(
                $role,
                [
                    'conference_chair',
                    'super_admin',
                    'superadmin'
                ],
                true
            )
        )
        {
            if($status==='recommend_accept')
            {
                $actions[] = [
                    'label'=>'Accept',
                    'status'=>'accepted',
                    'class'=>'btn-success'
                ];
            }

            if($status==='recommend_revision')
            {
                $actions[] = [
                    'label'=>'Request Revision',
                    'status'=>'revision_required',
                    'class'=>'btn-warning'
                ];
            }

            if($status==='recommend_reject')
            {
                $actions[] = [
                    'label'=>'Reject',
                    'status'=>'rejected',
                    'class'=>'btn-danger'
                ];
            }
        }

        if(!empty($actions))
        {
            $queue[] = [

                'conference' =>
                    $row['short_name'],

                'status' =>
                    $status,

                'actions' =>
                    $actions

            ];
        }
    }

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/approval_queue.php';

    $content =
        ob_get_clean();

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

public function slaCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $sla = [

        'submitted' => 3,
        'screening' => 3,
        'under_review' => 14,

        'recommend_accept' => 7,
        'recommend_revision' => 7,
        'recommend_reject' => 7,

        'production' => 5,
        'galley' => 3,
        'assigned_to_issue' => 3

    ];

    $rows =
        $db
        ->query("

            SELECT

                c.short_name,
                d.status,
                d.created_at

            FROM homepage_deployments d

            INNER JOIN conferences c
                ON c.id = d.conference_id

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    $violations = [];

    foreach($rows as $row)
    {
        $status =
            strtolower(
                (string)$row['status']
            );

        if(
            !isset($sla[$status])
        ) {
            continue;
        }

        $days =
            floor(
                (
                    time()
                    -
                    strtotime(
                        $row['created_at']
                    )
                )
                / 86400
            );

        if(
            $days <=
            $sla[$status]
        ) {
            continue;
        }

        $severity =
            'Medium';

        $class =
            'warning';

        if(
            $days >
            ($sla[$status] * 2)
        ) {

            $severity =
                'Critical';

            $class =
                'danger';
        }

        $violations[] = [

            'conference' =>
                $row['short_name'],

            'status' =>
                $status,

            'days' =>
                $days,

            'sla' =>
                $sla[$status],

            'severity' =>
                $severity,

            'class' =>
                $class

        ];
    }

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/sla_center.php';

    $content =
        ob_get_clean();

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

public function automationCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $rules =
        $db
        ->query("

            SELECT *

            FROM homepage_workflow_rules

            ORDER BY id

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/automation_center.php';

    $content =
        ob_get_clean();

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

public function automationRunner()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    /*
    ------------------------------------
    Evaluate rules
    ------------------------------------
    */

    $rules =
        $db
        ->query("
            SELECT *
            FROM homepage_workflow_rules
            WHERE is_active=1
        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    foreach($rules as $rule)
    {
        $rows =
            $db
            ->prepare("
                SELECT
                    d.conference_id,
                    d.status,
                    d.created_at
                FROM homepage_deployments d
                WHERE d.status=?
            ");

        $rows->execute([
            $rule['target_status']
        ]);

        foreach(
            $rows->fetchAll(\PDO::FETCH_ASSOC)
            as $deployment
        )
        {
            $days =
                floor(
                    (
                        time()
                        -
                        strtotime(
                            $deployment['created_at']
                        )
                    ) / 86400
                );

            if(
                $days <
                (int)$rule['threshold_days']
            ) {
                continue;
            }

            $exists =
                $db
                ->prepare("
                    SELECT id
                    FROM homepage_workflow_alerts
                    WHERE conference_id=?
                    AND rule_id=?
                    AND is_resolved=0
                    LIMIT 1
                ");

            $exists->execute([
                $deployment['conference_id'],
                $rule['id']
            ]);

            if(
                $exists->fetch()
            ) {
                continue;
            }

            $db
            ->prepare("
                INSERT INTO
                homepage_workflow_alerts
                (
                    conference_id,
                    rule_id,
                    status,
                    severity,
                    message
                )
                VALUES
                (
                    ?,?,?,?,?
                )
            ")
            ->execute([

                $deployment['conference_id'],

                $rule['id'],

                $deployment['status'],

                'warning',

                'Workflow SLA exceeded'

            ]);
        }
    }

    $alerts =
        $db
        ->query("
            SELECT

                a.*,

                c.short_name AS conference_name,

                r.rule_name

            FROM homepage_workflow_alerts a

            INNER JOIN conferences c
                ON c.id=a.conference_id

            INNER JOIN homepage_workflow_rules r
                ON r.id=a.rule_id

            ORDER BY a.id DESC

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/automation_runner.php';

    $content =
        ob_get_clean();

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

public function resolveWorkflowAlert()
{
    $this->requireAccess();

    $alertId =
        (int)(
            $_POST['alert_id']
            ?? 0
        );

    if ($alertId <= 0) {

        $_SESSION['error'] =
            'Invalid alert';

        $this->redirect(
            '/easychair/admin/conference-home/automation-runner'
        );
    }

    $db =
        \App\Core\Database::getInstance();

    $db
    ->prepare("

        UPDATE
        homepage_workflow_alerts

        SET

            is_resolved = 1,

            resolved_by = ?,

            resolved_at = NOW()

        WHERE id = ?

    ")
    ->execute([

        (int)(
            $_SESSION['user_id']
            ?? 0
        ),

        $alertId

    ]);

    $_SESSION['success'] =
        'Alert resolved';

    $this->redirect(
        '/easychair/admin/conference-home/automation-runner'
    );
}

public function resolveAllWorkflowAlerts()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $db
    ->prepare("

        UPDATE
        homepage_workflow_alerts

        SET

            is_resolved = 1,

            resolved_by = ?,

            resolved_at = NOW()

        WHERE is_resolved = 0

    ")
    ->execute([

        (int)(
            $_SESSION['user_id']
            ?? 0
        )

    ]);

    $_SESSION['success'] =
        'All alerts resolved';

    $this->redirect(
        '/easychair/admin/conference-home/automation-runner'
    );
}

	public function workflowAlertHistory()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $history =
        $db
        ->query("

            SELECT *

            FROM homepage_workflow_alerts

            WHERE is_resolved = 1

            ORDER BY resolved_at DESC

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/alert_history.php';

    $content =
        ob_get_clean();

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

public function workflowTimeline()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $timelineRows =
        $db
        ->query("

            SELECT

                h.*,

                c.short_name
                AS conference_name,

                COALESCE(
                    u.first_name,
                    u.last_name,
                    CONCAT('User #', h.changed_by)
                )
                AS user_name

            FROM homepage_workflow_history h

            INNER JOIN conferences c
                ON c.id = h.conference_id

            LEFT JOIN users u
                ON u.id = h.changed_by

            ORDER BY
                c.short_name,
                h.created_at ASC

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/timeline_center.php';

    $content =
        ob_get_clean();

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

public function workflowDurationAnalytics()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $history =
        $db
        ->query("

            SELECT

                h.*,

                c.short_name AS conference_name,

                COALESCE(
                    u.first_name,
                    u.last_name,
                    u.email,
                    CONCAT('User #', h.changed_by)
                ) AS changed_by_name

            FROM homepage_workflow_history h

            INNER JOIN conferences c
                ON c.id = h.conference_id

            LEFT JOIN users u
                ON u.id = h.changed_by

            ORDER BY
                h.conference_id ASC,
                h.created_at ASC,
                h.id ASC

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    $durationRows =
        [];

    $conferenceBuckets =
        [];

    $previousByConference =
        [];

    foreach ($history as $row) {

        $conferenceId =
            (int)$row['conference_id'];

        if (
            isset(
                $previousByConference[$conferenceId]
            )
        ) {

            $previous =
                $previousByConference[$conferenceId];

            $start =
                strtotime(
                    (string)$previous['created_at']
                );

            $end =
                strtotime(
                    (string)$row['created_at']
                );

            $minutes =
                0;

            if (
                $start
                &&
                $end
                &&
                $end >= $start
            ) {
                $minutes =
                    (int)floor(
                        ($end - $start) / 60
                    );
            }

            $durationRows[] =
                [

                    'conference_id' =>
                        $conferenceId,

                    'conference_name' =>
                        $row['conference_name'],

                    'from_status' =>
                        $previous['new_status'],

                    'to_status' =>
                        $row['new_status'],

                    'started_at' =>
                        $previous['created_at'],

                    'ended_at' =>
                        $row['created_at'],

                    'minutes' =>
                        $minutes,

                    'changed_by_name' =>
                        $row['changed_by_name']

                ];

            if (
                !isset(
                    $conferenceBuckets[$conferenceId]
                )
            ) {
                $conferenceBuckets[$conferenceId] =
                    [

                        'conference_name' =>
                            $row['conference_name'],

                        'total_minutes' =>
                            0,

                        'transitions' =>
                            0

                    ];
            }

            $conferenceBuckets[$conferenceId]['total_minutes'] +=
                $minutes;

            $conferenceBuckets[$conferenceId]['transitions']++;
        }

        $previousByConference[$conferenceId] =
            $row;
    }

    $minutesList =
        array_column(
            $durationRows,
            'minutes'
        );

    $summary =
        [

            'total_transitions' =>
                count($durationRows),

            'avg_minutes' =>
                !empty($minutesList)
                    ? round(
                        array_sum($minutesList)
                        /
                        max(1, count($minutesList))
                    )
                    : 0,

            'fastest_minutes' =>
                !empty($minutesList)
                    ? min($minutesList)
                    : 0,

            'slowest_minutes' =>
                !empty($minutesList)
                    ? max($minutesList)
                    : 0

        ];

    $conferenceRanking =
        array_values(
            $conferenceBuckets
        );

    usort(
        $conferenceRanking,
        function ($a, $b) {
            return
                ($b['total_minutes'] ?? 0)
                <=>
                ($a['total_minutes'] ?? 0);
        }
    );

    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/workflow_duration_analytics.php';

    $content =
        ob_get_clean();

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

public function workflowHeatmap()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $heatmap =
        $db
        ->query("

            SELECT

                status,

                COUNT(*) AS total

            FROM homepage_deployments

            GROUP BY status

            ORDER BY total DESC

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/workflow_heatmap.php';

    $content =
        ob_get_clean();

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

public function executiveDashboard()
{
    $this->requireAccess();
     $this->verifyWorkflowOwnership();

    $db =
        \App\Core\Database::getInstance();

    $summaryCards = [

        [
            'label' => 'Homepages',
            'value' => 0
        ],

        [
            'label' => 'Published',
            'value' => 0
        ],

        [
            'label' => 'Under Review',
            'value' => 0
        ],

        [
            'label' => 'Production',
            'value' => 0
        ]

    ];

    $rows =
        $db
        ->query("
            SELECT status
            FROM homepage_deployments
        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    $summaryCards[0]['value'] =
        count($rows);

    foreach($rows as $row)
    {
        $status =
            strtolower(
                (string)$row['status']
            );

        if($status==='published')
        {
            $summaryCards[1]['value']++;
        }

        if($status==='under_review')
        {
            $summaryCards[2]['value']++;
        }

        if($status==='production')
        {
            $summaryCards[3]['value']++;
        }
    }

    $alerts =
        $db
        ->query("
            SELECT

                a.*,

                c.short_name

            FROM homepage_workflow_alerts a

            INNER JOIN conferences c
                ON c.id=a.conference_id

            WHERE a.is_resolved=0

            ORDER BY a.id DESC

            LIMIT 10
        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    $distribution =
        $db
        ->query("
            SELECT
                status,
                COUNT(*) total
            FROM homepage_deployments
            GROUP BY status
            ORDER BY total DESC
        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/executive_dashboard.php';

    $content =
        ob_get_clean();

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

public function decisionBoard()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $rows =
        $db
        ->query("

            SELECT

                d.conference_id,

                d.status,

                d.created_at AS updated_at,

                c.short_name AS conference_name,

                COALESCE(
                    u.first_name,
                    u.last_name,
                    u.email,
                    'Unassigned'
                ) AS chair_name

            FROM homepage_deployments d

            INNER JOIN conferences c
                ON c.id = d.conference_id

            LEFT JOIN users u
                ON u.id = c.chair_user_id

            ORDER BY c.short_name

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    $transitions =
        $this->homepageWorkflowTransitions();

    foreach($rows as &$row)
    {
        $row['allowed_actions'] =
            $transitions[
                $row['status']
            ]
            ?? [];
    }

    unset($row);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/decision_board.php';

    $content =
        ob_get_clean();

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

public function updateDecisionBoard()
{
    $this->requireAccess();

    $_POST['status'] =
        trim(
            $_POST['status']
            ?? ''
        );

    $_POST['conference_id'] =
        (int)(
            $_POST['conference_id']
            ?? 0
        );

    $conferenceId =
        $_POST['conference_id'];

    $newStatus =
        $_POST['status'];

    $db =
        \App\Core\Database::getInstance();

    $stmt =
        $db->prepare("

            SELECT status

            FROM homepage_deployments

            WHERE conference_id=?

            LIMIT 1

        ");

    $stmt->execute([
        $conferenceId
    ]);

$this->syncHomepageWorkflowOwnership(
    $conferenceId,
    $newStatus
);

    $currentStatus =
        (string)(
            $stmt->fetchColumn()
            ?: 'draft'
        );

    $allowed =
        $this->homepageWorkflowTransitions()[
            $currentStatus
        ]
        ?? [];

    if(
        !in_array(
            $newStatus,
            $allowed,
            true
        )
    )
    {
        $_SESSION['error'] =
            'Transition not allowed';

        $this->redirect(
            '/easychair/admin/conference-home/decision-board'
        );
    }

    $db->beginTransaction();

    try {

        $db
        ->prepare("

            UPDATE
            homepage_deployments

            SET status=?

            WHERE conference_id=?

        ")
        ->execute([
            $newStatus,
            $conferenceId
        ]);

        $db
        ->prepare("

            INSERT INTO
            homepage_workflow_history
            (
                conference_id,
                old_status,
                new_status,
                remarks,
                changed_by
            )

            VALUES
            (
                ?,?,?,?,?
            )

        ")
        ->execute([

            $conferenceId,

            $currentStatus,

            $newStatus,

            'Decision Board',

            (int)(
                $_SESSION['user_id']
                ?? 0
            )

        ]);

        $db->commit();

        $_SESSION['success'] =
            'Decision applied successfully';

    }
    catch(\Throwable $e)
    {
        $db->rollBack();

        $_SESSION['error'] =
            $e->getMessage();
    }

    $this->redirect(
        '/easychair/admin/conference-home/decision-board'
    );
}

public function operationsCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $statusCards =
        $db
        ->query("

            SELECT

                status,

                COUNT(*) AS total,

                MAX(
                    TIMESTAMPDIFF(
                        DAY,
                        created_at,
                        NOW()
                    )
                ) AS oldest_days

            FROM homepage_deployments

            GROUP BY status

            ORDER BY total DESC

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/operations_center.php';

    $content =
        ob_get_clean();

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

public function ownershipCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $ownershipRows =
        $db
        ->query("

            SELECT

                c.short_name
                AS conference_name,

                COALESCE(d.status, a.status, 'draft')
                AS status,

                a.assigned_role
                AS assigned_role,

                TIMESTAMPDIFF(
                    DAY,
                    a.assigned_at,
                    NOW()
                )
                AS days_waiting,

                COALESCE(

                    NULLIF(
                        TRIM(
                            CONCAT(
                                COALESCE(u.first_name,''),
                                ' ',
                                COALESCE(u.last_name,'')
                            )
                        ),
                        ''
                    ),

                    u.email,

                    CONCAT(
                        'User #',
                        a.assigned_user_id
                    )

                )
                AS owner_name

            FROM homepage_workflow_assignments a

            INNER JOIN conferences c
                ON c.id = a.conference_id

            LEFT JOIN homepage_deployments d
                ON d.conference_id = a.conference_id

            LEFT JOIN users u
                ON u.id = a.assigned_user_id

            WHERE COALESCE(a.is_active,1) = 1

            ORDER BY
                days_waiting DESC,
                c.short_name ASC

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    foreach ($ownershipRows as &$row) {

        if (
            ($row['assigned_role'] ?? '')
            ===
            'track_chair'
        ) {
            $row['escalation_target'] =
                'Conference Chair';
        } else {
            $row['escalation_target'] =
                'Super Admin';
        }
    }

    unset($row);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/ownership_center.php';

    $content =
        ob_get_clean();

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

private function homepageWorkflowOwnerRole(
    string $status
): string
{
    switch ($status)
    {
        case 'under_review':
        case 'revision_required':
        case 'revised':

            return 'track_chair';

        default:

            return 'conference_chair';
    }
}

private function syncHomepageWorkflowOwnership(
    int $conferenceId,
    string $status
): void
{
    $db =
        \App\Core\Database::getInstance();

    $role =
        $this->homepageWorkflowOwnerRole(
            $status
        );

    $db
    ->prepare("

        UPDATE
        homepage_workflow_assignments

        SET is_active = 0

        WHERE conference_id = ?

    ")
    ->execute([
        $conferenceId
    ]);

    if (
        $role ===
        'conference_chair'
    )
    {
        $stmt =
            $db->prepare("

                SELECT
                user_id

                FROM conference_user_roles

                WHERE conference_id = ?
                AND role_code='conference_chair'

            ");

        $stmt->execute([
            $conferenceId
        ]);

        $users =
            $stmt->fetchAll(
                \PDO::FETCH_COLUMN
            );
    }
    else
    {
        $stmt =
            $db->prepare("

                SELECT
                user_id

                FROM conference_user_roles

                WHERE conference_id = ?
                AND role_code='track_chair'

            ");

        $stmt->execute([
            $conferenceId
        ]);

        $users =
            $stmt->fetchAll(
                \PDO::FETCH_COLUMN
            );
    }

    foreach($users as $userId)
    {
        $db
        ->prepare("

            INSERT INTO
            homepage_workflow_assignments
            (

                conference_id,
                status,
                assigned_role,
                assigned_user_id,
                assigned_by,
                assigned_at,
                is_active

            )

            VALUES
            (
                ?,?,?,?,?,NOW(),1
            )

        ")
        ->execute([

            $conferenceId,

            $status,

            $role,

            (int)$userId,

            (int)(
                $_SESSION['user_id']
                ?? 0
            )

        ]);
    }
}

private function runHomepageEscalationEngine(): void
{
    $db =
        \App\Core\Database::getInstance();

    $rows =
        $db
        ->query("

            SELECT

                a.conference_id,
                a.status,
                a.assigned_role,
                a.assigned_user_id,
                a.assigned_at,

                TIMESTAMPDIFF(
                    DAY,
                    a.assigned_at,
                    NOW()
                ) AS days_waiting

            FROM homepage_workflow_assignments a

            WHERE a.is_active = 1

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    foreach($rows as $row)
    {
        $days =
            (int)$row['days_waiting'];

        if($days < 7)
        {
            continue;
        }

        $status =
            (string)$row['status'];

        $role =
            (string)$row['assigned_role'];

        $severity =
            'warning';

        $message =
            'Workflow escalation: '
            .
            $status
            .
            ' waiting '
            .
            $days
            .
            ' days';

        if(
            in_array(
                $status,
                [
                    'under_review',
                    'revision_required',
                    'revised'
                ],
                true
            )
        )
        {
            $message .=
                ' (Track Chair → Conference Chair)';
        }
        else
        {
            $message .=
                ' (Conference Chair → Super Admin)';
        }

        $stmt =
            $db->prepare("

                SELECT COUNT(*)

                FROM homepage_workflow_alerts

                WHERE conference_id=?
                AND message=?
                AND is_resolved=0

            ");

        $stmt->execute([
            (int)$row['conference_id'],
            $message
        ]);

        if(
            (int)$stmt->fetchColumn()
            > 0
        )
        {
            continue;
        }

        $db
        ->prepare("

            INSERT INTO
            homepage_workflow_alerts
            (

                conference_id,
                severity,
                message,
                is_resolved

            )

            VALUES
            (
                ?,?,?,0
            )

        ")
        ->execute([

            (int)$row['conference_id'],

            $severity,

            $message

        ]);
    }
}

public function runEscalationMatrix()
{
    $this->requireAccess();

    $this->runHomepageEscalationEngine();

    $_SESSION['success'] =
        'Escalation engine executed';

    $this->redirect(
        '/easychair/admin/conference-home/executive-dashboard'
    );
}

private function verifyWorkflowOwnership(): void
{
    $db =
        \App\Core\Database::getInstance();

    $rows =
        $db
        ->query("

            SELECT
                conference_id,
                status
            FROM homepage_deployments

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    foreach ($rows as $row)
    {
        $stmt =
            $db->prepare("

                SELECT COUNT(*)

                FROM homepage_workflow_assignments

                WHERE conference_id = ?
                AND is_active = 1

            ");

        $stmt->execute([
            (int)$row['conference_id']
        ]);

        if (
            (int)$stmt->fetchColumn() > 0
        ) {
            continue;
        }

        $this->syncHomepageWorkflowOwnership(
            (int)$row['conference_id'],
            (string)$row['status']
        );
    }
}

public function automationScheduler()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $runs =
        $db
        ->query("

            SELECT *

            FROM homepage_automation_runs

            ORDER BY id DESC

            LIMIT 50

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/automation_scheduler.php';

    $content =
        ob_get_clean();

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

public function runAllAutomation()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $db
    ->prepare("

        INSERT INTO
        homepage_automation_runs
        (
            job_name,
            run_by
        )

        VALUES
        (
            'run_all_automation',
            ?
        )

    ")
    ->execute([
        (int)(
            $_SESSION['user_id']
            ?? 0
        )
    ]);

    $runId =
        (int)$db->lastInsertId();

    try {

        $this->verifyWorkflowOwnership();

        $this->runHomepageEscalationEngine();

        $db
        ->prepare("

            UPDATE
            homepage_automation_runs

            SET

                completed_at = NOW(),

                status = 'success'

            WHERE id = ?

        ")
        ->execute([
            $runId
        ]);

        $_SESSION['success'] =
            'Automation completed successfully';

    }
    catch(\Throwable $e)
    {
        $db
        ->prepare("

            UPDATE
            homepage_automation_runs

            SET

                completed_at = NOW(),

                status='failed',

                notes=?

            WHERE id=?

        ")
        ->execute([
            $e->getMessage(),
            $runId
        ]);

        $_SESSION['error'] =
            $e->getMessage();
    }

    $this->redirect(
        '/easychair/admin/conference-home/automation-scheduler'
    );
}

public function cronLogs()
{
    $this->requireAccess();

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/cron_logs.php';

    $content =
        ob_get_clean();

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

public function governanceCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $cards = [];

    $cards[] = [

        'label' => 'Deployments',

        'value' => (int)$db
            ->query("
                SELECT COUNT(*)
                FROM homepage_deployments
            ")
            ->fetchColumn()

    ];

    $cards[] = [

        'label' => 'Active Owners',

        'value' => (int)$db
            ->query("
                SELECT COUNT(*)
                FROM homepage_workflow_assignments
                WHERE is_active=1
            ")
            ->fetchColumn()

    ];

    $cards[] = [

        'label' => 'Open Alerts',

        'value' => (int)$db
            ->query("
                SELECT COUNT(*)
                FROM homepage_workflow_alerts
                WHERE is_resolved=0
            ")
            ->fetchColumn()

    ];

    $cards[] = [

        'label' => 'Automation Runs',

        'value' => (int)$db
            ->query("
                SELECT COUNT(*)
                FROM homepage_automation_runs
            ")
            ->fetchColumn()

    ];

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/governance_center.php';

    $content =
        ob_get_clean();

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

public function governanceAnalytics()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $forecastCards = [];

    $forecastCards[] = [

        'label' => 'Active Escalations',

        'value' => (int)$db
            ->query("

                SELECT COUNT(*)

                FROM homepage_workflow_alerts

                WHERE is_resolved = 0

            ")
            ->fetchColumn()

    ];

    $forecastCards[] = [

        'label' => 'Active Owners',

        'value' => (int)$db
            ->query("

                SELECT COUNT(*)

                FROM homepage_workflow_assignments

                WHERE is_active = 1

            ")
            ->fetchColumn()

    ];

    $forecastCards[] = [

        'label' => 'Workflow Events',

        'value' => (int)$db
            ->query("

                SELECT COUNT(*)

                FROM homepage_workflow_history

            ")
            ->fetchColumn()

    ];

    $forecastCards[] = [

        'label' => 'Automation Runs',

        'value' => (int)$db
            ->query("

                SELECT COUNT(*)

                FROM homepage_automation_runs

            ")
            ->fetchColumn()

    ];

    $conferenceScores =
        $db
        ->query("

            SELECT

                c.short_name
                AS conference_name,

                COUNT(
                    DISTINCT a.assigned_user_id
                ) AS owners,

                (

                    SELECT COUNT(*)

                    FROM homepage_workflow_alerts x

                    WHERE x.conference_id = c.id

                ) AS escalations

            FROM conferences c

            LEFT JOIN homepage_workflow_assignments a
                ON a.conference_id = c.id
               AND a.is_active = 1

            GROUP BY
                c.id,
                c.short_name

            ORDER BY
                c.short_name

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    foreach($conferenceScores as &$row)
    {
        $row['governance_score'] =
            max(
                0,
                100
                -
                (
                    ((int)$row['escalations'])
                    * 10
                )
            );
    }

    unset($row);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/governance_analytics.php';

    $content =
        ob_get_clean();

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

public function workloadCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $workloadRows =
        $db
        ->query("

            SELECT

                a.assigned_role,

                a.assigned_user_id,

                COUNT(
                    DISTINCT a.conference_id
                ) AS assigned_conferences,

                COUNT(*) AS open_stages,

                SUM(

                    CASE

                        WHEN

                            TIMESTAMPDIFF(
                                DAY,
                                a.assigned_at,
                                NOW()
                            ) > 7

                        THEN 1

                        ELSE 0

                    END

                ) AS overdue_count,

                COALESCE(

                    NULLIF(

                        TRIM(

                            CONCAT(

                                COALESCE(
                                    u.first_name,
                                    ''
                                ),

                                ' ',

                                COALESCE(
                                    u.last_name,
                                    ''
                                )

                            )

                        ),

                        ''

                    ),

                    u.email,

                    CONCAT(
                        'User #',
                        a.assigned_user_id
                    )

                ) AS user_name

            FROM homepage_workflow_assignments a

            LEFT JOIN users u
                ON u.id =
                   a.assigned_user_id

            WHERE a.is_active = 1

            GROUP BY

                a.assigned_role,
                a.assigned_user_id

            ORDER BY

                overdue_count DESC,
                open_stages DESC

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    foreach($workloadRows as &$row)
    {
        $row['workload_score'] =

            ((int)$row['open_stages'])

            +

            (
                ((int)$row['overdue_count'])
                * 2
            );
    }

    unset($row);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/workload_center.php';

    $content =
        ob_get_clean();

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

public function governanceIntelligence()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $alerts =
        (int)$db
        ->query("
            SELECT COUNT(*)
            FROM homepage_workflow_alerts
            WHERE is_resolved=0
        ")
        ->fetchColumn();

    $owners =
        (int)$db
        ->query("
            SELECT COUNT(*)
            FROM homepage_workflow_assignments
            WHERE is_active=1
        ")
        ->fetchColumn();

    $history =
        (int)$db
        ->query("
            SELECT COUNT(*)
            FROM homepage_workflow_history
        ")
        ->fetchColumn();

    $deployments =
        (int)$db
        ->query("
            SELECT COUNT(*)
            FROM homepage_deployments
        ")
        ->fetchColumn();

    $metrics = [

        [
            'label'=>'Conference Health Index',
            'value'=>max(
                0,
                100 - ($alerts * 10)
            )
        ],

        [
            'label'=>'Governance Risk Index',
            'value'=>min(
                100,
                $alerts * 10
            )
        ],

        [
            'label'=>'Ownership Stability',
            'value'=>min(
                100,
                $owners * 10
            )
        ],

        [
            'label'=>'Workflow Activity',
            'value'=>min(
                100,
                $history * 5
            )
        ],

        [
            'label'=>'Deployments',
            'value'=>$deployments
        ]

    ];

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/governance_intelligence.php';

    $content =
        ob_get_clean();

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

public function performanceCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $rows =
        $db
        ->query("

            SELECT

                a.assigned_role,

                COALESCE(

                    NULLIF(
                        TRIM(
                            CONCAT(
                                COALESCE(u.first_name,''),
                                ' ',
                                COALESCE(u.last_name,'')
                            )
                        ),
                        ''
                    ),

                    u.email,

                    CONCAT(
                        'User #',
                        a.assigned_user_id
                    )

                ) AS user_name,

                COUNT(*) AS assignments,

                SUM(

                    CASE

                        WHEN TIMESTAMPDIFF(
                            DAY,
                            a.assigned_at,
                            NOW()
                        ) > 7

                        THEN 1

                        ELSE 0

                    END

                ) AS overdue

            FROM homepage_workflow_assignments a

            LEFT JOIN users u
            ON u.id = a.assigned_user_id

            WHERE a.is_active = 1

            GROUP BY
                a.assigned_role,
                a.assigned_user_id

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    foreach($rows as &$row)
    {
        $row['score'] =
            max(
                0,
                100 -
                (
                    ((int)$row['overdue']) * 10
                )
            );
    }

    unset($row);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/performance_center.php';

    $content =
        ob_get_clean();

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

public function workflowHistory()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $history =
        $db
        ->query("

            SELECT
                h.*,
                COALESCE(
                    CONCAT(
                        u.first_name,
                        ' ',
                        u.last_name
                    ),
                    u.email
                ) AS changed_by_name

            FROM homepage_workflow_history h

            LEFT JOIN users u
                ON u.id = h.changed_by

            ORDER BY h.id DESC

            LIMIT 500

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/workflow_history.php';

    $content =
        ob_get_clean();

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

public function alertCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $alerts =
        $db
        ->query("

            SELECT *

            FROM homepage_workflow_alerts

            ORDER BY
                is_resolved ASC,
                id DESC

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/alert_center.php';

    $content =
        ob_get_clean();

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

public function escalationCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $rows =
        $db
        ->query("

            SELECT

                e.*,

                COALESCE(

                    NULLIF(

                        TRIM(

                            CONCAT(

                                COALESCE(
                                    u.first_name,
                                    ''
                                ),

                                ' ',

                                COALESCE(
                                    u.last_name,
                                    ''
                                )

                            )

                        ),

                        ''

                    ),

                    u.email,

                    CONCAT(
                        'User #',
                        e.assigned_user_id
                    )

                ) AS user_name

            FROM homepage_workflow_escalations e

            LEFT JOIN users u
                ON u.id =
                   e.assigned_user_id

            ORDER BY

                e.is_resolved ASC,

                e.id DESC

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/escalation_center.php';

    $content =
        ob_get_clean();

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

public function runAutoEscalation()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $alertsCreated = 0;

    $runId = null;

    try {

        $db->beginTransaction();

        $db
        ->prepare("
            INSERT INTO homepage_escalation_runs
            (
                executed_by
            )
            VALUES
            (
                ?
            )
        ")
        ->execute([
            (int)(
                $_SESSION['user_id']
                ?? 0
            )
        ]);

        $runId =
            (int)$db->lastInsertId();

        $deployments =
            $db
            ->query("
                SELECT
                    conference_id,
                    status
                FROM homepage_deployments
            ")
            ->fetchAll(
                \PDO::FETCH_ASSOC
            );

        foreach(
            $deployments
            as $d
        )
        {
            $exists =
                (int)$db
                ->prepare("
                    SELECT COUNT(*)
                    FROM homepage_workflow_alerts
                    WHERE conference_id=?
                    AND status=?
                    AND is_resolved=0
                ");

            $stmt =
                $db->prepare("
                    SELECT COUNT(*)
                    FROM homepage_workflow_alerts
                    WHERE conference_id=?
                    AND status=?
                    AND is_resolved=0
                ");

            $stmt->execute([
                (int)$d['conference_id'],
                (string)$d['status']
            ]);

            $exists =
                (int)$stmt->fetchColumn();

            if($exists>0)
            {
                continue;
            }

            $db
            ->prepare("
                INSERT INTO
                homepage_workflow_alerts
                (
                    conference_id,
                    rule_id,
                    status,
                    severity,
                    message
                )
                VALUES
                (
                    ?,0,?,
                    'low',
                    ?
                )
            ")
            ->execute([

                (int)$d['conference_id'],

                (string)$d['status'],

                'Auto escalation check: '
                . $d['status']

            ]);

            $alertsCreated++;
        }

        $db
        ->prepare("
            UPDATE homepage_escalation_runs
            SET
                alerts_created=?,
                finished_at=NOW()
            WHERE id=?
        ")
        ->execute([
            $alertsCreated,
            $runId
        ]);

        $db->commit();

        $_SESSION['success'] =
            'Auto escalation completed. Alerts created: '
            . $alertsCreated;

    }
    catch(\Throwable $e)
    {
        if(
            $db->inTransaction()
        )
        {
            $db->rollBack();
        }

        $_SESSION['error'] =
            $e->getMessage();
    }

    $this->redirect(
        '/easychair/admin/conference-home/alert-center'
    );
}

public function reviewerSla()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $rows =
        $db
        ->query("

            SELECT

                ra.id,

                ra.status,

                ra.due_date,

                DATEDIFF(
                    CURDATE(),
                    ra.due_date
                ) AS overdue_days,

                CONCAT(
                    COALESCE(u.first_name,''),
                    ' ',
                    COALESCE(u.last_name,'')
                ) reviewer_name,

                s.submission_no,

                s.title

            FROM review_assignments ra

            LEFT JOIN users u
                ON u.id = ra.reviewer_id

            LEFT JOIN submissions s
                ON s.id = ra.submission_id

            WHERE
                ra.status <> 'completed'
                AND ra.due_date < CURDATE()

            ORDER BY
                overdue_days DESC

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/reviewer_sla.php';

    $content =
        ob_get_clean();

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

public function trackOwnership()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $unassignedTracks =
        $db
        ->query("

            SELECT

                t.id,

                t.conference_id,

                COALESCE(
                    t.name_en,
                    t.name_ar
                ) track_name,

                COUNT(s.id) submissions

            FROM tracks t

            LEFT JOIN submissions s
                ON s.track_id=t.id

            WHERE NOT EXISTS
            (
                SELECT 1
                FROM track_chair_assignments a
                WHERE a.track_id=t.id
                AND a.is_active=1
            )

            GROUP BY t.id

            ORDER BY submissions DESC

        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    $duplicateChairs =
        $db
        ->query("

            SELECT

                track_id,

                COUNT(*) active_chairs

            FROM track_chair_assignments

            WHERE is_active=1

            GROUP BY track_id

            HAVING COUNT(*) > 1

        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    $nullTracks =
        $db
        ->query("

            SELECT

                id,
                submission_no,
                title,
                conference_id,
                status

            FROM submissions

            WHERE track_id IS NULL

            ORDER BY id DESC

        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/track_ownership.php';

    $content =
        ob_get_clean();

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

public function governanceOps()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $score =
        (int)$db
        ->query("
            SELECT
            (
                100
                -
                (
                    (SELECT COUNT(*)
                     FROM submissions
                     WHERE track_id IS NULL) * 2
                )
                -
                (
                    (
                    SELECT COUNT(*)
                    FROM tracks t
                    WHERE NOT EXISTS
                    (
                        SELECT 1
                        FROM track_chair_assignments a
                        WHERE a.track_id=t.id
                        AND a.is_active=1
                    )
                    ) * 3
                )
                -
                (
                    (
                    SELECT COUNT(*)
                    FROM
                    (
                        SELECT track_id
                        FROM track_chair_assignments
                        WHERE is_active=1
                        GROUP BY track_id
                        HAVING COUNT(*) > 1
                    ) x
                    ) * 2
                )
            )
        ")
        ->fetchColumn();

    require
    BASE_PATH .
    '/app/views/admin/conference_home/governance_ops.php';
}	

private function governanceIntegrityIssues(): array
{
    $db =
        \App\Core\Database::getInstance();

    return
        $db
        ->query("

            SELECT
                'NULL_TRACKS' issue_type,
                COUNT(*) total
            FROM submissions
            WHERE track_id IS NULL

            UNION ALL

            SELECT
                'NULL_SUBMISSION_NO',
                COUNT(*)
            FROM submissions
            WHERE submission_no IS NULL

            UNION ALL

            SELECT
                'REVIEWS_WITHOUT_DUE_DATE',
                COUNT(*)
            FROM review_assignments
            WHERE due_date IS NULL

            UNION ALL

            SELECT
                'TRACKS_WITHOUT_CHAIRS',
                COUNT(*)
            FROM tracks t
            WHERE NOT EXISTS
            (
                SELECT 1
                FROM track_chair_assignments a
                WHERE a.track_id=t.id
                AND a.is_active=1
            )

            UNION ALL

            SELECT
                'DUPLICATE_TRACK_CHAIRS',
                COUNT(*)
            FROM
            (
                SELECT track_id
                FROM track_chair_assignments
                WHERE is_active=1
                GROUP BY track_id
                HAVING COUNT(*) > 1
            ) x

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );
}

public function selfHealing()
{
    $this->requireAccess();

    $issues =
        $this->governanceIntegrityIssues();

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/self_healing.php';

    $content =
        ob_get_clean();

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

public function selfHealingSubmissionNumbers()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stmt =
        $db->prepare("

            UPDATE submissions

            SET submission_no =
            CONCAT(
                'SUB-',
                conference_id,
                '-',
                LPAD(id,6,'0')
            )

            WHERE submission_no IS NULL

        ");

    $stmt->execute();

    $_SESSION['success'] =
        'Submission number recovery completed. Rows updated: '
        . $stmt->rowCount();

    $this->redirect(
        '/easychair/admin/conference-home/self-healing'
    );
}

public function selfHealingReviewDueDates()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stmt =
        $db->prepare("

            UPDATE review_assignments

            SET due_date =
            DATE(
                DATE_ADD(
                    assigned_at,
                    INTERVAL 21 DAY
                )
            )

            WHERE due_date IS NULL

        ");

    $stmt->execute();

    $_SESSION['success'] =
        'Review due-date recovery completed. Rows updated: '
        . $stmt->rowCount();

    $this->redirect(
        '/easychair/admin/conference-home/self-healing'
    );
}

public function selfHealingScan()
{
    $this->requireAccess();

    $_SESSION['success'] =
        'Integrity scan completed';

    $this->redirect(
        '/easychair/admin/conference-home/self-healing'
    );
}

public function manualTrackAssignment()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $rows =
        $db
        ->query("

            SELECT
                id,
                submission_no,
                conference_id,
                title,
                status
            FROM submissions
            WHERE track_id IS NULL
            ORDER BY id DESC

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    $tracks =
        $db
        ->query("

            SELECT
                id,
                conference_id,
                name_en,
                name_ar
            FROM tracks
            WHERE is_active=1
            ORDER BY conference_id, sort_order, id

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    $tracksByConference = [];

    foreach($tracks as $track)
    {
        $tracksByConference[
            (int)$track['conference_id']
        ][] = $track;
    }

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/manual_track_assignment.php';

    $content =
        ob_get_clean();

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

public function saveManualTrackAssignment()
{
    $this->requireAccess();

    $submissionId =
        (int)(
            $_POST['submission_id']
            ?? 0
        );

    $trackId =
        (int)(
            $_POST['track_id']
            ?? 0
        );

    if($submissionId <= 0 || $trackId <= 0)
    {
        $_SESSION['error'] =
            'Invalid submission or track';

        $this->redirect(
            '/easychair/admin/conference-home/manual-track-assignment'
        );
    }

    $db =
        \App\Core\Database::getInstance();

    $stmt =
        $db->prepare("

            SELECT
                s.conference_id AS submission_conference_id,
                t.conference_id AS track_conference_id
            FROM submissions s
            INNER JOIN tracks t
                ON t.id=?
            WHERE s.id=?
            LIMIT 1

        ");

    $stmt->execute([
        $trackId,
        $submissionId
    ]);

    $row =
        $stmt->fetch(
            \PDO::FETCH_ASSOC
        );

    if(
        !$row
        ||
        (int)$row['submission_conference_id']
        !==
        (int)$row['track_conference_id']
    )
    {
        $_SESSION['error'] =
            'Track does not belong to the same conference';

        $this->redirect(
            '/easychair/admin/conference-home/manual-track-assignment'
        );
    }

    $db
    ->prepare("

        UPDATE submissions

        SET
            track_id=?,
            updated_by=?,
            updated_at=NOW()

        WHERE id=?
        AND track_id IS NULL

    ")
    ->execute([
        $trackId,
        (int)($_SESSION['user_id'] ?? 0),
        $submissionId
    ]);

    $_SESSION['success'] =
        'Track assigned successfully';

    $this->redirect(
        '/easychair/admin/conference-home/manual-track-assignment'
    );
}

public function trackChairGovernance()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    /*
    --------------------------------------------------
    Main track governance overview
    --------------------------------------------------
    */
    $tracks =
        $db
        ->query("

            SELECT

                t.id,

                t.conference_id,

                COALESCE(
                    c.short_name,
                    c.title_en,
                    c.title_ar,
                    CONCAT('Conference #', t.conference_id)
                ) AS conference_name,

                COALESCE(
                    t.name_en,
                    t.name_ar
                ) AS track_name,

                COUNT(
                    DISTINCT tca.user_id
                ) AS active_chairs,

                COUNT(
                    DISTINCT s.id
                ) AS submissions,

                COUNT(
                    DISTINCT ra.id
                ) AS reviews

            FROM tracks t

            LEFT JOIN conferences c
                ON c.id = t.conference_id

            LEFT JOIN track_chair_assignments tca
                ON tca.track_id = t.id
               AND tca.is_active = 1

            LEFT JOIN submissions s
                ON s.track_id = t.id

            LEFT JOIN review_assignments ra
                ON ra.submission_id = s.id

            GROUP BY
                t.id,
                t.conference_id,
                c.short_name,
                c.title_en,
                c.title_ar,
                t.name_en,
                t.name_ar

            ORDER BY
                t.conference_id,
                t.id

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    /*
    --------------------------------------------------
    Primary-chair workload pool
    First assigned active chair is treated as primary.
    This avoids duplicate-chair workload inflation.
    --------------------------------------------------
    */
    $chairRows =
        $db
        ->query("

            SELECT

                pc.user_id,

                COALESCE(
                    NULLIF(
                        TRIM(
                            CONCAT(
                                COALESCE(u.first_name,''),
                                ' ',
                                COALESCE(u.last_name,'')
                            )
                        ),
                        ''
                    ),
                    u.email,
                    CONCAT('User #', pc.user_id)
                ) AS chair_name,

                COUNT(
                    DISTINCT pc.track_id
                ) AS tracks_owned,

                COUNT(
                    DISTINCT ra.id
                ) AS reviews

            FROM
            (
                SELECT
                    t1.track_id,
                    t1.user_id
                FROM track_chair_assignments t1

                INNER JOIN
                (
                    SELECT
                        track_id,
                        MIN(created_at) AS first_assigned
                    FROM track_chair_assignments
                    WHERE is_active = 1
                    GROUP BY track_id
                ) x
                    ON x.track_id = t1.track_id
                   AND x.first_assigned = t1.created_at

                WHERE t1.is_active = 1
            ) pc

            LEFT JOIN users u
                ON u.id = pc.user_id

            LEFT JOIN submissions s
                ON s.track_id = pc.track_id

            LEFT JOIN review_assignments ra
                ON ra.submission_id = s.id

            GROUP BY
                pc.user_id,
                u.first_name,
                u.last_name,
                u.email

            ORDER BY
                reviews ASC,
                tracks_owned ASC,
                chair_name ASC

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    /*
    --------------------------------------------------
    Orphan and duplicate tracks
    --------------------------------------------------
    */
    $orphanTracks =
        array_values(
            array_filter(
                $tracks,
                function($r) {
                    return (int)($r['active_chairs'] ?? 0) === 0;
                }
            )
        );

    $duplicateTracks =
        array_values(
            array_filter(
                $tracks,
                function($r) {
                    return (int)($r['active_chairs'] ?? 0) > 1;
                }
            )
        );

    /*
    --------------------------------------------------
    Add recovery priority + suggested chair.
    Suggested chair is selected from lowest current workload.
    This is advisory only. No automatic assignment happens here.
    --------------------------------------------------
    */
    $chairPointer = 0;

    foreach ($orphanTracks as &$track) {

        $reviews =
            (int)($track['reviews'] ?? 0);

        $submissions =
            (int)($track['submissions'] ?? 0);

        if ($reviews > 0) {
            $track['recovery_priority'] = 'HIGH';
        } elseif ($submissions > 0) {
            $track['recovery_priority'] = 'MEDIUM';
        } else {
            $track['recovery_priority'] = 'LOW';
        }

        if (!empty($chairRows)) {

            $suggested =
                $chairRows[
                    $chairPointer % count($chairRows)
                ];

            $track['suggested_user_id'] =
                (int)($suggested['user_id'] ?? 0);

            $track['suggested_chair'] =
                (string)($suggested['chair_name'] ?? '');

            $track['suggested_reviews'] =
                (int)($suggested['reviews'] ?? 0);

            $track['suggested_tracks'] =
                (int)($suggested['tracks_owned'] ?? 0);

            $chairPointer++;

        } else {

            $track['suggested_user_id'] = 0;
            $track['suggested_chair'] = '';
            $track['suggested_reviews'] = 0;
            $track['suggested_tracks'] = 0;
        }
    }

    unset($track);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/track_chair_governance.php';

    $content =
        ob_get_clean();

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

public function chairCapacityPlanner()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $rows =
        $db
        ->query("

            SELECT

                tca.user_id,

                CONCAT(
                    COALESCE(u.first_name,''),
                    ' ',
                    COALESCE(u.last_name,'')
                ) chair_name,

                COUNT(
                    DISTINCT tca.track_id
                ) tracks_owned,

                COUNT(
                    DISTINCT s.id
                ) submissions,

                COUNT(
                    DISTINCT ra.id
                ) reviews,

                COUNT(
                    DISTINCT CASE
                    WHEN ra.status='completed'
                    THEN ra.id
                    END
                ) completed_reviews,

                COUNT(
                    DISTINCT CASE
                    WHEN ra.status<>'completed'
                    THEN ra.id
                    END
                ) open_reviews,

                COUNT(
                    DISTINCT CASE
                    WHEN ra.status<>'completed'
                    AND ra.due_date<CURDATE()
                    THEN ra.id
                    END
                ) overdue_reviews

            FROM track_chair_assignments tca

            LEFT JOIN users u
            ON u.id=tca.user_id

            LEFT JOIN tracks t
            ON t.id=tca.track_id

            LEFT JOIN submissions s
            ON s.track_id=t.id

            LEFT JOIN review_assignments ra
            ON ra.submission_id=s.id

            WHERE tca.is_active=1

            GROUP BY
            tca.user_id

            ORDER BY
            reviews DESC

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    $summary = [
        'total_chairs'=>0,
        'critical'=>0,
        'high'=>0,
        'idle'=>0
    ];

    foreach($rows as &$r)
    {
        $reviews =
            (int)$r['reviews'];

        if($reviews >= 26)
        {
            $r['capacity']='CRITICAL';
            $summary['critical']++;
        }
        elseif($reviews >= 16)
        {
            $r['capacity']='HIGH';
            $summary['high']++;
        }
        elseif($reviews >= 6)
        {
            $r['capacity']='NORMAL';
        }
        else
        {
            $r['capacity']='LOW';
        }

        if($reviews==0)
        {
            $summary['idle']++;
        }

        $summary['total_chairs']++;
    }

    unset($r);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/chair_capacity.php';

    $content =
        ob_get_clean();

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

public function governanceLoadBalancer()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $rows =
        $db
        ->query("

            SELECT

                tca.user_id,

                CONCAT(
                    COALESCE(u.first_name,''),
                    ' ',
                    COALESCE(u.last_name,'')
                ) chair_name,

                COUNT(
                    DISTINCT tca.track_id
                ) tracks_owned,

                COUNT(
                    DISTINCT ra.id
                ) reviews

            FROM track_chair_assignments tca

            LEFT JOIN users u
            ON u.id=tca.user_id

            LEFT JOIN tracks t
            ON t.id=tca.track_id

            LEFT JOIN submissions s
            ON s.track_id=t.id

            LEFT JOIN review_assignments ra
            ON ra.submission_id=s.id

            WHERE tca.is_active=1

            GROUP BY tca.user_id

            ORDER BY reviews DESC

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    $summary = [
        'overloaded'=>0,
        'balanced'=>0,
        'idle'=>0
    ];

    foreach($rows as &$r)
    {
        $reviews =
            (int)$r['reviews'];

        if($reviews >= 25)
        {
            $r['balance_status'] =
                'OVERLOADED';

            $r['recommended_action'] =
                'Redistribute future assignments';

            $summary['overloaded']++;
        }
        elseif($reviews == 0)
        {
            $r['balance_status'] =
                'IDLE';

            $r['recommended_action'] =
                'Candidate for governance ownership';

            $summary['idle']++;
        }
        else
        {
            $r['balance_status'] =
                'BALANCED';

            $r['recommended_action'] =
                'No action required';

            $summary['balanced']++;
        }
    }

    unset($r);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/governance_load_balancer.php';

    $content =
        ob_get_clean();

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

public function governanceRecommendations()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $rows =
        $db
        ->query("

            SELECT

                tca.user_id,

                CONCAT(
                    COALESCE(u.first_name,''),
                    ' ',
                    COALESCE(u.last_name,'')
                ) chair_name,

                COUNT(
                    DISTINCT tca.track_id
                ) tracks_owned,

                COUNT(
                    DISTINCT ra.id
                ) reviews,

                SUM(
                    CASE
                    WHEN ra.status='completed'
                    THEN 1
                    ELSE 0
                    END
                ) completed_reviews,

                SUM(
                    CASE
                    WHEN ra.status<>'completed'
                    THEN 1
                    ELSE 0
                    END
                ) open_reviews,

                SUM(
                    CASE
                    WHEN ra.status<>'completed'
                    AND ra.due_date<CURDATE()
                    THEN 1
                    ELSE 0
                    END
                ) overdue_reviews

            FROM track_chair_assignments tca

            LEFT JOIN users u
            ON u.id=tca.user_id

            LEFT JOIN tracks t
            ON t.id=tca.track_id

            LEFT JOIN submissions s
            ON s.track_id=t.id

            LEFT JOIN review_assignments ra
            ON ra.submission_id=s.id

            WHERE tca.is_active=1

            GROUP BY tca.user_id

            ORDER BY reviews DESC

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    foreach($rows as &$r)
    {
        $score =
            max(
                0,
                min(
                    100,
                    100
                    -
                    (
                        ((int)$r['overdue_reviews'] * 10)
                    )
                    -
                    (
                        ((int)$r['open_reviews'])
                    )
                    +
                    (
                        ((int)$r['completed_reviews'] * 2)
                    )
                )
            );

        $r['governance_score']
            = $score;

        if(
            (int)$r['reviews']
            >= 25
        )
        {
            $r['recommendation']
                =
                'Reduce future ownership assignments';
        }
        elseif(
            (int)$r['reviews']
            == 0
        )
        {
            $r['recommendation']
                =
                'Assign future track ownership';
        }
        else
        {
            $r['recommendation']
                =
                'Balanced governance workload';
        }
    }

    unset($r);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/governance_recommendations.php';

    $content =
        ob_get_clean();

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


public function governanceAutomation()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $actions = [];

    $chairs =
        $db
        ->query("

            SELECT

                tca.user_id,

                CONCAT(
                    COALESCE(u.first_name,''),
                    ' ',
                    COALESCE(u.last_name,'')
                ) chair_name,

                COUNT(
                    DISTINCT tca.track_id
                ) tracks_owned,

                COUNT(
                    DISTINCT ra.id
                ) reviews

            FROM track_chair_assignments tca

            LEFT JOIN users u
                ON u.id=tca.user_id

            LEFT JOIN tracks t
                ON t.id=tca.track_id

            LEFT JOIN submissions s
                ON s.track_id=t.id

            LEFT JOIN review_assignments ra
                ON ra.submission_id=s.id

            WHERE tca.is_active=1

            GROUP BY tca.user_id

            ORDER BY reviews ASC

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    foreach($chairs as $c)
    {
        if((int)$c['reviews']==0)
        {
            $actions[] = [

                'type' =>
                    'INCREASE_UTILIZATION',

                'target' =>
                    $c['chair_name'],

                'reason' =>
                    'Owns tracks but has no reviews'

            ];
        }

        if((int)$c['reviews']>=25)
        {
            $actions[] = [

                'type' =>
                    'REDUCE_ASSIGNMENTS',

                'target' =>
                    $c['chair_name'],

                'reason' =>
                    'Review load exceeds governance threshold'

            ];
        }
    }

    $orphanTracks =
        $db
        ->query("

            SELECT

                t.id,

                COALESCE(
                    t.name_en,
                    t.name_ar
                ) track_name

            FROM tracks t

            WHERE NOT EXISTS
            (
                SELECT 1
                FROM track_chair_assignments a
                WHERE a.track_id=t.id
                AND a.is_active=1
            )

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    foreach($orphanTracks as $t)
    {
        $actions[] = [

            'type' =>
                'ASSIGN_TRACK_CHAIR',

            'target' =>
                $t['track_name'],

            'reason' =>
                'Track has no active chair'

        ];
    }

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/governance_automation.php';

    $content =
        ob_get_clean();

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


public function governanceSimulation()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $rows =
        $db
        ->query("

            SELECT

                t.id,

                COALESCE(
                    t.name_en,
                    t.name_ar
                ) track_name,

                COUNT(
                    DISTINCT ra.id
                ) reviews,

                COUNT(
                    DISTINCT tca.user_id
                ) active_chairs

            FROM tracks t

            LEFT JOIN submissions s
                ON s.track_id=t.id

            LEFT JOIN review_assignments ra
                ON ra.submission_id=s.id

            LEFT JOIN track_chair_assignments tca
                ON tca.track_id=t.id
               AND tca.is_active=1

            GROUP BY t.id

            ORDER BY reviews DESC

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/governance_simulation.php';

    $content =
        ob_get_clean();

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

public function governanceExecutiveBoard()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $decisions =
        $db
        ->query("

            SELECT *

            FROM conference_home_decisions

            ORDER BY
                id DESC

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    $governanceAudits =
        $db
        ->query("

            SELECT *

            FROM conference_home_governance

            ORDER BY
                id DESC

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    $executiveDecisions =
        $db
        ->query("

            SELECT *

            FROM platform_executive_decisions

            ORDER BY
                id DESC

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/governance_executive_board.php';

    $content =
        ob_get_clean();

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

public function governanceDecisionEngine()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $generated = 0;

    $orphanTracks =
        $db
        ->query("
            SELECT
                t.id,
                t.conference_id,
                COALESCE(
                    t.name_en,
                    t.name_ar
                ) track_name
            FROM tracks t
            WHERE NOT EXISTS
            (
                SELECT 1
                FROM track_chair_assignments a
                WHERE a.track_id=t.id
                AND a.is_active=1
            )
        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    foreach($orphanTracks as $t)
    {
        $db
        ->prepare("
            INSERT INTO
            conference_home_decisions
            (
                conference_id,
                decision_type,
                decision_title,
                decision_reason,
                decision_score,
                decision_state
            )
            VALUES
            (
                ?,?,?,?,?,?
            )
        ")
        ->execute([
            $t['conference_id'],
            'ASSIGN_TRACK_CHAIR',
            'Assign Chair - '.$t['track_name'],
            'Track has no active chair',
            100,
            'suggested'
        ]);

        $generated++;
    }

    $decisions =
        $db
        ->query("
            SELECT *
            FROM conference_home_decisions
            ORDER BY id DESC
        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/governance_decision_engine.php';

    $content =
        ob_get_clean();

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

public function governanceApprovalCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $rows =
        $db
        ->query("

            SELECT *

            FROM conference_home_decisions

            ORDER BY
                decision_state,
                decision_score DESC,
                id DESC

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/governance_approval_center.php';

    $content =
        ob_get_clean();

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

public function approveGovernanceDecision()
{
    $this->requireAccess();

    $id =
        (int)(
            $_GET['id']
            ?? 0
        );

    if($id<=0)
    {
        $this->redirect(
            '/easychair/admin/conference-home/governance-approval-center'
        );
    }

    $db =
        \App\Core\Database::getInstance();

    $db
    ->prepare("

        UPDATE conference_home_decisions

        SET
            decision_state='approved',
            approved_by=?

        WHERE id=?

    ")
    ->execute([

        (int)(
            $_SESSION['user_id']
            ?? 0
        ),

        $id

    ]);

    $this->redirect(
        '/easychair/admin/conference-home/governance-approval-center'
    );
}

public function rejectGovernanceDecision()
{
    $this->requireAccess();

    $id =
        (int)(
            $_GET['id']
            ?? 0
        );

    if($id<=0)
    {
        $this->redirect(
            '/easychair/admin/conference-home/governance-approval-center'
        );
    }

    $db =
        \App\Core\Database::getInstance();

    $db
    ->prepare("

        UPDATE conference_home_decisions

        SET
            decision_state='rejected'

        WHERE id=?

    ")
    ->execute([
        $id
    ]);

    $this->redirect(
        '/easychair/admin/conference-home/governance-approval-center'
    );
}

public function governanceExecutionCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $rows =
        $db
        ->query("

            SELECT *

            FROM conference_home_decisions

            WHERE decision_state='approved'

            ORDER BY id DESC

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/governance_execution_center.php';

    $content =
        ob_get_clean();

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

public function executeGovernanceDecision()
{
    $this->requireAccess();

    $id =
        (int)(
            $_GET['id']
            ?? 0
        );

    if($id<=0)
    {
        $this->redirect(
            '/easychair/admin/conference-home/governance-execution-center'
        );
    }

    $db =
        \App\Core\Database::getInstance();

    $decision =
        $db
        ->prepare("

            SELECT *

            FROM conference_home_decisions

            WHERE id=?

            LIMIT 1

        ");

    $decision->execute([$id]);

    $row =
        $decision->fetch(
            \PDO::FETCH_ASSOC
        );

    if(!$row)
    {
        $this->redirect(
            '/easychair/admin/conference-home/governance-execution-center'
        );
    }

    $db
    ->prepare("

        INSERT INTO
        conference_home_governance
        (
            conference_id,
            audit_type,
            audit_score,
            details_json
        )
        VALUES
        (
            ?,?,?,?
        )

    ")
    ->execute([

        $row['conference_id'],

        $row['decision_type'],

        $row['decision_score'],

        json_encode($row)

    ]);

    $db
    ->prepare("

        UPDATE conference_home_decisions

        SET decision_state='executed'

        WHERE id=?

    ")
    ->execute([
        $id
    ]);

    $this->redirect(
        '/easychair/admin/conference-home/governance-execution-center'
    );
}

public function governanceObservatory()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $ownershipCoverage =
        $db
        ->query("

            SELECT

                COUNT(*) total_tracks,

                SUM(

                    CASE

                        WHEN EXISTS
                        (
                            SELECT 1
                            FROM track_chair_assignments a
                            WHERE a.track_id=t.id
                            AND a.is_active=1
                        )

                        THEN 1

                        ELSE 0

                    END

                ) governed_tracks

            FROM tracks t

        ")
        ->fetch(
            \PDO::FETCH_ASSOC
        );

    $decisionStats =
        $db
        ->query("

            SELECT

                decision_state,

                COUNT(*) total

            FROM conference_home_decisions

            GROUP BY decision_state

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/governance_observatory.php';

    $content =
        ob_get_clean();

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

public function governanceCommandCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $coverage =
        $db
        ->query("

            SELECT

                COUNT(*) total_tracks,

                SUM(

                    CASE

                        WHEN EXISTS
                        (
                            SELECT 1
                            FROM track_chair_assignments a
                            WHERE a.track_id=t.id
                            AND a.is_active=1
                        )

                        THEN 1

                        ELSE 0

                    END

                ) governed_tracks

            FROM tracks t

        ")
        ->fetch(
            \PDO::FETCH_ASSOC
        );

    $orphanTracks =
        $db
        ->query("

            SELECT

                t.id,

                t.conference_id,

                COALESCE(
                    t.name_en,
                    t.name_ar
                ) track_name,

                COUNT(
                    DISTINCT s.id
                ) submissions,

                COUNT(
                    DISTINCT ra.id
                ) reviews

            FROM tracks t

            LEFT JOIN submissions s
                ON s.track_id=t.id

            LEFT JOIN review_assignments ra
                ON ra.submission_id=s.id

            WHERE NOT EXISTS
            (
                SELECT 1
                FROM track_chair_assignments a
                WHERE a.track_id=t.id
                AND a.is_active=1
            )

            GROUP BY t.id

            ORDER BY
                reviews DESC,
                submissions DESC

            LIMIT 10

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    $duplicateTracks =
        $db
        ->query("

            SELECT

                t.id,

                COALESCE(
                    t.name_en,
                    t.name_ar
                ) track_name,

                COUNT(*) active_chairs

            FROM track_chair_assignments a

            INNER JOIN tracks t
                ON t.id=a.track_id

            WHERE a.is_active=1

            GROUP BY t.id

            HAVING COUNT(*) > 1

            ORDER BY active_chairs DESC

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    $decisionPipeline =
        $db
        ->query("

            SELECT

                decision_state,

                COUNT(*) total

            FROM conference_home_decisions

            GROUP BY decision_state

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    $healthScore =
        max(
            0,
            100
            -
            (
                count($orphanTracks) * 5
            )
            -
            (
                count($duplicateTracks) * 3
            )
        );

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/governance_command_center.php';

    $content =
        ob_get_clean();

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

public function selfHealingGovernanceScan()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $orphanTracks =
        (int)$db
        ->query("

            SELECT COUNT(*)

            FROM tracks t

            WHERE NOT EXISTS
            (
                SELECT 1
                FROM track_chair_assignments a
                WHERE a.track_id=t.id
                AND a.is_active=1
            )

        ")
        ->fetchColumn();

    $duplicateTracks =
        (int)$db
        ->query("

            SELECT COUNT(*)

            FROM
            (
                SELECT track_id

                FROM track_chair_assignments

                WHERE is_active=1

                GROUP BY track_id

                HAVING COUNT(*)>1
            ) x

        ")
        ->fetchColumn();

    $idleChairs =
        (int)$db
        ->query("

            SELECT COUNT(*)

            FROM
            (
                SELECT

                    tca.user_id

                FROM track_chair_assignments tca

                LEFT JOIN tracks t
                    ON t.id=tca.track_id

                LEFT JOIN submissions s
                    ON s.track_id=t.id

                LEFT JOIN review_assignments ra
                    ON ra.submission_id=s.id

                WHERE tca.is_active=1

                GROUP BY tca.user_id

                HAVING COUNT(
                    DISTINCT ra.id
                ) = 0

            ) z

        ")
        ->fetchColumn();

    $overloadedChairs =
        (int)$db
        ->query("

            SELECT COUNT(*)

            FROM
            (
                SELECT

                    tca.user_id

                FROM track_chair_assignments tca

                LEFT JOIN tracks t
                    ON t.id=tca.track_id

                LEFT JOIN submissions s
                    ON s.track_id=t.id

                LEFT JOIN review_assignments ra
                    ON ra.submission_id=s.id

                WHERE tca.is_active=1

                GROUP BY tca.user_id

                HAVING COUNT(
                    DISTINCT ra.id
                ) >= 20

            ) x

        ")
        ->fetchColumn();

    $_SESSION['success'] =
        'Governance scan completed. '
        .
        'Orphan Tracks='
        . $orphanTracks
        .
        ', Duplicate Tracks='
        . $duplicateTracks
        .
        ', Idle Chairs='
        . $idleChairs
        .
        ', Overloaded Chairs='
        . $overloadedChairs;

    $this->redirect(
        '/easychair/admin/conference-home/self-healing'
    );
}

public function captureGovernanceSnapshot()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $coverage =
        $db
        ->query("

            SELECT

                COUNT(*) total_tracks,

                SUM(

                    CASE

                        WHEN EXISTS
                        (
                            SELECT 1
                            FROM track_chair_assignments a
                            WHERE a.track_id=t.id
                            AND a.is_active=1
                        )

                        THEN 1

                        ELSE 0

                    END

                ) governed_tracks

            FROM tracks t

        ")
        ->fetch(
            \PDO::FETCH_ASSOC
        );

    $orphanTracks =
        (int)$db
        ->query("

            SELECT COUNT(*)

            FROM tracks t

            WHERE NOT EXISTS
            (
                SELECT 1
                FROM track_chair_assignments a
                WHERE a.track_id=t.id
                AND a.is_active=1
            )

        ")
        ->fetchColumn();

    $duplicateTracks =
        (int)$db
        ->query("

            SELECT COUNT(*)

            FROM
            (
                SELECT track_id

                FROM track_chair_assignments

                WHERE is_active=1

                GROUP BY track_id

                HAVING COUNT(*)>1
            ) x

        ")
        ->fetchColumn();

    $coveragePercent =
        round(
            (
                (int)$coverage['governed_tracks']
                /
                max(
                    1,
                    (int)$coverage['total_tracks']
                )
            ) * 100,
            2
        );

    $healthScore =
        max(
            0,
            100
            -
            ($orphanTracks * 5)
            -
            ($duplicateTracks * 3)
        );

    $payload =
        json_encode([
            'coverage_percent' => $coveragePercent,
            'orphan_tracks'    => $orphanTracks,
            'duplicate_tracks' => $duplicateTracks,
            'health_score'     => $healthScore
        ]);

    $db
    ->prepare("

        INSERT INTO
        platform_governance_observatory
        (
            governance_key,
            governance_title,
            governance_type,
            governance_score,
            governance_state,
            governance_json
        )
        VALUES
        (
            'governance_snapshot',
            'Governance Snapshot',
            'snapshot',
            ?,
            'observed',
            ?
        )

    ")
    ->execute([
        $healthScore,
        $payload
    ]);

    $_SESSION['success'] =
        'Governance snapshot captured successfully';

    $this->redirect(
        '/easychair/admin/conference-home/governance-observatory'
    );
}

public function reviewerGovernance()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $rows =
        $db
        ->query("

            SELECT

                u.id AS user_id,

                CONCAT(
                    COALESCE(u.first_name,''),
                    ' ',
                    COALESCE(u.last_name,'')
                ) AS reviewer_name,

                COUNT(
                    DISTINCT ra.id
                ) AS total_reviews,

                SUM(
                    CASE
                    WHEN ra.status='completed'
                    THEN 1
                    ELSE 0
                    END
                ) AS completed_reviews,

                SUM(
                    CASE
                    WHEN ra.status<>'completed'
                    THEN 1
                    ELSE 0
                    END
                ) AS open_reviews,

                SUM(
                    CASE
                    WHEN ra.status<>'completed'
                    AND ra.due_date<CURDATE()
                    THEN 1
                    ELSE 0
                    END
                ) AS overdue_reviews

            FROM users u

            INNER JOIN review_assignments ra
                ON ra.reviewer_id=u.id

            GROUP BY u.id

            ORDER BY overdue_reviews DESC,
                     open_reviews DESC

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    foreach($rows as &$row)
    {
        $score =
            100
            -
            (
                ((int)$row['overdue_reviews'])
                * 10
            )
            -
            (
                ((int)$row['open_reviews'])
                * 2
            )
            +
            (
                ((int)$row['completed_reviews'])
            );

        $row['governance_score'] =
            max(
                0,
                min(
                    100,
                    $score
                )
            );

        if(
            (int)$row['overdue_reviews']
            >= 3
        )
        {
            $row['risk']='Critical';
        }
        elseif(
            (int)$row['overdue_reviews']
            >=1
        )
        {
            $row['risk']='Watch';
        }
        else
        {
            $row['risk']='Healthy';
        }
    }

    unset($row);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/reviewer_governance.php';

    $content =
        ob_get_clean();

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

public function reviewLoadBalancer()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $rows =
        $db
        ->query("

            SELECT

                u.id,

                CONCAT(
                    COALESCE(u.first_name,''),
                    ' ',
                    COALESCE(u.last_name,'')
                ) reviewer_name,

                MAX(
    COALESCE(
        p.reviewer_capacity,
        10
    )
) reviewer_capacity,

                COUNT(
                    ra.id
                ) open_reviews

            FROM users u

            INNER JOIN conference_reviewers cr
                ON cr.user_id=u.id

            LEFT JOIN user_profiles p
                ON p.user_id=u.id

            LEFT JOIN review_assignments ra
                ON ra.reviewer_id=u.id
               AND ra.status<>'completed'

            GROUP BY
                u.id

            ORDER BY
                open_reviews DESC

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    $recommendations = [];

    foreach($rows as $source)
    {
        if(
            (int)$source['open_reviews']
            < 10
        )
        {
            continue;
        }

        foreach($rows as $target)
        {
            if(
                $source['id']
                ==
                $target['id']
            )
            {
                continue;
            }

            $available =
                (int)$target['reviewer_capacity']
                -
                (int)$target['open_reviews'];

            if($available <= 0)
            {
                continue;
            }

            $recommendations[] = [

                'from' =>
                    $source['reviewer_name'],

                'to' =>
                    $target['reviewer_name'],

                'suggested_transfer' =>
                    min(
                        3,
                        $available
                    )

            ];

            break;
        }
    }

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/review_load_balancer.php';

    $content =
        ob_get_clean();

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

public function reviewRiskIntelligence()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $rows =
        $db
        ->query("

            SELECT

                s.id,

                s.submission_no,

                s.title,

                COALESCE(
                    t.name_en,
                    t.name_ar
                ) AS track_name,

                COUNT(
                    DISTINCT ra.id
                ) AS assigned_reviews,

                SUM(
                    CASE
                    WHEN ra.status='completed'
                    THEN 1
                    ELSE 0
                    END
                ) AS completed_reviews,

                SUM(
                    CASE
                    WHEN ra.status<>'completed'
                    THEN 1
                    ELSE 0
                    END
                ) AS open_reviews,

                SUM(
                    CASE
                    WHEN ra.status<>'completed'
                    AND ra.due_date<CURDATE()
                    THEN 1
                    ELSE 0
                    END
                ) AS overdue_reviews

            FROM submissions s

            LEFT JOIN tracks t
                ON t.id=s.track_id

            LEFT JOIN review_assignments ra
                ON ra.submission_id=s.id

            GROUP BY
                s.id

            ORDER BY
                overdue_reviews DESC,
                open_reviews DESC

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    foreach($rows as &$row)
    {
        $missing =
            max(
                0,
                3 - (int)$row['assigned_reviews']
            );

        $risk =
            (
                ((int)$row['overdue_reviews'])
                * 20
            )
            +
            (
                $missing * 10
            )
            +
            (
                ((int)$row['open_reviews'])
                * 5
            );

        $risk =
            min(
                100,
                $risk
            );

        $row['risk_score'] =
            $risk;

        if($risk >= 80)
        {
            $row['risk_level']='Critical';
        }
        elseif($risk >= 50)
        {
            $row['risk_level']='High Risk';
        }
        elseif($risk >= 20)
        {
            $row['risk_level']='Watch';
        }
        else
        {
            $row['risk_level']='Healthy';
        }
    }

    unset($row);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/review_risk_intelligence.php';

    $content =
        ob_get_clean();

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

public function trackRiskIntelligence()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $rows =
        $db
        ->query("

            SELECT

                t.id,

                COALESCE(
                    t.name_en,
                    t.name_ar
                ) AS track_name,

                COUNT(
                    DISTINCT s.id
                ) AS submissions,

                COUNT(
                    DISTINCT ra.id
                ) AS assigned_reviews,

                SUM(
                    CASE
                    WHEN ra.status='completed'
                    THEN 1
                    ELSE 0
                    END
                ) AS completed_reviews,

                SUM(
                    CASE
                    WHEN ra.status<>'completed'
                    THEN 1
                    ELSE 0
                    END
                ) AS open_reviews,

                SUM(
                    CASE
                    WHEN ra.status<>'completed'
                    AND ra.due_date<CURDATE()
                    THEN 1
                    ELSE 0
                    END
                ) AS overdue_reviews

            FROM tracks t

            LEFT JOIN submissions s
                ON s.track_id=t.id

            LEFT JOIN review_assignments ra
                ON ra.submission_id=s.id

            GROUP BY
                t.id

            ORDER BY
                overdue_reviews DESC,
                open_reviews DESC

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    foreach($rows as &$row)
    {
        $criticalSubmissions = 0;

        $risk =
            (
                ((int)$row['overdue_reviews'])
                * 5
            )
            +
            (
                ((int)$row['open_reviews'])
                * 2
            );

        $risk =
            min(
                100,
                $risk
            );

        $row['critical_submissions'] =
            $criticalSubmissions;

        $row['risk_score'] =
            $risk;

        if($risk >= 80)
        {
            $row['risk_level'] =
                'Critical';
        }
        elseif($risk >= 50)
        {
            $row['risk_level'] =
                'High Risk';
        }
        elseif($risk >= 20)
        {
            $row['risk_level'] =
                'Watch';
        }
        else
        {
            $row['risk_level'] =
                'Healthy';
        }
    }

    unset($row);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/track_risk_intelligence.php';

    $content =
        ob_get_clean();

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

public function conferenceHealthEngine()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $rows =
        $db
        ->query("

            SELECT

                c.id,

                c.short_name,

                c.title_en,

                COUNT(
                    DISTINCT t.id
                ) AS total_tracks,

                COUNT(
                    DISTINCT CASE
                    WHEN EXISTS
                    (
                        SELECT 1
                        FROM track_chair_assignments a
                        WHERE a.track_id=t.id
                        AND a.is_active=1
                    )
                    THEN t.id
                    END
                ) AS governed_tracks,

                COUNT(
                    DISTINCT s.id
                ) AS submissions,

                COUNT(
                    DISTINCT ra.id
                ) AS reviews,

                SUM(
                    CASE
                    WHEN ra.status<>'completed'
                    AND ra.due_date<CURDATE()
                    THEN 1
                    ELSE 0
                    END
                ) AS overdue_reviews

            FROM conferences c

            LEFT JOIN tracks t
                ON t.conference_id=c.id

            LEFT JOIN submissions s
                ON s.conference_id=c.id

            LEFT JOIN review_assignments ra
                ON ra.submission_id=s.id

            GROUP BY
                c.id

            ORDER BY
                c.short_name

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    $platformHealth = 0;

    foreach($rows as &$row)
    {
        $coverage =
            (
                (int)$row['governed_tracks']
                /
                max(
                    1,
                    (int)$row['total_tracks']
                )
            ) * 100;

        $reviewHealth =
            max(
                0,
                100 -
                (
                    ((int)$row['overdue_reviews'])
                    * 5
                )
            );

        $health =
            round(
                (
                    $coverage * 0.50
                )
                +
                (
                    $reviewHealth * 0.50
                ),
                2
            );

        $row['coverage_percent'] =
            round($coverage,2);

        $row['health_score'] =
            $health;

        if($health >= 90)
        {
            $row['health_status']='Excellent';
        }
        elseif($health >= 75)
        {
            $row['health_status']='Healthy';
        }
        elseif($health >= 50)
        {
            $row['health_status']='Watch';
        }
        elseif($health >= 25)
        {
            $row['health_status']='At Risk';
        }
        else
        {
            $row['health_status']='Critical';
        }

        $platformHealth += $health;
    }

    unset($row);

    $averageHealth =
        count($rows)
        ?
        round(
            $platformHealth /
            count($rows),
            2
        )
        :
        0;

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/conference_health_engine.php';

    $content =
        ob_get_clean();

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

public function executiveGovernanceCockpit()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $activeAlerts =
        (int)$db
        ->query("
            SELECT COUNT(*)
            FROM homepage_workflow_alerts
            WHERE is_resolved=0
        ")
        ->fetchColumn();

    $pendingDecisions =
        (int)$db
        ->query("
            SELECT COUNT(*)
            FROM conference_home_decisions
            WHERE decision_state IN
            (
                'suggested',
                'pending',
                'proposed',
                'approved'
            )
        ")
        ->fetchColumn();

    $executedDecisions =
        (int)$db
        ->query("
            SELECT COUNT(*)
            FROM conference_home_decisions
            WHERE decision_state='executed'
        ")
        ->fetchColumn();

    $conferenceHealth =
        $db
        ->query("

            SELECT

                c.id,
                c.short_name,
                c.title_en,

                COUNT(DISTINCT t.id) AS total_tracks,

                COUNT(
                    DISTINCT CASE
                    WHEN EXISTS
                    (
                        SELECT 1
                        FROM track_chair_assignments a
                        WHERE a.track_id=t.id
                        AND a.is_active=1
                    )
                    THEN t.id
                    END
                ) AS governed_tracks,

                COUNT(DISTINCT s.id) AS submissions,

                COUNT(DISTINCT ra.id) AS reviews,

                SUM(
                    CASE
                    WHEN ra.status<>'completed'
                    AND ra.due_date<CURDATE()
                    THEN 1
                    ELSE 0
                    END
                ) AS overdue_reviews

            FROM conferences c

            LEFT JOIN tracks t
                ON t.conference_id=c.id

            LEFT JOIN submissions s
                ON s.conference_id=c.id

            LEFT JOIN review_assignments ra
                ON ra.submission_id=s.id

            GROUP BY
                c.id,
                c.short_name,
                c.title_en

            ORDER BY
                c.id ASC

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    $platformHealth = 0;
    $highestRiskConference = null;
    $bestConference = null;

    foreach($conferenceHealth as &$row)
    {
        $coverage =
            (
                (int)$row['governed_tracks']
                /
                max(
                    1,
                    (int)$row['total_tracks']
                )
            ) * 100;

        $reviewHealth =
            max(
                0,
                100 -
                (
                    ((int)$row['overdue_reviews'])
                    * 5
                )
            );

        $health =
            round(
                ($coverage * 0.50)
                +
                ($reviewHealth * 0.50),
                2
            );

        $row['coverage_percent'] =
            round($coverage, 2);

        $row['health_score'] =
            $health;

        if($health >= 90)
        {
            $row['health_status']='Excellent';
        }
        elseif($health >= 75)
        {
            $row['health_status']='Healthy';
        }
        elseif($health >= 50)
        {
            $row['health_status']='Watch';
        }
        elseif($health >= 25)
        {
            $row['health_status']='At Risk';
        }
        else
        {
            $row['health_status']='Critical';
        }

        $platformHealth += $health;

        if(
            $highestRiskConference === null
            ||
            $health < (float)$highestRiskConference['health_score']
        )
        {
            $highestRiskConference = $row;
        }

        if(
            $bestConference === null
            ||
            $health > (float)$bestConference['health_score']
        )
        {
            $bestConference = $row;
        }
    }

    unset($row);

    $platformHealth =
        count($conferenceHealth)
        ?
        round(
            $platformHealth / count($conferenceHealth),
            2
        )
        :
        0;

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/executive_governance_cockpit.php';

    $content =
        ob_get_clean();

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

public function governanceOperationsCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $actionQueue = [];

    $overloadedReviewers =
        $db
        ->query("

            SELECT

                reviewer_id,

                COUNT(*) total_reviews

            FROM review_assignments

            WHERE status<>'completed'

            GROUP BY reviewer_id

            HAVING COUNT(*) >= 10

            ORDER BY total_reviews DESC

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    foreach($overloadedReviewers as $row)
    {
        $actionQueue[] = [

            'category' =>
                'Reviewer',

            'severity' =>
                'High',

            'action' =>
                'Rebalance Reviews',

            'details' =>
                'Reviewer #' .
                $row['reviewer_id'] .
                ' has ' .
                $row['total_reviews'] .
                ' active reviews.'

        ];
    }

    $missingTrackChairs =
        $db
        ->query("

            SELECT

                t.id,
                COALESCE(
                    t.name_en,
                    t.name_ar
                ) track_name

            FROM tracks t

            WHERE NOT EXISTS
            (
                SELECT 1
                FROM track_chair_assignments a
                WHERE a.track_id=t.id
                AND a.is_active=1
            )

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    foreach($missingTrackChairs as $row)
    {
        $actionQueue[] = [

            'category' =>
                'Track',

            'severity' =>
                'Critical',

            'action' =>
                'Assign Track Chair',

            'details' =>
                $row['track_name']

        ];
    }

    $criticalSubmissions =
        $db
        ->query("

            SELECT

                s.submission_no,

                COUNT(*) overdue_reviews

            FROM submissions s

            INNER JOIN review_assignments ra
                ON ra.submission_id=s.id

            WHERE
                ra.status<>'completed'
                AND ra.due_date<CURDATE()

            GROUP BY
                s.id

            HAVING overdue_reviews>=2

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    foreach($criticalSubmissions as $row)
    {
        $actionQueue[] = [

            'category' =>
                'Submission',

            'severity' =>
                'Critical',

            'action' =>
                'Review Intervention',

            'details' =>
                $row['submission_no']

        ];
    }

    usort(
        $actionQueue,
        function($a,$b)
        {
            return strcmp(
                $b['severity'],
                $a['severity']
            );
        }
    );

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/governance_operations_center.php';

    $content =
        ob_get_clean();

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

public function portfolioManagement()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $portfolio =
        $db
        ->query("

            SELECT

                c.id,

                c.short_name,

                c.title_en,

                COUNT(
                    DISTINCT t.id
                ) AS tracks,

                COUNT(
                    DISTINCT s.id
                ) AS submissions,

                COUNT(
                    DISTINCT ra.id
                ) AS reviews,

                SUM(
                    CASE
                    WHEN ra.status<>'completed'
                    AND ra.due_date<CURDATE()
                    THEN 1
                    ELSE 0
                    END
                ) AS overdue_reviews

            FROM conferences c

            LEFT JOIN tracks t
                ON t.conference_id=c.id

            LEFT JOIN submissions s
                ON s.conference_id=c.id

            LEFT JOIN review_assignments ra
                ON ra.submission_id=s.id

            GROUP BY
                c.id,
                c.short_name,
                c.title_en

            ORDER BY
                submissions DESC

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    foreach($portfolio as &$row)
    {
        $score =
            max(
                0,
                100
                -
                (
                    ((int)$row['overdue_reviews'])
                    * 5
                )
            );

        $row['portfolio_score'] =
            $score;

        if($score >= 90)
        {
            $row['classification']='Strategic';
        }
        elseif($score >= 75)
        {
            $row['classification']='Healthy';
        }
        elseif($score >= 50)
        {
            $row['classification']='Watch';
        }
        else
        {
            $row['classification']='Intervention';
        }
    }

    unset($row);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/portfolio_management.php';

    $content =
        ob_get_clean();

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

public function organizationIntelligenceHub()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $rows =
        $db
        ->query("

            SELECT

                o.id,
                o.name,

                COUNT(
                    DISTINCT c.id
                ) AS conferences,

                COUNT(
                    DISTINCT t.id
                ) AS tracks,

                COUNT(
                    DISTINCT s.id
                ) AS submissions,

                COUNT(
                    DISTINCT ra.id
                ) AS reviews,

                SUM(
                    CASE
                    WHEN ra.status<>'completed'
                    AND ra.due_date<CURDATE()
                    THEN 1
                    ELSE 0
                    END
                ) AS overdue_reviews

            FROM organizations o

            LEFT JOIN conferences c
                ON c.org_id=o.id

            LEFT JOIN tracks t
                ON t.conference_id=c.id

            LEFT JOIN submissions s
                ON s.conference_id=c.id

            LEFT JOIN review_assignments ra
                ON ra.submission_id=s.id

            GROUP BY
                o.id,
                o.name

            ORDER BY
                conferences DESC

        ")
        ->fetchAll(
            \PDO::FETCH_ASSOC
        );

    foreach($rows as &$row)
    {
        $score =
            max(
                0,
                100 -
                (
                    ((int)$row['overdue_reviews'])
                    * 3
                )
            );

        $row['intelligence_score'] =
            $score;

        if($score >= 90)
        {
            $row['classification']='Leader';
        }
        elseif($score >= 75)
        {
            $row['classification']='Strong';
        }
        elseif($score >= 50)
        {
            $row['classification']='Watch';
        }
        else
        {
            $row['classification']='Intervention';
        }
    }

    unset($row);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/organization_intelligence_hub.php';

    $content =
        ob_get_clean();

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

public function platformOperationsCommandCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $overview = [

        'organizations' =>
            (int)$db
            ->query("
                SELECT COUNT(*)
                FROM organizations
            ")
            ->fetchColumn(),

        'conferences' =>
            (int)$db
            ->query("
                SELECT COUNT(*)
                FROM conferences
            ")
            ->fetchColumn(),

        'tracks' =>
            (int)$db
            ->query("
                SELECT COUNT(*)
                FROM tracks
            ")
            ->fetchColumn(),

        'submissions' =>
            (int)$db
            ->query("
                SELECT COUNT(*)
                FROM submissions
            ")
            ->fetchColumn(),

        'reviews' =>
            (int)$db
            ->query("
                SELECT COUNT(*)
                FROM review_assignments
            ")
            ->fetchColumn(),

        'reviewers' =>
            (int)$db
            ->query("
                SELECT COUNT(*)
                FROM conference_reviewers
            ")
            ->fetchColumn()

    ];

    $alerts =
        (int)$db
        ->query("
            SELECT COUNT(*)
            FROM homepage_workflow_alerts
            WHERE is_resolved=0
        ")
        ->fetchColumn();

    $pendingDecisions =
        (int)$db
        ->query("
            SELECT COUNT(*)
            FROM conference_home_decisions
            WHERE decision_state IN
            (
                'suggested',
                'pending',
                'proposed'
            )
        ")
        ->fetchColumn();

    $missingTrackChairs =
        (int)$db
        ->query("

            SELECT COUNT(*)

            FROM tracks t

            WHERE NOT EXISTS
            (
                SELECT 1
                FROM track_chair_assignments a
                WHERE a.track_id=t.id
                AND a.is_active=1
            )

        ")
        ->fetchColumn();

    $overloadedReviewers =
        (int)$db
        ->query("

            SELECT COUNT(*)

            FROM
            (
                SELECT reviewer_id

                FROM review_assignments

                WHERE status<>'completed'

                GROUP BY reviewer_id

                HAVING COUNT(*)>=10
            ) x

        ")
        ->fetchColumn();

    $criticalSubmissions =
        (int)$db
        ->query("

            SELECT COUNT(*)

            FROM
            (
                SELECT s.id

                FROM submissions s

                INNER JOIN review_assignments ra
                    ON ra.submission_id=s.id

                WHERE
                    ra.status<>'completed'
                    AND ra.due_date<CURDATE()

                GROUP BY s.id

                HAVING COUNT(*)>=2
            ) z

        ")
        ->fetchColumn();

    $platformHealth =
        max(
            0,
            100
            -
            ($alerts * 2)
            -
            ($missingTrackChairs * 2)
        );

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/platform_operations_command_center.php';

    $content =
        ob_get_clean();

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


public function governanceConsolidationEngine()
{
    $this->requireAccess();

    $overview = \App\Services\GovernanceEngine::platformOverview();
    $risks = \App\Services\GovernanceEngine::riskCounters();
    $platformHealth = \App\Services\GovernanceEngine::platformHealth();

    ob_start();
    require BASE_PATH . '/app/views/admin/conference_home/governance_consolidation_engine.php';
    $content = ob_get_clean();
    require BASE_PATH . '/app/views/layouts/admin_layout.php';
}

public function governanceAutomationActions()
{
    $this->requireAccess();

    $actions = \App\Services\GovernanceEngine::recommendedActions();

    ob_start();
    require BASE_PATH . '/app/views/admin/conference_home/governance_automation_actions.php';
    $content = ob_get_clean();
    require BASE_PATH . '/app/views/layouts/admin_layout.php';
}

public function smartReviewerAssignmentEngine()
{
    $this->requireAccess();

    $db = \App\Core\Database::getInstance();

    $rows = $db->query("
        SELECT
            u.id,
            CONCAT(COALESCE(u.first_name,''),' ',COALESCE(u.last_name,'')) reviewer_name,
            COUNT(ra.id) open_reviews,
            MAX(COALESCE(p.reviewer_capacity,10)) reviewer_capacity,
            GREATEST(0, MAX(COALESCE(p.reviewer_capacity,10)) - COUNT(ra.id)) available_capacity
        FROM users u
        INNER JOIN conference_reviewers cr ON cr.user_id=u.id
        LEFT JOIN user_profiles p ON p.user_id=u.id
        LEFT JOIN review_assignments ra
            ON ra.reviewer_id=u.id
           AND ra.status<>'completed'
        GROUP BY u.id
        ORDER BY available_capacity DESC, open_reviews ASC
    ")->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();
    require BASE_PATH . '/app/views/admin/conference_home/smart_reviewer_assignment_engine.php';
    $content = ob_get_clean();
    require BASE_PATH . '/app/views/layouts/admin_layout.php';
}

public function predictiveConferenceRiskEngine()
{
    $this->requireAccess();

    $db = \App\Core\Database::getInstance();

    $rows = $db->query("
        SELECT
            c.id,
            c.short_name,
            COUNT(DISTINCT s.id) submissions,
            COUNT(DISTINCT ra.id) reviews,
            SUM(CASE WHEN ra.status<>'completed' AND ra.due_date<CURDATE() THEN 1 ELSE 0 END) overdue_reviews
        FROM conferences c
        LEFT JOIN submissions s ON s.conference_id=c.id
        LEFT JOIN review_assignments ra ON ra.submission_id=s.id
        GROUP BY c.id, c.short_name
        ORDER BY overdue_reviews DESC
    ")->fetchAll(\PDO::FETCH_ASSOC);

    foreach($rows as &$r) {
        $risk = min(100, ((int)$r['overdue_reviews'] * 8));
        $r['predicted_risk'] = $risk;
        $r['predicted_status'] = $risk >= 70 ? 'High' : ($risk >= 30 ? 'Watch' : 'Stable');
    }
    unset($r);

    ob_start();
    require BASE_PATH . '/app/views/admin/conference_home/predictive_conference_risk_engine.php';
    $content = ob_get_clean();
    require BASE_PATH . '/app/views/layouts/admin_layout.php';
}

public function executiveAiAssistant()
{
    $this->requireAccess();

    $overview = \App\Services\GovernanceEngine::platformOverview();
    $risks = \App\Services\GovernanceEngine::riskCounters();
    $platformHealth = \App\Services\GovernanceEngine::platformHealth();
    $actions = \App\Services\GovernanceEngine::recommendedActions();

    ob_start();
    require BASE_PATH . '/app/views/admin/conference_home/executive_ai_assistant.php';
    $content = ob_get_clean();
    require BASE_PATH . '/app/views/layouts/admin_layout.php';
}

public function publicationIntegrityMonitor()
{
    $this->requireAccess();

    $db = \App\Core\Database::getInstance();

    /*
    ---------------------------------------------------------
    Missing Proceedings Rows
    ---------------------------------------------------------
    */

    $missingProceedings = $db->query("
        SELECT
            s.id,
            s.submission_no,
            COALESCE(
                s.title,
                s.title_en,
                s.title_ar
            ) title,
            s.issue_id
        FROM submissions s
        LEFT JOIN proceedings_issue_articles pia
            ON pia.submission_id=s.id
        WHERE s.status='assigned_to_issue'
          AND pia.id IS NULL
        ORDER BY s.id DESC
    ")->fetchAll(\PDO::FETCH_ASSOC);

    /*
    ---------------------------------------------------------
    Missing Galleys
    ---------------------------------------------------------
    */

    $missingGalleys = $db->query("
        SELECT
            s.id,
            s.submission_no,
            pia.issue_id,
            pia.galley_id
        FROM proceedings_issue_articles pia
        JOIN submissions s
            ON s.id=pia.submission_id
        LEFT JOIN production_galleys g
            ON g.id=pia.galley_id
        WHERE g.id IS NULL
        ORDER BY s.id DESC
    ")->fetchAll(\PDO::FETCH_ASSOC);

    /*
    ---------------------------------------------------------
    Non Approved Galleys
    ---------------------------------------------------------
    */

    $nonApprovedGalleys = $db->query("
        SELECT
            s.id,
            s.submission_no,
            pia.issue_id,
            g.status
        FROM proceedings_issue_articles pia
        JOIN submissions s
            ON s.id=pia.submission_id
        JOIN production_galleys g
            ON g.id=pia.galley_id
        WHERE g.status<>'approved'
        ORDER BY s.id DESC
    ")->fetchAll(\PDO::FETCH_ASSOC);

    /*
    ---------------------------------------------------------
    Approved Galleys Not Assigned
    ---------------------------------------------------------
    */

    $readyForIssue = $db->query("
        SELECT
            s.id,
            s.submission_no,
            g.id galley_id
        FROM submissions s
        JOIN production_galleys g
            ON g.submission_id=s.id
        LEFT JOIN proceedings_issue_articles pia
            ON pia.submission_id=s.id
        WHERE g.status='approved'
          AND pia.id IS NULL
        ORDER BY s.id DESC
    ")->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/publication_integrity_monitor.php';

    $content = ob_get_clean();

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

public function publicationIntegrityRepair()
{
    $this->requireAccess();

    $db = \App\Core\Database::getInstance();

    $action =
        trim($_GET['action'] ?? '');

    $submissionId =
        (int)($_GET['submission_id'] ?? 0);

    /*
    --------------------------------------------------
    Repair Missing Galley
    --------------------------------------------------
    */

    if (
        $action === 'repair_galley'
        &&
        $submissionId > 0
    ) {

        $stmt = $db->prepare("
            SELECT id
            FROM production_galleys
            WHERE submission_id=?
              AND status='approved'
            ORDER BY id DESC
            LIMIT 1
        ");

        $stmt->execute([
            $submissionId
        ]);

        $galleyId =
            (int)$stmt->fetchColumn();

        if ($galleyId > 0) {

            $stmt = $db->prepare("
                UPDATE proceedings_issue_articles
                SET galley_id=?
                WHERE submission_id=?
            ");

            $stmt->execute([
                $galleyId,
                $submissionId
            ]);
        }
    }

    /*
    --------------------------------------------------
    Repair Missing Proceedings Row
    --------------------------------------------------
    */

    if (
        $action === 'repair_proceedings'
        &&
        $submissionId > 0
    ) {

        $stmt = $db->prepare("
            SELECT
                issue_id,
                conference_id,
                org_id
            FROM submissions
            WHERE id=?
        ");

        $stmt->execute([
            $submissionId
        ]);

        $s =
            $stmt->fetch(\PDO::FETCH_ASSOC);

        if (
            $s
            &&
            !empty($s['issue_id'])
        ) {

            $stmt = $db->prepare("
                INSERT IGNORE INTO
                proceedings_issue_articles
                (
                    org_id,
                    conference_id,
                    issue_id,
                    submission_id,
                    article_order
                )
                VALUES
                (
                    ?, ?, ?, ?, 999
                )
            ");

            $stmt->execute([
                $s['org_id'],
                $s['conference_id'],
                $s['issue_id'],
                $submissionId
            ]);
        }
    }

    header(
        "Location: /easychair/admin/conference-home/publication-integrity-monitor"
    );
    exit;
}

public function productionOperationsCenter()
{
    header(
        "Location: /easychair/admin/production"
    );
    exit;
}

public function issueBuilderWizard()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $issues =
        $db->query("
            SELECT *
            FROM proceedings_issues
            ORDER BY id DESC
        ")->fetchAll(\PDO::FETCH_ASSOC);

    $readyArticles =
        $db->query("
            SELECT
                s.id,
                s.submission_no,
                COALESCE(
                    s.title,
                    s.title_en,
                    s.title_ar
                ) title,
                g.id galley_id
            FROM submissions s
            INNER JOIN production_galleys g
                ON g.submission_id=s.id
               AND g.status='approved'
            LEFT JOIN proceedings_issue_articles pia
                ON pia.submission_id=s.id
            WHERE pia.id IS NULL
            ORDER BY s.id DESC
        ")->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/issue_builder_wizard.php';

    $content =
        ob_get_clean();

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

public function doiGenerator()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $rows =
        $db->query("
            SELECT
                s.id,
                s.submission_no,
                COALESCE(
                    s.title,
                    s.title_en,
                    s.title_ar
                ) title,
                s.doi,
                pia.issue_id,
                pia.article_order
            FROM submissions s
            LEFT JOIN proceedings_issue_articles pia
                ON pia.submission_id=s.id
            WHERE
                s.status IN
                (
                    'production',
                    'assigned_to_issue',
                    'published'
                )
            ORDER BY
                pia.issue_id,
                pia.article_order,
                s.id
        ")->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/doi_generator.php';

    $content =
        ob_get_clean();

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

public function generateDoi()
{
    $this->requireAccess();

    $submissionId =
        (int)($_GET['submission_id'] ?? 0);

    if (!$submissionId) {
        exit('Submission missing.');
    }

    $db =
        \App\Core\Database::getInstance();

    $stmt =
        $db->prepare("
            SELECT
                s.*,
                c.short_name,
                c.start_date
            FROM submissions s
            JOIN conferences c
                ON c.id=s.conference_id
            WHERE s.id=?
            LIMIT 1
        ");

    $stmt->execute([
        $submissionId
    ]);

    $row =
        $stmt->fetch(\PDO::FETCH_ASSOC);

    if (!$row) {
        exit('Submission not found.');
    }

    $year =
        date(
            'Y',
            strtotime(
                $row['start_date']
                ?: date('Y-m-d')
            )
        );

    $prefix =
        '10.99999';

    $doi =
        $prefix .
        '/' .
        strtoupper(
            preg_replace(
                '/[^A-Za-z0-9]/',
                '',
                $row['short_name']
            )
        ) .
        '.' .
        $year .
        '.' .
        str_pad(
            $submissionId,
            3,
            '0',
            STR_PAD_LEFT
        );

    $stmt =
        $db->prepare("
            UPDATE submissions
            SET doi=?
            WHERE id=?
        ");

    $stmt->execute([
        $doi,
        $submissionId
    ]);

    $stmt =
        $db->prepare("
            UPDATE proceedings_issue_articles
            SET doi=?
            WHERE submission_id=?
        ");

    $stmt->execute([
        $doi,
        $submissionId
    ]);

    header(
        'Location: /easychair/admin/conference-home/doi-generator'
    );
    exit;
}

public function proceedingsExportCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $issues =
        $db->query("
            SELECT
                i.*,
                COUNT(pia.id) article_count
            FROM proceedings_issues i
            LEFT JOIN proceedings_issue_articles pia
                ON pia.issue_id=i.id
            GROUP BY i.id
            ORDER BY i.id DESC
        ")->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/proceedings_export_center.php';

    $content =
        ob_get_clean();

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

public function exportIssueCsv()
{
    $this->requireAccess();

    $issueId =
        (int)($_GET['issue_id'] ?? 0);

    if (!$issueId) {
        exit('Issue ID missing.');
    }

    $db =
        \App\Core\Database::getInstance();

    $stmt =
        $db->prepare("
            SELECT
                pia.article_order,
                s.submission_no,
                COALESCE(
                    s.title,
                    s.title_en,
                    s.title_ar
                ) title,
                pia.page_from,
                pia.page_to,
                pia.doi
            FROM proceedings_issue_articles pia
            JOIN submissions s
                ON s.id=pia.submission_id
            WHERE pia.issue_id=?
            ORDER BY pia.article_order
        ");

    $stmt->execute([
        $issueId
    ]);

    header(
        'Content-Type: text/csv'
    );

    header(
        'Content-Disposition: attachment; filename=issue_' .
        $issueId .
        '.csv'
    );

    $out =
        fopen(
            'php://output',
            'w'
        );

    fputcsv(
        $out,
        [
            'Order',
            'Submission',
            'Title',
            'Page From',
            'Page To',
            'DOI'
        ]
    );

    while(
        $row =
        $stmt->fetch(\PDO::FETCH_ASSOC)
    ){
        fputcsv(
            $out,
            $row
        );
    }

    fclose($out);
    exit;
}

public function publicationAnalytics()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    /*
    ---------------------------------------------------------
    Submission Funnel
    ---------------------------------------------------------
    */

    $funnel = [

        'accepted' => 0,
        'camera_ready' => 0,
        'production' => 0,
        'assigned_to_issue' => 0,
        'published' => 0

    ];

    $rows =
        $db->query("
            SELECT
                status,
                production_status
            FROM submissions
        ")->fetchAll(\PDO::FETCH_ASSOC);

    foreach($rows as $r)
    {
        if (($r['status'] ?? '') === 'accepted') {
            $funnel['accepted']++;
        }

        if (
            ($r['production_status'] ?? '') ===
            'camera_ready_uploaded'
        ) {
            $funnel['camera_ready']++;
        }

        if (($r['status'] ?? '') === 'production') {
            $funnel['production']++;
        }

        if (($r['status'] ?? '') === 'assigned_to_issue') {
            $funnel['assigned_to_issue']++;
        }

        if (($r['status'] ?? '') === 'published') {
            $funnel['published']++;
        }
    }

    /*
    ---------------------------------------------------------
    Issue Metrics
    ---------------------------------------------------------
    */

    $issueMetrics =
        $db->query("
            SELECT
                i.id,
                i.volume_no,
                i.issue_no,
                COUNT(pia.id) article_count
            FROM proceedings_issues i
            LEFT JOIN proceedings_issue_articles pia
                ON pia.issue_id=i.id
            GROUP BY i.id
            ORDER BY i.id DESC
        ")->fetchAll(\PDO::FETCH_ASSOC);

    /*
    ---------------------------------------------------------
    DOI Metrics
    ---------------------------------------------------------
    */

    $doiCount =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE doi IS NOT NULL
              AND doi<>''
        ")->fetchColumn();

    $totalSubmissions =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
        ")->fetchColumn();

    /*
    ---------------------------------------------------------
    Integrity Metrics
    ---------------------------------------------------------
    */

    $missingGalleys =
        (int)$db->query("
            SELECT COUNT(*)
            FROM proceedings_issue_articles pia
            LEFT JOIN production_galleys g
                ON g.id=pia.galley_id
            WHERE g.id IS NULL
        ")->fetchColumn();

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/publication_analytics.php';

    $content =
        ob_get_clean();

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

public function crossrefDepositCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $rows =
        $db->query("
            SELECT
                s.id,
                s.submission_no,
                COALESCE(
                    s.title,
                    s.title_en,
                    s.title_ar
                ) title,
                s.doi,
                pia.issue_id,
                pia.page_from,
                pia.page_to,

                CASE
                    WHEN s.doi IS NULL
                      OR s.doi=''
                    THEN 'Missing DOI'

                    WHEN pia.issue_id IS NULL
                    THEN 'Missing Issue'

                    WHEN pia.page_from IS NULL
                    THEN 'Missing Pages'

                    ELSE 'Ready'
                END
                AS deposit_status

            FROM submissions s

            LEFT JOIN proceedings_issue_articles pia
                ON pia.submission_id=s.id

            WHERE
                s.production_status='approved'

            ORDER BY s.id DESC
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/crossref_deposit_center.php';

    $content =
        ob_get_clean();

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

public function indexingReadinessCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $rows =
        $db->query("
            SELECT
                s.id,
                s.submission_no,
                COALESCE(
                    s.title,
                    s.title_en,
                    s.title_ar
                ) title,

                s.abstract,
                s.doi,

                pia.issue_id,
                pia.page_from,
                pia.page_to,

                g.id galley_id,

                (
                    IF(
                        COALESCE(
                            s.title,
                            s.title_en,
                            s.title_ar
                        ) <> '',
                        15,
                        0
                    )

                    +

                    IF(
                        COALESCE(
                            s.abstract,
                            ''
                        ) <> '',
                        15,
                        0
                    )

                    +

                    IF(
                        COALESCE(
                            s.doi,
                            ''
                        ) <> '',
                        20,
                        0
                    )

                    +

                    IF(
                        pia.issue_id IS NOT NULL,
                        20,
                        0
                    )

                    +

                    IF(
                        pia.page_from IS NOT NULL,
                        15,
                        0
                    )

                    +

                    IF(
                        g.id IS NOT NULL,
                        15,
                        0
                    )

                ) AS readiness_score

            FROM submissions s

            LEFT JOIN proceedings_issue_articles pia
                ON pia.submission_id=s.id

            LEFT JOIN production_galleys g
                ON g.submission_id=s.id
               AND g.status='approved'

            WHERE
                s.production_status='approved'

           
            ORDER BY readiness_score DESC
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/indexing_readiness_center.php';

    $content =
        ob_get_clean();

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

public function publicationOperationsCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stats = [];

    $stats['accepted_pending'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='accepted'
              AND COALESCE(production_status,'pending')='pending'
        ")->fetchColumn();

    $stats['camera_ready_uploaded'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE production_status='camera_ready_uploaded'
        ")->fetchColumn();

    $stats['approved_galleys'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM production_galleys
            WHERE status='approved'
        ")->fetchColumn();

    $stats['assigned_to_issue'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='assigned_to_issue'
        ")->fetchColumn();

    $stats['published'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='published'
        ")->fetchColumn();

    $stats['broken_issue_links'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM proceedings_issue_articles pia
            LEFT JOIN production_galleys g
                   ON g.id=pia.galley_id
            WHERE g.id IS NULL
        ")->fetchColumn();

    $stats['indexing_ready'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE production_status='approved'
              AND COALESCE(doi,'')<>''
        ")->fetchColumn();

    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/publication_operations_center.php';

    $content =
        ob_get_clean();

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

public function publicationKpiDashboard()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stats = [];

    /*
    -----------------------------------------
    Total Publications
    -----------------------------------------
    */

    $stats['published'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='published'
        ")->fetchColumn();

    /*
    -----------------------------------------
    Assigned To Issue
    -----------------------------------------
    */

    $stats['assigned_to_issue'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='assigned_to_issue'
        ")->fetchColumn();

    /*
    -----------------------------------------
    Approved Galleys
    -----------------------------------------
    */

    $stats['approved_galleys'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM production_galleys
            WHERE status='approved'
        ")->fetchColumn();

    /*
    -----------------------------------------
    DOI Coverage
    -----------------------------------------
    */

    $stats['doi_count'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE production_status='approved'
              AND COALESCE(doi,'')<>''
        ")->fetchColumn();

    /*
    -----------------------------------------
    Indexing Ready
    -----------------------------------------
    */

    $stats['indexing_ready'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions s
            LEFT JOIN proceedings_issue_articles pia
                ON pia.submission_id=s.id
            WHERE
                s.production_status='approved'
                AND COALESCE(s.doi,'')<>''
                AND pia.issue_id IS NOT NULL
        ")->fetchColumn();

    /*
    -----------------------------------------
    Recent Publication Activity
    -----------------------------------------
    */

    $rows =
        $db->query("
            SELECT
                s.id,
                s.submission_no,
                COALESCE(
                    s.title,
                    s.title_en,
                    s.title_ar
                ) title,

                s.status,
                s.production_status,
                s.updated_at

            FROM submissions s

            WHERE
                s.production_status='approved'

            ORDER BY s.updated_at DESC

            LIMIT 25
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/publication_kpi_dashboard.php';

    $content =
        ob_get_clean();

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

public function doiManagementCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stats = [];

    $stats['total_records'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE
                production_status='approved'
                OR status='assigned_to_issue'
        ")->fetchColumn();

    $stats['missing_doi'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE
                (
                    production_status='approved'
                    OR status='assigned_to_issue'
                )
                AND COALESCE(doi,'')=''
        ")->fetchColumn();

    $stats['assigned_issue_missing_doi'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions s
            LEFT JOIN proceedings_issue_articles pia
                ON pia.submission_id=s.id
            WHERE
                pia.issue_id IS NOT NULL
                AND COALESCE(s.doi,'')=''
        ")->fetchColumn();

    $stats['ready_for_doi'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE
                production_status='approved'
                AND COALESCE(doi,'')=''
        ")->fetchColumn();

    $rows =
        $db->query("
            SELECT
                s.id,
                s.submission_no,

                COALESCE(
                    s.title,
                    s.title_en,
                    s.title_ar
                ) title,

                s.doi,

                pia.issue_id,

                i.doi_prefix,

                s.production_status

            FROM submissions s

            LEFT JOIN proceedings_issue_articles pia
                ON pia.submission_id=s.id

            LEFT JOIN proceedings_issues i
                ON i.id=pia.issue_id

            WHERE
            (
                s.production_status='approved'
                OR
                s.status='assigned_to_issue'
            )

            ORDER BY s.id DESC
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/doi_management_center.php';

    $content =
        ob_get_clean();

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

public function crossrefXmlExportCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $rows =
        $db->query("
            SELECT
                s.id,
                s.submission_no,

                COALESCE(
                    s.title,
                    s.title_en,
                    s.title_ar
                ) title,

                s.doi,

                pia.issue_id,

                i.volume_no,
                i.issue_no,
                i.publication_year,
                i.doi_prefix,

                g.id galley_id,

                (
                    IF(
                        COALESCE(s.doi,'')<>'',
                        25,
                        0
                    )

                    +

                    IF(
                        pia.issue_id IS NOT NULL,
                        25,
                        0
                    )

                    +

                    IF(
                        g.id IS NOT NULL,
                        25,
                        0
                    )

                    +

                    IF(
                        COALESCE(
                            s.title,
                            ''
                        )<>'',
                        25,
                        0
                    )

                ) xml_score

            FROM submissions s

            LEFT JOIN proceedings_issue_articles pia
                ON pia.submission_id=s.id

            LEFT JOIN proceedings_issues i
                ON i.id=pia.issue_id

            LEFT JOIN production_galleys g
                ON g.id=pia.galley_id

            WHERE
                s.production_status='approved'

            ORDER BY xml_score DESC,
                     s.id DESC
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/crossref_xml_export_center.php';

    $content =
        ob_get_clean();

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

public function publicationAnalyticsWarehouse()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stats = [];

    /*
    -----------------------------------------
    Total Submissions
    -----------------------------------------
    */

    $stats['submissions'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
        ")->fetchColumn();

    /*
    -----------------------------------------
    Published
    -----------------------------------------
    */

    $stats['published'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='published'
        ")->fetchColumn();

    /*
    -----------------------------------------
    Approved Production
    -----------------------------------------
    */

    $stats['approved'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE production_status='approved'
        ")->fetchColumn();

    /*
    -----------------------------------------
    DOI Coverage
    -----------------------------------------
    */

    $stats['doi'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE COALESCE(doi,'')<>''
        ")->fetchColumn();

    /*
    -----------------------------------------
    Indexing Ready
    -----------------------------------------
    */

    $stats['indexing_ready'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions s
            LEFT JOIN proceedings_issue_articles pia
                ON pia.submission_id=s.id
            WHERE
                s.production_status='approved'
                AND COALESCE(s.doi,'')<>''
                AND pia.issue_id IS NOT NULL
        ")->fetchColumn();

    /*
    -----------------------------------------
    Publication Health
    -----------------------------------------
    */

    $stats['health_score'] =
        (
            $stats['approved']
            +
            $stats['doi']
            +
            $stats['indexing_ready']
        ) > 0
        ?
        min(
            100,
            round(
                (
                    (
                        $stats['approved']
                        +
                        $stats['doi']
                        +
                        $stats['indexing_ready']
                    )
                    /
                    max(
                        1,
                        $stats['submissions']
                    )
                ) * 35
            )
        )
        :
        0;

    /*
    -----------------------------------------
    Issue Statistics
    -----------------------------------------
    */

    $issues =
        $db->query("
            SELECT
                id,
                volume_no,
                issue_no,
                publication_year,
                status
            FROM proceedings_issues
            ORDER BY id DESC
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/publication_analytics_warehouse.php';

    $content =
        ob_get_clean();

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

public function researchIntelligenceCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stats = [];

    /*
    ------------------------------------------------
    Total Authors
    ------------------------------------------------
    */

    $stats['authors'] =
        (int)$db->query("
            SELECT COUNT(DISTINCT author_id)
            FROM submissions
            WHERE author_id IS NOT NULL
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Total Reviewers
    ------------------------------------------------
    */

    $stats['reviewers'] =
        (int)$db->query("
            SELECT COUNT(DISTINCT reviewer_id)
            FROM review_assignments
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Accepted Papers
    ------------------------------------------------
    */

    $stats['accepted'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE
                status IN
                (
                    'accepted',
                    'production',
                    'assigned_to_issue',
                    'published'
                )
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Published Papers
    ------------------------------------------------
    */

    $stats['published'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE
                status='published'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Top Authors
    ------------------------------------------------
    */

    $topAuthors =
        $db->query("
            SELECT
                u.id,
                CONCAT(
                    COALESCE(u.first_name,''),
                    ' ',
                    COALESCE(u.last_name,'')
                ) author_name,

                COUNT(s.id) submissions

            FROM users u

            INNER JOIN submissions s
                ON s.author_id=u.id

            GROUP BY
                u.id

            ORDER BY
                submissions DESC

            LIMIT 20
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    /*
    ------------------------------------------------
    Top Reviewers
    ------------------------------------------------
    */

    $topReviewers =
        $db->query("
            SELECT
                u.id,

                CONCAT(
                    COALESCE(u.first_name,''),
                    ' ',
                    COALESCE(u.last_name,'')
                ) reviewer_name,

                COUNT(ra.id) reviews

            FROM users u

            INNER JOIN review_assignments ra
                ON ra.reviewer_id=u.id

            GROUP BY
                u.id

            ORDER BY
                reviews DESC

            LIMIT 20
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    /*
    ------------------------------------------------
    Track Analytics
    ------------------------------------------------
    */

    $trackAnalytics =
        $db->query("
            SELECT
                t.id,
                t.name_en,

                COUNT(s.id) submissions,

                SUM(
                    CASE
                    WHEN s.status IN
                    (
                        'accepted',
                        'production',
                        'assigned_to_issue',
                        'published'
                    )
                    THEN 1
                    ELSE 0
                    END
                ) accepted_count

            FROM tracks t

            LEFT JOIN submissions s
                ON s.track_id=t.id

            GROUP BY
                t.id,
                t.name_en

            ORDER BY
                submissions DESC
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/research_intelligence_center.php';

    $content =
        ob_get_clean();

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

public function reviewerIntelligenceCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stats = [];

    /*
    -----------------------------------------
    Total Reviewers
    -----------------------------------------
    */

    $stats['reviewers'] =
        (int)$db->query("
            SELECT COUNT(DISTINCT reviewer_id)
            FROM review_assignments
        ")->fetchColumn();

    /*
    -----------------------------------------
    Open Reviews
    -----------------------------------------
    */

    $stats['open_reviews'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM review_assignments
            WHERE status<>'completed'
        ")->fetchColumn();

    /*
    -----------------------------------------
    Completed Reviews
    -----------------------------------------
    */

    $stats['completed_reviews'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM review_assignments
            WHERE status='completed'
        ")->fetchColumn();

    /*
    -----------------------------------------
    Overdue Reviews
    -----------------------------------------
    */

    $stats['overdue_reviews'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM review_assignments
            WHERE status<>'completed'
              AND due_date IS NOT NULL
              AND due_date<CURDATE()
        ")->fetchColumn();

    /*
    -----------------------------------------
    Reviewer Load Analytics
    -----------------------------------------
    */

    $rows =
        $db->query("
            SELECT

                u.id,

                CONCAT(
                    COALESCE(u.first_name,''),
                    ' ',
                    COALESCE(u.last_name,'')
                ) reviewer_name,

                COUNT(ra.id) total_reviews,

                SUM(
                    CASE
                    WHEN ra.status='completed'
                    THEN 1
                    ELSE 0
                    END
                ) completed_reviews,

                SUM(
                    CASE
                    WHEN ra.status<>'completed'
                    THEN 1
                    ELSE 0
                    END
                ) open_reviews,

                SUM(
                    CASE
                    WHEN
                        ra.status<>'completed'
                        AND ra.due_date<CURDATE()
                    THEN 1
                    ELSE 0
                    END
                ) overdue_reviews

            FROM users u

            INNER JOIN review_assignments ra
                ON ra.reviewer_id=u.id

            GROUP BY
                u.id

            ORDER BY
                open_reviews DESC,
                overdue_reviews DESC
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/reviewer_intelligence_center.php';

    $content =
        ob_get_clean();

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

public function trackChairIntelligenceCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stats = [];

    /*
    -----------------------------------------
    Active Tracks
    -----------------------------------------
    */

    $stats['tracks'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM tracks
            WHERE is_active=1
        ")->fetchColumn();

    /*
    -----------------------------------------
    Track Chairs
    -----------------------------------------
    */

    $stats['track_chairs'] =
        (int)$db->query("
            SELECT COUNT(DISTINCT user_id)
            FROM track_chair_assignments
            WHERE is_active=1
        ")->fetchColumn();

    /*
    -----------------------------------------
    Assigned Tracks
    -----------------------------------------
    */

    $stats['assigned_tracks'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM track_chair_assignments
            WHERE is_active=1
        ")->fetchColumn();

    /*
    -----------------------------------------
    Track Analytics
    -----------------------------------------
    */

    $rows =
        $db->query("
            SELECT

                t.id,
                t.name_en,
                t.name_ar,

                COUNT(DISTINCT s.id)
                    submissions,

                COUNT(DISTINCT ra.id)
                    reviews,

                SUM(
                    CASE
                    WHEN s.status IN
                    (
                        'accepted',
                        'production',
                        'assigned_to_issue',
                        'published'
                    )
                    THEN 1
                    ELSE 0
                    END
                ) accepted_papers,

                COUNT(
                    DISTINCT tca.user_id
                ) track_chairs

            FROM tracks t

            LEFT JOIN submissions s
                ON s.track_id=t.id

            LEFT JOIN review_assignments ra
                ON ra.submission_id=s.id

            LEFT JOIN track_chair_assignments tca
                ON tca.track_id=t.id
               AND tca.is_active=1

            GROUP BY
                t.id,
                t.name_en,
                t.name_ar

            ORDER BY
                submissions DESC
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/track_chair_intelligence_center.php';

    $content =
        ob_get_clean();

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

public function conferenceCommandCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stats = [];

    /*
    ------------------------------------------------
    Submission Pipeline
    ------------------------------------------------
    */

    $stats['submitted'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='submitted'
        ")->fetchColumn();

    $stats['under_review'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='under_review'
        ")->fetchColumn();

    $stats['accepted'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status IN
            (
                'accepted',
                'production',
                'assigned_to_issue',
                'published'
            )
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Reviewer Intelligence
    ------------------------------------------------
    */

    $stats['reviewers'] =
        (int)$db->query("
            SELECT COUNT(DISTINCT reviewer_id)
            FROM review_assignments
        ")->fetchColumn();

    $stats['overdue_reviews'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM review_assignments
            WHERE status<>'completed'
              AND due_date<CURDATE()
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Track Intelligence
    ------------------------------------------------
    */

    $stats['tracks'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM tracks
            WHERE is_active=1
        ")->fetchColumn();

    $stats['track_chairs'] =
        (int)$db->query("
            SELECT COUNT(DISTINCT user_id)
            FROM track_chair_assignments
            WHERE is_active=1
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Publication Intelligence
    ------------------------------------------------
    */

    $stats['approved_galleys'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM production_galleys
            WHERE status='approved'
        ")->fetchColumn();

    $stats['assigned_to_issue'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='assigned_to_issue'
        ")->fetchColumn();

    $stats['published'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='published'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    DOI
    ------------------------------------------------
    */

    $stats['doi_count'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE COALESCE(doi,'')<>''
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Indexing
    ------------------------------------------------
    */

    $stats['indexing_ready'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions s
            LEFT JOIN proceedings_issue_articles pia
                ON pia.submission_id=s.id
            WHERE
                s.production_status='approved'
                AND COALESCE(s.doi,'')<>''
                AND pia.issue_id IS NOT NULL
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Platform Health
    ------------------------------------------------
    */

    $stats['health_score'] =
        min(
            100,
            (
                $stats['accepted']
                +
                $stats['approved_galleys']
                +
                $stats['assigned_to_issue']
                +
                $stats['doi_count']
            )
        );

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/conference_command_center.php';

    $content =
        ob_get_clean();

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

public function aiConferenceAdvisor()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $insights = [];

    /*
    ------------------------------------------------
    Overdue Reviews
    ------------------------------------------------
    */

    $overdueReviews =
        (int)$db->query("
            SELECT COUNT(*)
            FROM review_assignments
            WHERE status<>'completed'
              AND due_date<CURDATE()
        ")->fetchColumn();

    if ($overdueReviews > 0) {

        $insights[] = [
            'severity' => 'danger',
            'title' =>
                'Reviewer Delay Risk',
            'message' =>
                $overdueReviews .
                ' overdue reviews detected. Consider sending reminders.'
        ];
    }

    /*
    ------------------------------------------------
    Reviewer Overload
    ------------------------------------------------
    */

    $overloaded =
        $db->query("
            SELECT
                CONCAT(
                    COALESCE(u.first_name,''),
                    ' ',
                    COALESCE(u.last_name,'')
                ) reviewer_name,

                COUNT(ra.id) active_reviews

            FROM users u

            JOIN review_assignments ra
                ON ra.reviewer_id=u.id

            WHERE
                ra.status<>'completed'

            GROUP BY u.id

            HAVING COUNT(ra.id) >= 5

            ORDER BY active_reviews DESC

            LIMIT 5
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    foreach ($overloaded as $r) {

        $insights[] = [
            'severity' => 'warning',
            'title' =>
                'Reviewer Overload',
            'message' =>
                $r['reviewer_name']
                .
                ' currently has '
                .
                $r['active_reviews']
                .
                ' active reviews.'
        ];
    }

    /*
    ------------------------------------------------
    Missing DOI
    ------------------------------------------------
    */

    $missingDoi =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE
                production_status='approved'
                AND COALESCE(doi,'')=''
        ")->fetchColumn();

    if ($missingDoi > 0) {

        $insights[] = [
            'severity' => 'info',
            'title' =>
                'DOI Opportunity',
            'message' =>
                $missingDoi
                .
                ' approved papers still require DOI assignment.'
        ];
    }

    /*
    ------------------------------------------------
    Camera Ready Pending
    ------------------------------------------------
    */

    $cameraReady =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE production_status='camera_ready_uploaded'
        ")->fetchColumn();

    if ($cameraReady > 0) {

        $insights[] = [
            'severity' => 'primary',
            'title' =>
                'Production Queue',
            'message' =>
                $cameraReady
                .
                ' camera-ready files require production approval.'
        ];
    }

    /*
    ------------------------------------------------
    Track Risk
    ------------------------------------------------
    */

    $tracks =
        $db->query("
            SELECT
                t.name_en,
                COUNT(s.id) submissions
            FROM tracks t
            LEFT JOIN submissions s
                ON s.track_id=t.id
            GROUP BY
                t.id,
                t.name_en
            ORDER BY submissions DESC
            LIMIT 1
        ")
        ->fetch(\PDO::FETCH_ASSOC);

    if ($tracks) {

        $insights[] = [
            'severity' => 'secondary',
            'title' =>
                'Track Load',
            'message' =>
                $tracks['name_en']
                .
                ' is currently the busiest track with '
                .
                $tracks['submissions']
                .
                ' submissions.'
        ];
    }

    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/ai_conference_advisor.php';

    $content =
        ob_get_clean();

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

public function conferenceRiskRadar()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $risk = [];

    /*
    ------------------------------------------------
    Review Risk
    ------------------------------------------------
    */

    $overdueReviews =
        (int)$db->query("
            SELECT COUNT(*)
            FROM review_assignments
            WHERE status<>'completed'
              AND due_date IS NOT NULL
              AND due_date<CURDATE()
        ")->fetchColumn();

    $risk['review_risk'] =
        min(
            100,
            $overdueReviews * 10
        );

    /*
    ------------------------------------------------
    Production Risk
    ------------------------------------------------
    */

    $cameraReadyPending =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE production_status='camera_ready_uploaded'
        ")->fetchColumn();

    $risk['production_risk'] =
        min(
            100,
            $cameraReadyPending * 15
        );

    /*
    ------------------------------------------------
    DOI Risk
    ------------------------------------------------
    */

    $missingDoi =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE
                production_status='approved'
                AND COALESCE(doi,'')=''
        ")->fetchColumn();

    $risk['doi_risk'] =
        min(
            100,
            $missingDoi * 12
        );

    /*
    ------------------------------------------------
    Broken Issue Links
    ------------------------------------------------
    */

    $brokenIssues =
        (int)$db->query("
            SELECT COUNT(*)
            FROM proceedings_issue_articles pia
            LEFT JOIN production_galleys g
                   ON g.id=pia.galley_id
            WHERE g.id IS NULL
        ")->fetchColumn();

    $risk['issue_risk'] =
        min(
            100,
            $brokenIssues * 25
        );

    /*
    ------------------------------------------------
    Indexing Risk
    ------------------------------------------------
    */

    $indexingMissing =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE
                production_status='approved'
                AND COALESCE(doi,'')=''
        ")->fetchColumn();

    $risk['indexing_risk'] =
        min(
            100,
            $indexingMissing * 10
        );

    /*
    ------------------------------------------------
    Overall Risk
    ------------------------------------------------
    */

    $risk['overall'] =
        round(
            (
                $risk['review_risk']
                +
                $risk['production_risk']
                +
                $risk['doi_risk']
                +
                $risk['issue_risk']
                +
                $risk['indexing_risk']
            ) / 5
        );

    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/conference_risk_radar.php';

    $content =
        ob_get_clean();

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

public function conferenceBenchmarkCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $rows =
        $db->query("
            SELECT

                c.id,
                c.short_name,
                c.title_ar,

                COUNT(
                    DISTINCT s.id
                ) submissions,

                COUNT(
                    DISTINCT ra.id
                ) reviews,

                SUM(
                    CASE
                    WHEN s.status IN
                    (
                        'accepted',
                        'production',
                        'assigned_to_issue',
                        'published'
                    )
                    THEN 1
                    ELSE 0
                    END
                ) accepted_papers,

                SUM(
                    CASE
                    WHEN s.production_status='approved'
                    THEN 1
                    ELSE 0
                    END
                ) publication_ready,

                SUM(
                    CASE
                    WHEN
                        COALESCE(s.doi,'')<>''
                    THEN 1
                    ELSE 0
                    END
                ) doi_count

            FROM conferences c

            LEFT JOIN submissions s
                ON s.conference_id=c.id

            LEFT JOIN review_assignments ra
                ON ra.submission_id=s.id

            GROUP BY
                c.id,
                c.short_name,
                c.title_ar

            ORDER BY
                submissions DESC
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    foreach($rows as &$r)
    {
        $submissions =
            max(
                1,
                (int)$r['submissions']
            );

        $r['acceptance_rate'] =
            round(
                (
                    (int)$r['accepted_papers']
                    /
                    $submissions
                ) * 100,
                1
            );

        $r['doi_coverage'] =
            round(
                (
                    (int)$r['doi_count']
                    /
                    $submissions
                ) * 100,
                1
            );

        $r['benchmark_score'] =
            round(
                (
                    $r['acceptance_rate']
                    +
                    $r['doi_coverage']
                    +
                    (
                        (
                            (int)$r['publication_ready']
                            /
                            $submissions
                        ) * 100
                    )
                ) / 3
            );
    }

    unset($r);

    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/conference_benchmark_center.php';

    $content =
        ob_get_clean();

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

public function globalOperationsControlTower()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stats = [];

    /*
    ------------------------------------------------
    Organizations
    ------------------------------------------------
    */

    $stats['organizations'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM organizations
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Conferences
    ------------------------------------------------
    */

    $stats['conferences'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM conferences
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Users
    ------------------------------------------------
    */

    $stats['users'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM users
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Reviewers
    ------------------------------------------------
    */

    $stats['reviewers'] =
        (int)$db->query("
            SELECT COUNT(DISTINCT reviewer_id)
            FROM review_assignments
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Submissions
    ------------------------------------------------
    */

    $stats['submissions'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Published
    ------------------------------------------------
    */

    $stats['published'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='published'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Approved Production
    ------------------------------------------------
    */

    $stats['approved_production'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE production_status='approved'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    DOI Coverage
    ------------------------------------------------
    */

    $stats['doi_count'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE COALESCE(doi,'')<>''
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Platform Risk
    ------------------------------------------------
    */

    $stats['overdue_reviews'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM review_assignments
            WHERE status<>'completed'
              AND due_date IS NOT NULL
              AND due_date<CURDATE()
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Top Conferences
    ------------------------------------------------
    */

    $rows =
        $db->query("
            SELECT

                c.id,
                c.short_name,
                c.title_ar,

                COUNT(DISTINCT s.id)
                    submissions,

                SUM(
                    CASE
                    WHEN s.status IN
                    (
                        'accepted',
                        'production',
                        'assigned_to_issue',
                        'published'
                    )
                    THEN 1
                    ELSE 0
                    END
                ) accepted_papers

            FROM conferences c

            LEFT JOIN submissions s
                ON s.conference_id=c.id

            GROUP BY
                c.id,
                c.short_name,
                c.title_ar

            ORDER BY
                submissions DESC

            LIMIT 20
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/global_operations_control_tower.php';

    $content =
        ob_get_clean();

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

public function enterpriseGovernanceControlCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stats = [];

    /*
    ------------------------------------------------
    Roles
    ------------------------------------------------
    */

    $stats['roles'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM roles
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Menu Items
    ------------------------------------------------
    */

    $stats['menu_items'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM rbac_menu_items
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Permission Records
    ------------------------------------------------
    */

    $stats['permissions'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM rbac_role_menu_permissions
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Track Chair Assignments
    ------------------------------------------------
    */

    $stats['track_assignments'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM track_chair_assignments
            WHERE is_active=1
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Orphan Menu Items
    ------------------------------------------------
    */

    $stats['orphan_menu_items'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM rbac_menu_items m
            LEFT JOIN rbac_role_menu_permissions p
                   ON p.menu_item_id=m.id
            WHERE p.id IS NULL
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Inactive Roles
    ------------------------------------------------
    */

    $stats['unused_roles'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM roles r
            LEFT JOIN users u
                   ON u.role_id=r.id
            WHERE u.id IS NULL
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Governance Score
    ------------------------------------------------
    */

    $stats['governance_score'] =
        max(
            0,
            100
            -
            (
                ($stats['orphan_menu_items'] * 5)
                +
                ($stats['unused_roles'] * 2)
            )
        );

    /*
    ------------------------------------------------
    Governance Details
    ------------------------------------------------
    */

    $rows =
        $db->query("
            SELECT

                r.code,
                r.name,

                COUNT(
                    DISTINCT p.menu_item_id
                ) permission_count

            FROM roles r

            LEFT JOIN
                rbac_role_menu_permissions p
                ON p.role_id=r.id
               AND p.can_view=1

            GROUP BY
                r.id,
                r.code,
                r.name

            ORDER BY
                permission_count DESC
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/enterprise_governance_control_center.php';

    $content =
        ob_get_clean();

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

public function platformSecurityOperationsCenter()
{
    $this->requireAccess();

    $db = \App\Core\Database::getInstance();

    $stats = [];

    $stats['users'] = (int)$db->query("
        SELECT COUNT(*)
        FROM users
    ")->fetchColumn();

    $stats['roles'] = (int)$db->query("
        SELECT COUNT(*)
        FROM roles
    ")->fetchColumn();

    $stats['permissions'] = (int)$db->query("
        SELECT COUNT(*)
        FROM rbac_role_menu_permissions
    ")->fetchColumn();

    $stats['dormant_users'] = (int)$db->query("
        SELECT COUNT(*)
        FROM users
        WHERE last_login_at IS NULL
           OR last_login_at < DATE_SUB(NOW(), INTERVAL 180 DAY)
    ")->fetchColumn();

    $stats['orphan_permissions'] = (int)$db->query("
        SELECT COUNT(*)
        FROM rbac_menu_items m
        LEFT JOIN rbac_role_menu_permissions p
               ON p.menu_item_id = m.id
        WHERE p.id IS NULL
    ")->fetchColumn();

    $stats['track_chairs'] = (int)$db->query("
        SELECT COUNT(DISTINCT user_id)
        FROM track_chair_assignments
        WHERE is_active = 1
    ")->fetchColumn();

    $stats['security_score'] = max(
        0,
        100 - (
            ((int)$stats['orphan_permissions'] * 5)
            + (int)$stats['dormant_users']
        )
    );

    $rows = $db->query("
        SELECT
            r.id,
            r.code,
            r.name,
            COUNT(DISTINCT p.menu_item_id) AS permission_count
        FROM roles r
        LEFT JOIN rbac_role_menu_permissions p
               ON p.role_id = r.id
              AND p.can_view = 1
        GROUP BY
            r.id,
            r.code,
            r.name
        ORDER BY
            permission_count DESC
    ")->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/platform_security_operations_center.php';

    $content = ob_get_clean();

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

public function enterpriseAuditActivityCenter()
{
    $this->requireAccess();

    $db = \App\Core\Database::getInstance();

    $stats = [];

    $stats['submission_activity'] = (int)$db->query("
        SELECT COUNT(*)
        FROM submission_activity_log
    ")->fetchColumn();

    $stats['recent_submission_activity'] = (int)$db->query("
        SELECT COUNT(*)
        FROM submission_activity_log
        WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
    ")->fetchColumn();

    $stats['workflow_updates'] = (int)$db->query("
        SELECT COUNT(*)
        FROM submission_activity_log
        WHERE event_key LIKE '%workflow%'
           OR event_key LIKE '%status%'
           OR event_key LIKE '%decision%'
    ")->fetchColumn();

    $stats['author_events'] = (int)$db->query("
        SELECT COUNT(*)
        FROM submission_activity_log
        WHERE actor_role='author'
    ")->fetchColumn();

    $stats['admin_events'] = (int)$db->query("
        SELECT COUNT(*)
        FROM submission_activity_log
        WHERE actor_role IN ('admin','super_admin','conference_chair','org_admin')
    ")->fetchColumn();

    $rows = $db->query("
        SELECT
            l.id,
            l.submission_id,
            s.submission_no,
            COALESCE(s.title,s.title_en,s.title_ar) AS title,
            l.actor_id,
            l.actor_role,
            l.event_key,
            l.event_title,
            l.created_at
        FROM submission_activity_log l
        LEFT JOIN submissions s
               ON s.id = l.submission_id
        ORDER BY l.id DESC
        LIMIT 100
    ")->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/enterprise_audit_activity_center.php';

    $content = ob_get_clean();

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

public function userAccessIntelligenceCenter()
{
    $this->requireAccess();

    $db = \App\Core\Database::getInstance();

    $stats = [];

    $stats['users'] = (int)$db->query("
        SELECT COUNT(*)
        FROM users
    ")->fetchColumn();

    $stats['active_users'] = (int)$db->query("
        SELECT COUNT(*)
        FROM users
        WHERE last_login_at IS NOT NULL
          AND last_login_at >= DATE_SUB(NOW(), INTERVAL 90 DAY)
    ")->fetchColumn();

    $stats['dormant_users'] = (int)$db->query("
        SELECT COUNT(*)
        FROM users
        WHERE last_login_at IS NULL
           OR last_login_at < DATE_SUB(NOW(), INTERVAL 180 DAY)
    ")->fetchColumn();

    $stats['users_without_role'] = (int)$db->query("
        SELECT COUNT(*)
        FROM users u
        LEFT JOIN roles r
               ON r.id = u.role_id
        WHERE r.id IS NULL
    ")->fetchColumn();

    $stats['conference_users'] = (int)$db->query("
        SELECT COUNT(*)
        FROM conference_user_roles
    ")->fetchColumn();

    $rows = $db->query("
        SELECT
            u.id,
            CONCAT(COALESCE(u.first_name,''),' ',COALESCE(u.last_name,'')) AS full_name,
            u.email,
            r.code AS role_code,
            u.last_login_at
        FROM users u
        LEFT JOIN roles r
               ON r.id = u.role_id
        ORDER BY
            u.last_login_at IS NULL DESC,
            u.last_login_at ASC
        LIMIT 100
    ")->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/user_access_intelligence_center.php';

    $content = ob_get_clean();

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

public function platformDataQualityCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stats = [];

    /*
    ------------------------------------------------
    Submissions Without Conference
    ------------------------------------------------
    */

    $stats['orphan_submissions'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions s
            LEFT JOIN conferences c
                   ON c.id=s.conference_id
            WHERE c.id IS NULL
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Reviews Without Submission
    ------------------------------------------------
    */

    $stats['orphan_reviews'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM review_assignments ra
            LEFT JOIN submissions s
                   ON s.id=ra.submission_id
            WHERE s.id IS NULL
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Missing DOI
    ------------------------------------------------
    */

    $stats['missing_doi'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE production_status='approved'
              AND COALESCE(doi,'')=''
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Approved Without Issue
    ------------------------------------------------
    */

    $stats['approved_without_issue'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE production_status='approved'
              AND issue_id IS NULL
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Broken Issue Articles
    ------------------------------------------------
    */

    $stats['broken_issue_articles'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM proceedings_issue_articles pia
            LEFT JOIN production_galleys g
                   ON g.id=pia.galley_id
            WHERE g.id IS NULL
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Conferences Missing Dates
    ------------------------------------------------
    */

    $stats['conference_date_gaps'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM conferences
            WHERE submission_start IS NULL
               OR submission_end IS NULL
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Quality Score
    ------------------------------------------------
    */

    $issues =
        $stats['orphan_submissions']
        +
        $stats['orphan_reviews']
        +
        $stats['missing_doi']
        +
        $stats['broken_issue_articles'];

    $stats['quality_score'] =
        max(
            0,
            100 - $issues
        );

    /*
    ------------------------------------------------
    Conference Health
    ------------------------------------------------
    */

    $rows =
        $db->query("
            SELECT

                c.id,
                c.short_name,

                COALESCE(
                    c.title_en,
                    c.title_ar,
                    c.short_name
                ) conference_title,

                COUNT(DISTINCT s.id)
                    submissions,

                SUM(
                    CASE
                    WHEN COALESCE(s.doi,'')=''
                    THEN 1
                    ELSE 0
                    END
                ) missing_doi

            FROM conferences c

            LEFT JOIN submissions s
                ON s.conference_id=c.id

            GROUP BY
                c.id,
                c.short_name,
                c.title_en,
                c.title_ar

            ORDER BY
                missing_doi DESC,
                submissions DESC
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/platform_data_quality_center.php';

    $content =
        ob_get_clean();

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

public function platformPerformanceCapacityCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stats = [];

    /*
    ------------------------------------------------
    Conferences
    ------------------------------------------------
    */

    $stats['conferences'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM conferences
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Tracks
    ------------------------------------------------
    */

    $stats['tracks'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM tracks
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Submissions
    ------------------------------------------------
    */

    $stats['submissions'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Review Assignments
    ------------------------------------------------
    */

    $stats['review_assignments'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM review_assignments
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Active Reviewers
    ------------------------------------------------
    */

    $stats['reviewers'] =
        (int)$db->query("
            SELECT COUNT(DISTINCT reviewer_id)
            FROM review_assignments
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Average Reviews Per Reviewer
    ------------------------------------------------
    */

    $stats['avg_reviews_per_reviewer'] =
        round(
            $stats['reviewers'] > 0
            ?
            (
                $stats['review_assignments']
                /
                $stats['reviewers']
            )
            :
            0,
            2
        );

    /*
    ------------------------------------------------
    Capacity Score
    ------------------------------------------------
    */

    $stats['capacity_score'] =
        min(
            100,
            round(
                (
                    $stats['reviewers'] * 10
                )
                /
                max(
                    1,
                    $stats['review_assignments']
                )
                * 100
            )
        );

    /*
    ------------------------------------------------
    Conference Capacity Table
    ------------------------------------------------
    */

    $rows =
        $db->query("
            SELECT

                c.id,

                c.short_name,

                COALESCE(
                    c.title_en,
                    c.title_ar,
                    c.short_name
                ) conference_title,

                COUNT(
                    DISTINCT s.id
                ) submissions,

                COUNT(
                    DISTINCT ra.id
                ) reviews,

                COUNT(
                    DISTINCT t.id
                ) tracks

            FROM conferences c

            LEFT JOIN submissions s
                ON s.conference_id=c.id

            LEFT JOIN review_assignments ra
                ON ra.submission_id=s.id

            LEFT JOIN tracks t
                ON t.conference_id=c.id

            GROUP BY
                c.id,
                c.short_name,
                c.title_en,
                c.title_ar

            ORDER BY
                submissions DESC
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/platform_performance_capacity_center.php';

    $content =
        ob_get_clean();

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

public function platformGrowthTrendAnalyticsCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stats = [];

    /*
    ------------------------------------------------
    Conferences
    ------------------------------------------------
    */

    $stats['conferences'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM conferences
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Submissions
    ------------------------------------------------
    */

    $stats['submissions'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Reviewers
    ------------------------------------------------
    */

    $stats['reviewers'] =
        (int)$db->query("
            SELECT COUNT(DISTINCT reviewer_id)
            FROM review_assignments
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Published Articles
    ------------------------------------------------
    */

    $stats['published'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='published'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Monthly Submission Trend
    ------------------------------------------------
    */

    $submissionTrend =
        $db->query("
            SELECT

                DATE_FORMAT(
                    created_at,
                    '%Y-%m'
                ) period,

                COUNT(*) total

            FROM submissions

            WHERE created_at IS NOT NULL

            GROUP BY
                DATE_FORMAT(
                    created_at,
                    '%Y-%m'
                )

            ORDER BY period DESC

            LIMIT 12
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    /*
    ------------------------------------------------
    Monthly Review Trend
    ------------------------------------------------
    */

    $reviewTrend =
        $db->query("
            SELECT

                DATE_FORMAT(
                    created_at,
                    '%Y-%m'
                ) period,

                COUNT(*) total

            FROM review_assignments

            WHERE created_at IS NOT NULL

            GROUP BY
                DATE_FORMAT(
                    created_at,
                    '%Y-%m'
                )

            ORDER BY period DESC

            LIMIT 12
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    /*
    ------------------------------------------------
    Conference Activity
    ------------------------------------------------
    */

    $conferenceRows =
        $db->query("
            SELECT

                c.id,
                c.short_name,

                COALESCE(
                    c.title_en,
                    c.title_ar,
                    c.short_name
                ) conference_title,

                COUNT(
                    DISTINCT s.id
                ) submissions,

                COUNT(
                    DISTINCT ra.id
                ) reviews

            FROM conferences c

            LEFT JOIN submissions s
                ON s.conference_id=c.id

            LEFT JOIN review_assignments ra
                ON ra.submission_id=s.id

            GROUP BY
                c.id,
                c.short_name,
                c.title_en,
                c.title_ar

            ORDER BY
                submissions DESC
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/platform_growth_trend_analytics_center.php';

    $content =
        ob_get_clean();

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

public function executiveKpiCommandCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stats = [];

    /*
    ------------------------------------------------
    Platform
    ------------------------------------------------
    */

    $stats['organizations'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM organizations
        ")->fetchColumn();

    $stats['conferences'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM conferences
        ")->fetchColumn();

    $stats['users'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM users
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Workflow
    ------------------------------------------------
    */

    $stats['submissions'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
        ")->fetchColumn();

    $stats['under_review'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='under_review'
        ")->fetchColumn();

    $stats['accepted'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status IN
            (
                'accepted',
                'production',
                'assigned_to_issue',
                'published'
            )
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Publication
    ------------------------------------------------
    */

    $stats['approved_production'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE production_status='approved'
        ")->fetchColumn();

    $stats['published'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='published'
        ")->fetchColumn();

    $stats['doi_count'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE COALESCE(doi,'') <> ''
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Security
    ------------------------------------------------
    */

    $stats['dormant_users'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM users
            WHERE last_login_at IS NULL
               OR last_login_at <
                  DATE_SUB(
                      NOW(),
                      INTERVAL 180 DAY
                  )
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Governance
    ------------------------------------------------
    */

    $stats['roles'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM roles
        ")->fetchColumn();

    $stats['permissions'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM rbac_role_menu_permissions
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Executive Score
    ------------------------------------------------
    */

    $qualityWeight =
        min(
            100,
            $stats['approved_production']
        );

    $securityWeight =
        max(
            0,
            100 - $stats['dormant_users']
        );

    $activityWeight =
        min(
            100,
            $stats['submissions']
        );

    $stats['executive_score'] =
        round(
            (
                $qualityWeight
                +
                $securityWeight
                +
                $activityWeight
            ) / 3
        );

    /*
    ------------------------------------------------
    Conference Ranking
    ------------------------------------------------
    */

    $rows =
        $db->query("
            SELECT

                c.id,

                c.short_name,

                COALESCE(
                    c.title_en,
                    c.title_ar,
                    c.short_name
                ) conference_title,

                COUNT(
                    DISTINCT s.id
                ) submissions,

                SUM(
                    CASE
                    WHEN s.status IN
                    (
                        'accepted',
                        'production',
                        'assigned_to_issue',
                        'published'
                    )
                    THEN 1
                    ELSE 0
                    END
                ) accepted

            FROM conferences c

            LEFT JOIN submissions s
                ON s.conference_id=c.id

            GROUP BY
                c.id,
                c.short_name,
                c.title_en,
                c.title_ar

            ORDER BY
                submissions DESC
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/executive_kpi_command_center.php';

    $content =
        ob_get_clean();

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

public function aiGovernanceDecisionIntelligenceCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $insights = [];

    /*
    ------------------------------------------------
    Overdue Reviews
    ------------------------------------------------
    */

    $overdueReviews =
        (int)$db->query("
            SELECT COUNT(*)
            FROM review_assignments
            WHERE status<>'completed'
              AND due_date IS NOT NULL
              AND due_date<CURDATE()
        ")->fetchColumn();

    if ($overdueReviews > 0) {

        $insights[] = [
            'severity' => 'danger',
            'title' =>
                'Reviewer Bottleneck Detected',
            'message' =>
                $overdueReviews .
                ' overdue review assignments require intervention.'
        ];
    }

    /*
    ------------------------------------------------
    Dormant Users
    ------------------------------------------------
    */

    $dormantUsers =
        (int)$db->query("
            SELECT COUNT(*)
            FROM users
            WHERE last_login_at IS NULL
               OR last_login_at <
                  DATE_SUB(
                      NOW(),
                      INTERVAL 180 DAY
                  )
        ")->fetchColumn();

    if ($dormantUsers > 10) {

        $insights[] = [
            'severity' => 'warning',
            'title' =>
                'Dormant User Risk',
            'message' =>
                $dormantUsers .
                ' dormant accounts should be reviewed.'
        ];
    }

    /*
    ------------------------------------------------
    Missing DOI
    ------------------------------------------------
    */

    $missingDoi =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE production_status='approved'
              AND COALESCE(doi,'')=''
        ")->fetchColumn();

    if ($missingDoi > 0) {

        $insights[] = [
            'severity' => 'warning',
            'title' =>
                'Publication Metadata Gap',
            'message' =>
                $missingDoi .
                ' approved articles have no DOI.'
        ];
    }

    /*
    ------------------------------------------------
    Camera Ready Waiting
    ------------------------------------------------
    */

    $cameraReady =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE production_status='camera_ready_uploaded'
        ")->fetchColumn();

    if ($cameraReady > 0) {

        $insights[] = [
            'severity' => 'info',
            'title' =>
                'Production Queue',
            'message' =>
                $cameraReady .
                ' submissions are waiting for production approval.'
        ];
    }

    /*
    ------------------------------------------------
    Track Chair Capacity
    ------------------------------------------------
    */

    $trackChairs =
        (int)$db->query("
            SELECT COUNT(DISTINCT user_id)
            FROM track_chair_assignments
            WHERE is_active=1
        ")->fetchColumn();

    if ($trackChairs == 0) {

        $insights[] = [
            'severity' => 'danger',
            'title' =>
                'Governance Coverage Risk',
            'message' =>
                'No active track chair assignments found.'
        ];
    }

    /*
    ------------------------------------------------
    Conference Health
    ------------------------------------------------
    */

    $conferenceHealth =
        $db->query("
            SELECT

                c.id,
                c.short_name,

                COALESCE(
                    c.title_en,
                    c.title_ar,
                    c.short_name
                ) conference_title,

                COUNT(
                    DISTINCT s.id
                ) submissions,

                SUM(
                    CASE
                    WHEN s.status='under_review'
                    THEN 1
                    ELSE 0
                    END
                ) under_review,

                SUM(
                    CASE
                    WHEN s.status='accepted'
                    THEN 1
                    ELSE 0
                    END
                ) accepted

            FROM conferences c

            LEFT JOIN submissions s
                ON s.conference_id=c.id

            GROUP BY
                c.id,
                c.short_name,
                c.title_en,
                c.title_ar

            ORDER BY
                submissions DESC
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/ai_governance_decision_intelligence_center.php';

    $content =
        ob_get_clean();

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

public function strategicPlanningForecastIntelligenceCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stats = [];

    /*
    ------------------------------------------------
    Current Capacity
    ------------------------------------------------
    */

    $stats['submissions'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
        ")->fetchColumn();

    $stats['reviewers'] =
        (int)$db->query("
            SELECT COUNT(DISTINCT reviewer_id)
            FROM review_assignments
        ")->fetchColumn();

    $stats['tracks'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM tracks
        ")->fetchColumn();

    $stats['conferences'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM conferences
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Forecast Model
    ------------------------------------------------
    */

    $stats['forecast_submissions'] =
        (int)round(
            $stats['submissions'] * 1.15
        );

    $stats['forecast_reviewers'] =
        (int)ceil(
            $stats['forecast_submissions'] / 3
        );

    $stats['forecast_tracks'] =
        max(
            $stats['tracks'],
            (int)ceil(
                $stats['forecast_submissions'] / 50
            )
        );

    /*
    ------------------------------------------------
    Strategic Recommendations
    ------------------------------------------------
    */

    $recommendations = [];

    if (
        $stats['forecast_reviewers']
        >
        $stats['reviewers']
    ) {

        $recommendations[] = [
            'severity' => 'warning',
            'title' =>
                'Reviewer Recruitment',
            'message' =>
                'Projected reviewer demand exceeds current reviewer capacity.'
        ];
    }

    if (
        $stats['forecast_tracks']
        >
        $stats['tracks']
    ) {

        $recommendations[] = [
            'severity' => 'info',
            'title' =>
                'Track Expansion',
            'message' =>
                'Additional tracks may be required based on forecasted submission growth.'
        ];
    }

    /*
    ------------------------------------------------
    Conference Planning Table
    ------------------------------------------------
    */

    $rows =
        $db->query("
            SELECT

                c.id,
                c.short_name,

                COALESCE(
                    c.title_en,
                    c.title_ar,
                    c.short_name
                ) conference_title,

                COUNT(
                    DISTINCT s.id
                ) submissions,

                COUNT(
                    DISTINCT t.id
                ) tracks

            FROM conferences c

            LEFT JOIN submissions s
                ON s.conference_id=c.id

            LEFT JOIN tracks t
                ON t.conference_id=c.id

            GROUP BY
                c.id,
                c.short_name,
                c.title_en,
                c.title_ar

            ORDER BY
                submissions DESC
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/strategic_planning_forecast_intelligence_center.php';

    $content =
        ob_get_clean();

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

public function enterpriseWorkflowOptimizationCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stats = [];

    /*
    ------------------------------------------------
    Submission Stage
    ------------------------------------------------
    */

    $stats['submitted'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='submitted'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Under Review
    ------------------------------------------------
    */

    $stats['under_review'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='under_review'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Revision Required
    ------------------------------------------------
    */

    $stats['revision_required'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='revision_required'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Accepted
    ------------------------------------------------
    */

    $stats['accepted'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='accepted'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Production Queue
    ------------------------------------------------
    */

    $stats['production_queue'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE production_status='camera_ready_uploaded'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Approved Production
    ------------------------------------------------
    */

    $stats['approved_production'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE production_status='approved'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Assigned To Issue
    ------------------------------------------------
    */

    $stats['assigned_to_issue'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='assigned_to_issue'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Published
    ------------------------------------------------
    */

    $stats['published'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='published'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Workflow Recommendations
    ------------------------------------------------
    */

    $recommendations = [];

    if ($stats['under_review'] > 20) {

        $recommendations[] = [
            'severity' => 'warning',
            'title' =>
                'Review Queue Congestion',
            'message' =>
                $stats['under_review'] .
                ' submissions remain under review.'
        ];
    }

    if ($stats['revision_required'] > 10) {

        $recommendations[] = [
            'severity' => 'info',
            'title' =>
                'Revision Follow-up',
            'message' =>
                $stats['revision_required'] .
                ' submissions require author revisions.'
        ];
    }

    if ($stats['production_queue'] > 0) {

        $recommendations[] = [
            'severity' => 'warning',
            'title' =>
                'Production Backlog',
            'message' =>
                $stats['production_queue'] .
                ' camera-ready files await approval.'
        ];
    }

    /*
    ------------------------------------------------
    Workflow Funnel
    ------------------------------------------------
    */

    $funnel = [
        [
            'stage' => 'Submitted',
            'total' => $stats['submitted']
        ],
        [
            'stage' => 'Under Review',
            'total' => $stats['under_review']
        ],
        [
            'stage' => 'Revision Required',
            'total' => $stats['revision_required']
        ],
        [
            'stage' => 'Accepted',
            'total' => $stats['accepted']
        ],
        [
            'stage' => 'Production Approved',
            'total' => $stats['approved_production']
        ],
        [
            'stage' => 'Assigned To Issue',
            'total' => $stats['assigned_to_issue']
        ],
        [
            'stage' => 'Published',
            'total' => $stats['published']
        ]
    ];

    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/enterprise_workflow_optimization_center.php';

    $content =
        ob_get_clean();

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

public function researchImpactPublicationIntelligenceCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stats = [];

    /*
    ------------------------------------------------
    Total Published
    ------------------------------------------------
    */

    $stats['published'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='published'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Production Approved
    ------------------------------------------------
    */

    $stats['production_approved'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE production_status='approved'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    DOI Coverage
    ------------------------------------------------
    */

    $stats['doi_count'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE COALESCE(doi,'')<>''
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Assigned To Issue
    ------------------------------------------------
    */

    $stats['assigned_to_issue'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='assigned_to_issue'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Approved Galleys
    ------------------------------------------------
    */

    $stats['approved_galleys'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM production_galleys
            WHERE status='approved'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Missing DOI
    ------------------------------------------------
    */

    $stats['missing_doi'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE production_status='approved'
              AND COALESCE(doi,'')=''
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Broken Issue Links
    ------------------------------------------------
    */

    $stats['broken_issue_links'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM proceedings_issue_articles pia
            LEFT JOIN production_galleys g
                   ON g.id=pia.galley_id
            WHERE g.id IS NULL
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Publication Readiness Score
    ------------------------------------------------
    */

    $penalty =
        ($stats['missing_doi'] * 5)
        +
        ($stats['broken_issue_links'] * 10);

    $stats['publication_score'] =
        max(
            0,
            100 - $penalty
        );

    /*
    ------------------------------------------------
    Publication Intelligence
    ------------------------------------------------
    */

    $rows =
        $db->query("
            SELECT

                s.id,
                s.submission_no,

                COALESCE(
                    s.title,
                    s.title_en,
                    s.title_ar
                ) title,

                s.status,
                s.production_status,
                s.doi,

                pia.issue_id,

                g.id AS galley_id,
                g.status AS galley_status

            FROM submissions s

            LEFT JOIN proceedings_issue_articles pia
                ON pia.submission_id=s.id

            LEFT JOIN production_galleys g
                ON g.id=
                (
                    SELECT MAX(g2.id)
                    FROM production_galleys g2
                    WHERE g2.submission_id=s.id
                )

            WHERE
                s.production_status='approved'

            ORDER BY s.id DESC
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/research_impact_publication_intelligence_center.php';

    $content =
        ob_get_clean();

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

public function enterpriseComplianceAccreditationIntelligenceCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stats = [];

    /*
    ------------------------------------------------
    Conferences
    ------------------------------------------------
    */

    $stats['conferences'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM conferences
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Conferences Missing Dates
    ------------------------------------------------
    */

    $stats['conference_gaps'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM conferences
            WHERE submission_start IS NULL
               OR submission_end IS NULL
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Approved Publications Missing DOI
    ------------------------------------------------
    */

    $stats['missing_doi'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE production_status='approved'
              AND COALESCE(doi,'')=''
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Orphan Menu Permissions
    ------------------------------------------------
    */

    $stats['orphan_permissions'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM rbac_menu_items m
            LEFT JOIN
                rbac_role_menu_permissions p
                ON p.menu_item_id=m.id
            WHERE p.id IS NULL
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Dormant Accounts
    ------------------------------------------------
    */

    $stats['dormant_users'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM users
            WHERE last_login_at IS NULL
               OR last_login_at <
                  DATE_SUB(
                      NOW(),
                      INTERVAL 180 DAY
                  )
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Overdue Reviews
    ------------------------------------------------
    */

    $stats['overdue_reviews'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM review_assignments
            WHERE status<>'completed'
              AND due_date IS NOT NULL
              AND due_date<CURDATE()
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Compliance Score
    ------------------------------------------------
    */

    $penalty =
        ($stats['conference_gaps'] * 5)
        +
        ($stats['missing_doi'] * 5)
        +
        ($stats['orphan_permissions'] * 5)
        +
        ($stats['overdue_reviews']);

    $stats['compliance_score'] =
        max(
            0,
            100 - $penalty
        );

    /*
    ------------------------------------------------
    Compliance Findings
    ------------------------------------------------
    */

    $findings = [];

    if ($stats['conference_gaps'] > 0) {

        $findings[] = [
            'severity'=>'warning',
            'title'=>'Conference Configuration',
            'message'=>
                $stats['conference_gaps']
                . ' conferences have incomplete submission dates.'
        ];
    }

    if ($stats['missing_doi'] > 0) {

        $findings[] = [
            'severity'=>'warning',
            'title'=>'Publication Compliance',
            'message'=>
                $stats['missing_doi']
                . ' approved publications have no DOI.'
        ];
    }

    if ($stats['orphan_permissions'] > 0) {

        $findings[] = [
            'severity'=>'danger',
            'title'=>'RBAC Governance',
            'message'=>
                $stats['orphan_permissions']
                . ' menu items have no permission mapping.'
        ];
    }

    if ($stats['overdue_reviews'] > 0) {

        $findings[] = [
            'severity'=>'info',
            'title'=>'Review Compliance',
            'message'=>
                $stats['overdue_reviews']
                . ' overdue reviews require action.'
        ];
    }

    /*
    ------------------------------------------------
    Conference Compliance
    ------------------------------------------------
    */

    $rows =
        $db->query("
            SELECT

                c.id,

                c.short_name,

                COALESCE(
                    c.title_en,
                    c.title_ar,
                    c.short_name
                ) conference_title,

                COUNT(
                    DISTINCT s.id
                ) submissions,

                SUM(
                    CASE
                    WHEN COALESCE(s.doi,'')=''
                    THEN 1
                    ELSE 0
                    END
                ) missing_doi

            FROM conferences c

            LEFT JOIN submissions s
                ON s.conference_id=c.id

            GROUP BY
                c.id,
                c.short_name,
                c.title_en,
                c.title_ar

            ORDER BY
                missing_doi DESC,
                submissions DESC
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/enterprise_compliance_accreditation_intelligence_center.php';

    $content =
        ob_get_clean();

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

public function institutionalBenchmarkingExcellenceIntelligenceCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stats = [];

    /*
    ------------------------------------------------
    Conferences
    ------------------------------------------------
    */

    $stats['conferences'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM conferences
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Reviewers
    ------------------------------------------------
    */

    $stats['reviewers'] =
        (int)$db->query("
            SELECT COUNT(DISTINCT reviewer_id)
            FROM review_assignments
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Published
    ------------------------------------------------
    */

    $stats['published'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='published'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Approved Production
    ------------------------------------------------
    */

    $stats['approved_publications'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE production_status='approved'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Governance Maturity
    ------------------------------------------------
    */

    $roles =
        (int)$db->query("
            SELECT COUNT(*)
            FROM roles
        ")->fetchColumn();

    $permissions =
        (int)$db->query("
            SELECT COUNT(*)
            FROM rbac_role_menu_permissions
        ")->fetchColumn();

    $stats['governance_score'] =
        min(
            100,
            (int)(
                ($roles * 5)
                +
                ($permissions / 10)
            )
        );

    /*
    ------------------------------------------------
    Operational Excellence
    ------------------------------------------------
    */

    $published =
        $stats['published'];

    $approved =
        max(
            1,
            $stats['approved_publications']
        );

    $stats['operational_score'] =
        min(
            100,
            (int)(
                ($published / $approved)
                * 100
            )
        );

    /*
    ------------------------------------------------
    Institutional Excellence Score
    ------------------------------------------------
    */

    $stats['excellence_score'] =
        (int)round(
            (
                $stats['governance_score']
                +
                $stats['operational_score']
            ) / 2
        );

    /*
    ------------------------------------------------
    Conference Benchmark Ranking
    ------------------------------------------------
    */

    $conferenceRows =
        $db->query("
            SELECT

                c.id,

                c.short_name,

                COALESCE(
                    c.title_en,
                    c.title_ar,
                    c.short_name
                ) conference_title,

                COUNT(
                    DISTINCT s.id
                ) submissions,

                SUM(
                    CASE
                    WHEN s.status='published'
                    THEN 1
                    ELSE 0
                    END
                ) published

            FROM conferences c

            LEFT JOIN submissions s
                ON s.conference_id=c.id

            GROUP BY
                c.id,
                c.short_name,
                c.title_en,
                c.title_ar

            ORDER BY
                published DESC,
                submissions DESC
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    /*
    ------------------------------------------------
    Reviewer Benchmark Ranking
    ------------------------------------------------
    */

    $reviewerRows =
        $db->query("
            SELECT

                u.id,

                CONCAT(
                    COALESCE(u.first_name,''),
                    ' ',
                    COALESCE(u.last_name,'')
                ) reviewer_name,

                COUNT(
                    ra.id
                ) reviews_completed

            FROM users u

            INNER JOIN review_assignments ra
                ON ra.reviewer_id=u.id

            WHERE
                ra.status='completed'

            GROUP BY
                u.id,
                u.first_name,
                u.last_name

            ORDER BY
                reviews_completed DESC

            LIMIT 25
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/institutional_benchmarking_excellence_intelligence_center.php';

    $content =
        ob_get_clean();

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

public function enterpriseRiskResilienceIntelligenceCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stats = [];

    /*
    ------------------------------------------------
    Overdue Reviews
    ------------------------------------------------
    */

    $stats['overdue_reviews'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM review_assignments
            WHERE status<>'completed'
              AND due_date IS NOT NULL
              AND due_date<CURDATE()
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Dormant Accounts
    ------------------------------------------------
    */

    $stats['dormant_users'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM users
            WHERE last_login_at IS NULL
               OR last_login_at <
                  DATE_SUB(
                      NOW(),
                      INTERVAL 180 DAY
                  )
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Missing DOI
    ------------------------------------------------
    */

    $stats['missing_doi'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE production_status='approved'
              AND COALESCE(doi,'')=''
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Camera Ready Queue
    ------------------------------------------------
    */

    $stats['camera_ready_queue'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE production_status='camera_ready_uploaded'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Broken Issue Links
    ------------------------------------------------
    */

    $stats['broken_issue_links'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM proceedings_issue_articles pia
            LEFT JOIN production_galleys g
                   ON g.id=pia.galley_id
            WHERE g.id IS NULL
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Orphan Permissions
    ------------------------------------------------
    */

    $stats['orphan_permissions'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM rbac_menu_items m
            LEFT JOIN rbac_role_menu_permissions p
                   ON p.menu_item_id=m.id
            WHERE p.id IS NULL
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Risk Score
    ------------------------------------------------
    */

    $riskScore =
        (
            ($stats['overdue_reviews'] * 2)
            +
            ($stats['dormant_users'])
            +
            ($stats['missing_doi'] * 3)
            +
            ($stats['camera_ready_queue'] * 2)
            +
            ($stats['broken_issue_links'] * 5)
            +
            ($stats['orphan_permissions'] * 3)
        );

    $stats['risk_score'] =
        min(
            100,
            $riskScore
        );

    /*
    ------------------------------------------------
    Resilience Score
    ------------------------------------------------
    */

    $stats['resilience_score'] =
        max(
            0,
            100 - $stats['risk_score']
        );

    /*
    ------------------------------------------------
    Risk Findings
    ------------------------------------------------
    */

    $findings = [];

    if ($stats['overdue_reviews'] > 0) {

        $findings[] = [
            'severity'=>'warning',
            'title'=>'Review Risk',
            'message'=>
                $stats['overdue_reviews']
                . ' overdue reviews detected.'
        ];
    }

    if ($stats['camera_ready_queue'] > 0) {

        $findings[] = [
            'severity'=>'info',
            'title'=>'Production Risk',
            'message'=>
                $stats['camera_ready_queue']
                . ' submissions waiting for production approval.'
        ];
    }

    if ($stats['missing_doi'] > 0) {

        $findings[] = [
            'severity'=>'warning',
            'title'=>'Publication Risk',
            'message'=>
                $stats['missing_doi']
                . ' approved publications missing DOI.'
        ];
    }

    if ($stats['broken_issue_links'] > 0) {

        $findings[] = [
            'severity'=>'danger',
            'title'=>'Issue Integrity Risk',
            'message'=>
                $stats['broken_issue_links']
                . ' broken issue article links detected.'
        ];
    }

    /*
    ------------------------------------------------
    Conference Risk Ranking
    ------------------------------------------------
    */

    $rows =
        $db->query("
            SELECT

                c.id,

                c.short_name,

                COALESCE(
                    c.title_en,
                    c.title_ar,
                    c.short_name
                ) conference_title,

                COUNT(
                    DISTINCT s.id
                ) submissions,

                SUM(
                    CASE
                    WHEN s.status='under_review'
                    THEN 1
                    ELSE 0
                    END
                ) under_review,

                SUM(
                    CASE
                    WHEN s.status='revision_required'
                    THEN 1
                    ELSE 0
                    END
                ) revisions

            FROM conferences c

            LEFT JOIN submissions s
                ON s.conference_id=c.id

            GROUP BY
                c.id,
                c.short_name,
                c.title_en,
                c.title_ar

            ORDER BY
                under_review DESC,
                revisions DESC
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/enterprise_risk_resilience_intelligence_center.php';

    $content =
        ob_get_clean();

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

public function digitalTransformationInnovationIntelligenceCenter()
{
$this->requireAccess();


$db =
    \App\Core\Database::getInstance();

$stats = [];

/*
------------------------------------------------
Core Digital Assets
------------------------------------------------
*/

$stats['users'] =
    (int)$db->query("
        SELECT COUNT(*)
        FROM users
    ")->fetchColumn();

$stats['conferences'] =
    (int)$db->query("
        SELECT COUNT(*)
        FROM conferences
    ")->fetchColumn();

$stats['submissions'] =
    (int)$db->query("
        SELECT COUNT(*)
        FROM submissions
    ")->fetchColumn();

$stats['reviews'] =
    (int)$db->query("
        SELECT COUNT(*)
        FROM review_assignments
    ")->fetchColumn();

/*
------------------------------------------------
Automation Indicators
------------------------------------------------
*/

$stats['workflow_events'] =
    (int)$db->query("
        SELECT COUNT(*)
        FROM submission_workflow_history
    ")->fetchColumn();

$stats['activity_events'] =
    (int)$db->query("
        SELECT COUNT(*)
        FROM submission_activity_log
    ")->fetchColumn();

$stats['review_events'] =
    (int)$db->query("
        SELECT COUNT(*)
        FROM review_assignment_events
    ")->fetchColumn();

$stats['audit_events'] =
    (int)$db->query("
        SELECT COUNT(*)
        FROM audit_logs
    ")->fetchColumn();

$stats['notifications'] =
    (int)$db->query("
        SELECT COUNT(*)
        FROM notifications
    ")->fetchColumn();

/*
------------------------------------------------
Digital Adoption
------------------------------------------------
*/

$activeUsers =
    (int)$db->query("
        SELECT COUNT(*)
        FROM users
        WHERE last_login_at >=
              DATE_SUB(
                  NOW(),
                  INTERVAL 90 DAY
              )
    ")->fetchColumn();

$stats['digital_adoption_score'] =
    $stats['users'] > 0
    ? (int)(
        ($activeUsers / $stats['users'])
        * 100
    )
    : 0;

/*
------------------------------------------------
Automation Score
------------------------------------------------
*/

$automationVolume =
    $stats['workflow_events']
    +
    $stats['activity_events']
    +
    $stats['review_events']
    +
    $stats['audit_events']
    +
    $stats['notifications'];

$stats['automation_score'] =
    min(
        100,
        (int)(
            $automationVolume / 100
        )
    );

/*
------------------------------------------------
Innovation Score
------------------------------------------------
*/

$stats['innovation_score'] =
    (int)round(
        (
            $stats['digital_adoption_score']
            +
            $stats['automation_score']
        ) / 2
    );

/*
------------------------------------------------
Innovation Findings
------------------------------------------------
*/

$findings = [];

if (
    $stats['digital_adoption_score']
    < 50
) {

    $findings[] = [
        'severity' => 'warning',
        'title' =>
            'Digital Adoption',
        'message' =>
            'User engagement levels are below target.'
    ];
}

if (
    $stats['automation_score']
    < 50
) {

    $findings[] = [
        'severity' => 'info',
        'title' =>
            'Automation Opportunity',
        'message' =>
            'Additional workflow automation opportunities exist.'
    ];
}

/*
------------------------------------------------
Conference Innovation Matrix
------------------------------------------------
*/

$rows =
    $db->query("
        SELECT

            c.id,

            c.short_name,

            COALESCE(
                c.title_en,
                c.title_ar,
                c.short_name
            ) conference_title,

            COUNT(
                DISTINCT s.id
            ) submissions,

            COUNT(
                DISTINCT ra.id
            ) reviews

        FROM conferences c

        LEFT JOIN submissions s
            ON s.conference_id=c.id

        LEFT JOIN review_assignments ra
            ON ra.submission_id=s.id

        GROUP BY
            c.id,
            c.short_name,
            c.title_en,
            c.title_ar

        ORDER BY
            submissions DESC,
            reviews DESC
    ")
    ->fetchAll(\PDO::FETCH_ASSOC);

ob_start();

require BASE_PATH .
'/app/views/admin/conference_home/digital_transformation_innovation_intelligence_center.php';

$content =
    ob_get_clean();

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

}

public function enterpriseSustainabilityContinuousImprovementCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stats = [];

    /*
    ------------------------------------------------
    Users
    ------------------------------------------------
    */

    $stats['users'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM users
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Active Users
    ------------------------------------------------
    */

    $stats['active_users'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM users
            WHERE last_login_at >=
                  DATE_SUB(
                      NOW(),
                      INTERVAL 90 DAY
                  )
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Reviewers
    ------------------------------------------------
    */

    $stats['reviewers'] =
        (int)$db->query("
            SELECT COUNT(
                DISTINCT reviewer_id
            )
            FROM review_assignments
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Active Reviewers
    ------------------------------------------------
    */

    $stats['active_reviewers'] =
        (int)$db->query("
            SELECT COUNT(
                DISTINCT reviewer_id
            )
            FROM review_assignments
            WHERE completed_at >=
                  DATE_SUB(
                      NOW(),
                      INTERVAL 365 DAY
                  )
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Approved Publications
    ------------------------------------------------
    */

    $stats['approved_publications'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE production_status='approved'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Published
    ------------------------------------------------
    */

    $stats['published'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='published'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Sustainability Scores
    ------------------------------------------------
    */

    $stats['user_sustainability'] =
        $stats['users'] > 0
        ? (int)(
            ($stats['active_users']
            /
            $stats['users'])
            * 100
        )
        : 0;

    $stats['reviewer_sustainability'] =
        $stats['reviewers'] > 0
        ? (int)(
            ($stats['active_reviewers']
            /
            $stats['reviewers'])
            * 100
        )
        : 0;

    $stats['publication_sustainability'] =
        $stats['approved_publications'] > 0
        ? (int)(
            ($stats['published']
            /
            $stats['approved_publications'])
            * 100
        )
        : 0;

    /*
    ------------------------------------------------
    Continuous Improvement Index
    ------------------------------------------------
    */

    $stats['improvement_index'] =
        (int)round(
            (
                $stats['user_sustainability']
                +
                $stats['reviewer_sustainability']
                +
                $stats['publication_sustainability']
            ) / 3
        );

    /*
    ------------------------------------------------
    Findings
    ------------------------------------------------
    */

    $findings = [];

    if (
        $stats['user_sustainability']
        < 60
    ) {

        $findings[] = [
            'severity'=>'warning',
            'title'=>'User Sustainability',
            'message'=>
                'User engagement sustainability is below target.'
        ];
    }

    if (
        $stats['reviewer_sustainability']
        < 60
    ) {

        $findings[] = [
            'severity'=>'warning',
            'title'=>'Reviewer Sustainability',
            'message'=>
                'Reviewer participation sustainability is below target.'
        ];
    }

    if (
        $stats['publication_sustainability']
        < 60
    ) {

        $findings[] = [
            'severity'=>'info',
            'title'=>'Publication Sustainability',
            'message'=>
                'Publication throughput can be improved.'
        ];
    }

    /*
    ------------------------------------------------
    Conference Sustainability Matrix
    ------------------------------------------------
    */

    $rows =
        $db->query("
            SELECT

                c.id,

                c.short_name,

                COALESCE(
                    c.title_en,
                    c.title_ar,
                    c.short_name
                ) conference_title,

                COUNT(
                    DISTINCT s.id
                ) submissions,

                SUM(
                    CASE
                    WHEN s.status='published'
                    THEN 1
                    ELSE 0
                    END
                ) published

            FROM conferences c

            LEFT JOIN submissions s
                ON s.conference_id=c.id

            GROUP BY
                c.id,
                c.short_name,
                c.title_en,
                c.title_ar

            ORDER BY
                published DESC,
                submissions DESC
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/enterprise_sustainability_continuous_improvement_center.php';

    $content =
        ob_get_clean();

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

public function enterpriseKnowledgeOrganizationalIntelligenceCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stats = [];

    /*
    ------------------------------------------------
    Knowledge Assets
    ------------------------------------------------
    */

    $stats['submissions'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
        ")->fetchColumn();

    $stats['reviews'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM review_assignments
            WHERE status='completed'
        ")->fetchColumn();

    $stats['workflow_history'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submission_workflow_history
        ")->fetchColumn();

    $stats['activity_history'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submission_activity_log
        ")->fetchColumn();

    $stats['audit_history'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM audit_logs
        ")->fetchColumn();

    $stats['review_events'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM review_assignment_events
        ")->fetchColumn();

    $stats['notifications'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM notifications
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Knowledge Capital
    ------------------------------------------------
    */

    $knowledgeVolume =
        $stats['reviews']
        +
        $stats['workflow_history']
        +
        $stats['activity_history']
        +
        $stats['audit_history']
        +
        $stats['review_events'];

    $stats['knowledge_score'] =
        min(
            100,
            (int)(
                $knowledgeVolume / 100
            )
        );

    /*
    ------------------------------------------------
    Organizational Memory
    ------------------------------------------------
    */

    $stats['organizational_memory_score'] =
        min(
            100,
            (int)(
                (
                    $stats['workflow_history']
                    +
                    $stats['activity_history']
                ) / 50
            )
        );

    /*
    ------------------------------------------------
    Institutional Learning Index
    ------------------------------------------------
    */

    $stats['learning_index'] =
        (int)round(
            (
                $stats['knowledge_score']
                +
                $stats['organizational_memory_score']
            ) / 2
        );

    /*
    ------------------------------------------------
    Findings
    ------------------------------------------------
    */

    $findings = [];

    if (
        $stats['knowledge_score']
        < 50
    ) {

        $findings[] = [
            'severity' => 'warning',
            'title' =>
                'Knowledge Maturity',
            'message' =>
                'Knowledge asset accumulation remains below target.'
        ];
    }

    if (
        $stats['organizational_memory_score']
        < 50
    ) {

        $findings[] = [
            'severity' => 'info',
            'title' =>
                'Organizational Memory',
            'message' =>
                'Workflow and activity retention can be improved.'
        ];
    }

    /*
    ------------------------------------------------
    Reviewer Knowledge Ranking
    ------------------------------------------------
    */

    $rows =
        $db->query("
            SELECT

                u.id,

                CONCAT(
                    COALESCE(u.first_name,''),
                    ' ',
                    COALESCE(u.last_name,'')
                ) reviewer_name,

                COUNT(
                    ra.id
                ) completed_reviews

            FROM users u

            INNER JOIN review_assignments ra
                ON ra.reviewer_id=u.id

            WHERE
                ra.status='completed'

            GROUP BY
                u.id,
                u.first_name,
                u.last_name

            ORDER BY
                completed_reviews DESC

            LIMIT 50
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/enterprise_knowledge_organizational_intelligence_center.php';

    $content =
        ob_get_clean();

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

public function enterpriseReviewerSustainabilityCenter()
{
    $this->requireAccess();

    $db = \App\Core\Database::getInstance();

    $stats = [];

    $stats['reviewers'] = (int)$db->query("
        SELECT COUNT(DISTINCT reviewer_id)
        FROM review_assignments
    ")->fetchColumn();

    $stats['completed_reviews'] = (int)$db->query("
        SELECT COUNT(*)
        FROM review_assignments
        WHERE status='completed'
    ")->fetchColumn();

    $stats['active_reviewers_365'] = (int)$db->query("
        SELECT COUNT(DISTINCT reviewer_id)
        FROM review_assignments
        WHERE completed_at >= DATE_SUB(NOW(), INTERVAL 365 DAY)
    ")->fetchColumn();

    $stats['open_reviews'] = (int)$db->query("
        SELECT COUNT(*)
        FROM review_assignments
        WHERE status<>'completed'
    ")->fetchColumn();

    $stats['overdue_reviews'] = (int)$db->query("
        SELECT COUNT(*)
        FROM review_assignments
        WHERE status<>'completed'
          AND due_date IS NOT NULL
          AND due_date<CURDATE()
    ")->fetchColumn();

    $stats['sustainability_score'] = $stats['reviewers'] > 0
        ? (int)round(($stats['active_reviewers_365'] / $stats['reviewers']) * 100)
        : 0;

    $findings = [];

    if ($stats['overdue_reviews'] > 0) {
        $findings[] = [
            'severity' => 'warning',
            'title' => 'Overdue Review Load',
            'message' => $stats['overdue_reviews'] . ' overdue reviews require follow-up.'
        ];
    }

    if ($stats['sustainability_score'] < 60) {
        $findings[] = [
            'severity' => 'info',
            'title' => 'Reviewer Sustainability',
            'message' => 'Active reviewer participation is below target.'
        ];
    }

    $rows = $db->query("
        SELECT
            u.id,
            CONCAT(COALESCE(u.first_name,''),' ',COALESCE(u.last_name,'')) AS reviewer_name,
            COUNT(ra.id) total_reviews,
            SUM(CASE WHEN ra.status='completed' THEN 1 ELSE 0 END) completed_reviews,
            SUM(CASE WHEN ra.status<>'completed' THEN 1 ELSE 0 END) open_reviews,
            SUM(
                CASE
                WHEN ra.status<>'completed'
                 AND ra.due_date IS NOT NULL
                 AND ra.due_date<CURDATE()
                THEN 1
                ELSE 0
                END
            ) overdue_reviews,
            MAX(ra.completed_at) AS last_completed_at
        FROM users u
        INNER JOIN review_assignments ra
                ON ra.reviewer_id=u.id
        GROUP BY
            u.id,
            u.first_name,
            u.last_name
        ORDER BY
            overdue_reviews DESC,
            open_reviews DESC,
            completed_reviews DESC
        LIMIT 100
    ")->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/enterprise_reviewer_sustainability_center.php';

    $content = ob_get_clean();

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

public function enterprisePublicationSustainabilityEditorialIntelligenceCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stats = [];

    /*
    ------------------------------------------------
    Publications
    ------------------------------------------------
    */

    $stats['approved'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE production_status='approved'
        ")->fetchColumn();

    $stats['published'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='published'
        ")->fetchColumn();

    $stats['assigned_to_issue'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='assigned_to_issue'
        ")->fetchColumn();

    $stats['camera_ready_uploaded'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE production_status='camera_ready_uploaded'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Approved Galleys
    ------------------------------------------------
    */

    $stats['approved_galleys'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM production_galleys
            WHERE status='approved'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Publication Sustainability
    ------------------------------------------------
    */

    $stats['publication_sustainability_score'] =
        $stats['approved'] > 0
        ? (int)(
            ($stats['published']
            /
            $stats['approved'])
            * 100
        )
        : 0;

    /*
    ------------------------------------------------
    Editorial Efficiency
    ------------------------------------------------
    */

    $stats['editorial_efficiency_score'] =
        $stats['approved_galleys'] > 0
        ? (int)(
            (
                $stats['assigned_to_issue']
                /
                $stats['approved_galleys']
            ) * 100
        )
        : 0;

    $stats['editorial_efficiency_score'] =
        min(
            100,
            $stats['editorial_efficiency_score']
        );

    /*
    ------------------------------------------------
    Editorial Intelligence Index
    ------------------------------------------------
    */

    $stats['editorial_intelligence_index'] =
        (int)round(
            (
                $stats['publication_sustainability_score']
                +
                $stats['editorial_efficiency_score']
            ) / 2
        );

    /*
    ------------------------------------------------
    Findings
    ------------------------------------------------
    */

    $findings = [];

    if (
        $stats['camera_ready_uploaded'] > 0
    ) {

        $findings[] = [
            'severity' => 'warning',
            'title' => 'Production Queue',
            'message' =>
                $stats['camera_ready_uploaded']
                . ' submissions awaiting editorial production processing.'
        ];
    }

    if (
        $stats['publication_sustainability_score'] < 60
    ) {

        $findings[] = [
            'severity' => 'info',
            'title' => 'Publication Sustainability',
            'message' =>
                'Publication conversion rate can be improved.'
        ];
    }

    /*
    ------------------------------------------------
    Issue Portfolio
    ------------------------------------------------
    */

    $rows =
        $db->query("
            SELECT

                pi.id,

                pi.volume_no,

                pi.issue_no,

                pi.publication_year,

                COUNT(
                    DISTINCT pia.submission_id
                ) article_count

            FROM proceedings_issues pi

            LEFT JOIN proceedings_issue_articles pia
                ON pia.issue_id=pi.id

            GROUP BY
                pi.id,
                pi.volume_no,
                pi.issue_no,
                pi.publication_year

            ORDER BY
                pi.id DESC
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/enterprise_publication_sustainability_editorial_intelligence_center.php';

    $content =
        ob_get_clean();

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

public function enterpriseConferencePerformanceIntelligenceCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stats = [];

    /*
    ------------------------------------------------
    Platform Totals
    ------------------------------------------------
    */

    $stats['conferences'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM conferences
        ")->fetchColumn();

    $stats['submissions'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
        ")->fetchColumn();

    $stats['reviews'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM review_assignments
        ")->fetchColumn();

    $stats['published'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='published'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Conference Performance Matrix
    ------------------------------------------------
    */

    $rows =
        $db->query("
            SELECT

                c.id,

                c.short_name,

                COALESCE(
                    c.title_en,
                    c.title_ar,
                    c.short_name
                ) conference_title,

                COUNT(
                    DISTINCT s.id
                ) submissions,

                SUM(
                    CASE
                    WHEN s.status='accepted'
                    THEN 1
                    ELSE 0
                    END
                ) accepted,

                SUM(
                    CASE
                    WHEN s.status='published'
                    THEN 1
                    ELSE 0
                    END
                ) published,

                COUNT(
                    DISTINCT ra.id
                ) reviews,

                COUNT(
                    DISTINCT g.id
                ) approved_galleys

            FROM conferences c

            LEFT JOIN submissions s
                ON s.conference_id=c.id

            LEFT JOIN review_assignments ra
                ON ra.submission_id=s.id

            LEFT JOIN production_galleys g
                ON g.submission_id=s.id
               AND g.status='approved'

            GROUP BY
                c.id,
                c.short_name,
                c.title_en,
                c.title_ar

            ORDER BY
                submissions DESC
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    /*
    ------------------------------------------------
    Derived Metrics
    ------------------------------------------------
    */

    foreach($rows as &$r)
    {
        $submissions =
            max(
                1,
                (int)$r['submissions']
            );

        $acceptanceRate =
            (
                (int)$r['accepted']
                /
                $submissions
            ) * 100;

        $publicationRate =
            (
                (int)$r['published']
                /
                $submissions
            ) * 100;

        $reviewDensity =
            (
                (int)$r['reviews']
                /
                $submissions
            ) * 100;

        $r['acceptance_rate'] =
            round(
                $acceptanceRate,
                1
            );

        $r['publication_rate'] =
            round(
                $publicationRate,
                1
            );

        $r['review_density'] =
            round(
                $reviewDensity,
                1
            );

        $r['performance_score'] =
            min(
                100,
                (int)round(
                    (
                        $acceptanceRate
                        +
                        $publicationRate
                        +
                        min(
                            100,
                            $reviewDensity
                        )
                    ) / 3
                )
            );
    }

    unset($r);

    /*
    ------------------------------------------------
    Platform Performance Index
    ------------------------------------------------
    */

    $scores = [];

    foreach($rows as $r)
    {
        $scores[] =
            (int)$r['performance_score'];
    }

    $stats['platform_performance_index'] =
        count($scores)
        ? (int)round(
            array_sum($scores)
            /
            count($scores)
        )
        : 0;

    /*
    ------------------------------------------------
    Findings
    ------------------------------------------------
    */

    $findings = [];

    if (
        $stats['platform_performance_index']
        < 60
    ) {

        $findings[] = [
            'severity'=>'warning',
            'title'=>'Conference Performance',
            'message'=>
                'Platform performance index is below target.'
        ];
    }

    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/enterprise_conference_performance_intelligence_center.php';

    $content =
        ob_get_clean();

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

public function enterpriseExecutiveCommandCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stats = [];

    /*
    ------------------------------------------------
    Core Assets
    ------------------------------------------------
    */

    $stats['users'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM users
        ")->fetchColumn();

    $stats['conferences'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM conferences
        ")->fetchColumn();

    $stats['submissions'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
        ")->fetchColumn();

    $stats['reviews'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM review_assignments
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Publication Layer
    ------------------------------------------------
    */

    $stats['approved_publications'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE production_status='approved'
        ")->fetchColumn();

    $stats['published_publications'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='published'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Reviewer Layer
    ------------------------------------------------
    */

    $stats['active_reviewers'] =
        (int)$db->query("
            SELECT COUNT(DISTINCT reviewer_id)
            FROM review_assignments
            WHERE completed_at >=
                  DATE_SUB(
                      NOW(),
                      INTERVAL 365 DAY
                  )
        ")->fetchColumn();

    $stats['overdue_reviews'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM review_assignments
            WHERE status<>'completed'
              AND due_date IS NOT NULL
              AND due_date<CURDATE()
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Governance Layer
    ------------------------------------------------
    */

    $stats['roles'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM roles
        ")->fetchColumn();

    $stats['permissions'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM rbac_role_menu_permissions
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Security Layer
    ------------------------------------------------
    */

    $stats['dormant_users'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM users
            WHERE last_login_at IS NULL
               OR last_login_at <
                  DATE_SUB(
                      NOW(),
                      INTERVAL 180 DAY
                  )
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Workflow Layer
    ------------------------------------------------
    */

    $stats['workflow_events'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submission_workflow_history
        ")->fetchColumn();

    $stats['activity_events'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submission_activity_log
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Executive Indexes
    ------------------------------------------------
    */

    $publicationIndex =
        $stats['approved_publications'] > 0
        ? (
            $stats['published_publications']
            /
            $stats['approved_publications']
        ) * 100
        : 0;

    $reviewerIndex =
        $stats['active_reviewers'] > 0
        ? min(
            100,
            $stats['active_reviewers']
        )
        : 0;

    $governanceIndex =
        min(
            100,
            (
                $stats['roles'] * 5
            )
            +
            (
                $stats['permissions'] / 20
            )
        );

    $securityIndex =
        max(
            0,
            100 - $stats['dormant_users']
        );

    $workflowIndex =
        min(
            100,
            (
                $stats['workflow_events']
                +
                $stats['activity_events']
            ) / 100
        );

    $stats['executive_health_index'] =
        (int)round(
            (
                $publicationIndex
                +
                $reviewerIndex
                +
                $governanceIndex
                +
                $securityIndex
                +
                $workflowIndex
            ) / 5
        );

    $stats['enterprise_maturity_index'] =
        $stats['executive_health_index'];

    /*
    ------------------------------------------------
    Executive Findings
    ------------------------------------------------
    */

    $findings = [];

    if ($stats['overdue_reviews'] > 0) {

        $findings[] = [
            'severity'=>'warning',
            'title'=>'Reviewer Operations',
            'message'=>
                $stats['overdue_reviews']
                .' overdue reviews require attention.'
        ];
    }

    if ($stats['dormant_users'] > 0) {

        $findings[] = [
            'severity'=>'info',
            'title'=>'User Activity',
            'message'=>
                $stats['dormant_users']
                .' dormant accounts detected.'
        ];
    }

    /*
    ------------------------------------------------
    Conference Ranking
    ------------------------------------------------
    */

    $rows =
        $db->query("
            SELECT

                c.id,

                COALESCE(
                    c.title_en,
                    c.title_ar,
                    c.short_name
                ) conference_title,

                COUNT(
                    DISTINCT s.id
                ) submissions,

                COUNT(
                    DISTINCT ra.id
                ) reviews

            FROM conferences c

            LEFT JOIN submissions s
                ON s.conference_id=c.id

            LEFT JOIN review_assignments ra
                ON ra.submission_id=s.id

            GROUP BY
                c.id,
                c.title_en,
                c.title_ar,
                c.short_name

            ORDER BY
                submissions DESC,
                reviews DESC
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/enterprise_executive_command_center.php';

    $content =
        ob_get_clean();

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

public function enterpriseBoardDirectorsIntelligenceCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stats = [];

    /*
    ------------------------------------------------
    Conferences
    ------------------------------------------------
    */

    $stats['conferences'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM conferences
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Submissions
    ------------------------------------------------
    */

    $stats['submissions'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Accepted
    ------------------------------------------------
    */

    $stats['accepted'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='accepted'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Published
    ------------------------------------------------
    */

    $stats['published'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='published'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Reviewers
    ------------------------------------------------
    */

    $stats['reviewers'] =
        (int)$db->query("
            SELECT COUNT(DISTINCT reviewer_id)
            FROM review_assignments
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Active Reviewers
    ------------------------------------------------
    */

    $stats['active_reviewers'] =
        (int)$db->query("
            SELECT COUNT(DISTINCT reviewer_id)
            FROM review_assignments
            WHERE completed_at >=
                  DATE_SUB(
                      NOW(),
                      INTERVAL 365 DAY
                  )
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Overdue Reviews
    ------------------------------------------------
    */

    $stats['overdue_reviews'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM review_assignments
            WHERE status<>'completed'
              AND due_date IS NOT NULL
              AND due_date<CURDATE()
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Board Readiness Index
    ------------------------------------------------
    */

    $acceptanceIndex =
        $stats['submissions'] > 0
        ? (
            $stats['accepted']
            /
            $stats['submissions']
        ) * 100
        : 0;

    $publicationIndex =
        $stats['accepted'] > 0
        ? (
            $stats['published']
            /
            $stats['accepted']
        ) * 100
        : 0;

    $reviewerIndex =
        $stats['reviewers'] > 0
        ? (
            $stats['active_reviewers']
            /
            $stats['reviewers']
        ) * 100
        : 0;

    $riskIndex =
        max(
            0,
            100 -
            $stats['overdue_reviews']
        );

    $stats['board_readiness_index'] =
        (int)round(
            (
                $acceptanceIndex
                +
                $publicationIndex
                +
                $reviewerIndex
                +
                $riskIndex
            ) / 4
        );

    /*
    ------------------------------------------------
    Conference Portfolio
    ------------------------------------------------
    */

    $rows =
        $db->query("
            SELECT

                c.id,

                COALESCE(
                    c.title_en,
                    c.title_ar,
                    c.short_name
                ) conference_title,

                COUNT(
                    DISTINCT s.id
                ) submissions,

                SUM(
                    CASE
                    WHEN s.status='accepted'
                    THEN 1
                    ELSE 0
                    END
                ) accepted,

                SUM(
                    CASE
                    WHEN s.status='published'
                    THEN 1
                    ELSE 0
                    END
                ) published

            FROM conferences c

            LEFT JOIN submissions s
                ON s.conference_id=c.id

            GROUP BY
                c.id,
                c.title_en,
                c.title_ar,
                c.short_name

            ORDER BY
                submissions DESC
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/enterprise_board_directors_intelligence_center.php';

    $content =
        ob_get_clean();

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

public function enterpriseStrategicPlanningInstitutionalForesightCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stats = [];

    /*
    ------------------------------------------------
    Conferences
    ------------------------------------------------
    */

    $stats['conferences'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM conferences
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Submissions
    ------------------------------------------------
    */

    $stats['submissions'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Reviews
    ------------------------------------------------
    */

    $stats['reviews'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM review_assignments
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Active Reviewers
    ------------------------------------------------
    */

    $stats['active_reviewers'] =
        (int)$db->query("
            SELECT COUNT(DISTINCT reviewer_id)
            FROM review_assignments
            WHERE completed_at >=
                  DATE_SUB(
                      NOW(),
                      INTERVAL 365 DAY
                  )
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Publications
    ------------------------------------------------
    */

    $stats['published'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='published'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Forecast Projections
    ------------------------------------------------
    */

    $stats['forecast_submissions_1y'] =
        (int)round(
            $stats['submissions'] * 1.10
        );

    $stats['forecast_submissions_3y'] =
        (int)round(
            $stats['submissions'] * 1.35
        );

    $stats['forecast_submissions_5y'] =
        (int)round(
            $stats['submissions'] * 1.75
        );

    $stats['forecast_reviewers_3y'] =
        (int)round(
            $stats['active_reviewers'] * 1.25
        );

    $stats['forecast_publications_5y'] =
        (int)round(
            $stats['published'] * 1.50
        );

    /*
    ------------------------------------------------
    Strategic Readiness
    ------------------------------------------------
    */

    $readiness =
        (
            $stats['conferences']
            +
            $stats['active_reviewers']
            +
            $stats['published']
        );

    $stats['strategic_readiness_index'] =
        min(
            100,
            (int)(
                $readiness / 10
            )
        );

    /*
    ------------------------------------------------
    Strategic Findings
    ------------------------------------------------
    */

    $findings = [];

    if (
        $stats['strategic_readiness_index']
        < 60
    ) {

        $findings[] = [
            'severity'=>'warning',
            'title'=>'Strategic Capacity',
            'message'=>
                'Institutional growth capacity requires expansion.'
        ];
    }

    if (
        $stats['active_reviewers']
        < 25
    ) {

        $findings[] = [
            'severity'=>'info',
            'title'=>'Reviewer Forecast',
            'message'=>
                'Reviewer recruitment should be prioritized.'
        ];
    }

    /*
    ------------------------------------------------
    Conference Planning Matrix
    ------------------------------------------------
    */

    $rows =
        $db->query("
            SELECT

                c.id,

                COALESCE(
                    c.title_en,
                    c.title_ar,
                    c.short_name
                ) conference_title,

                COUNT(
                    DISTINCT s.id
                ) submissions,

                COUNT(
                    DISTINCT ra.id
                ) reviews

            FROM conferences c

            LEFT JOIN submissions s
                ON s.conference_id=c.id

            LEFT JOIN review_assignments ra
                ON ra.submission_id=s.id

            GROUP BY
                c.id,
                c.title_en,
                c.title_ar,
                c.short_name

            ORDER BY
                submissions DESC
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
        '/app/views/admin/conference_home/enterprise_strategic_planning_institutional_foresight_center.php';

    $content =
        ob_get_clean();

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

public function enterpriseInstitutionalDigitalTwinCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stats = [];

    /*
    ------------------------------------------------
    Current State
    ------------------------------------------------
    */

    $stats['conferences'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM conferences
        ")->fetchColumn();

    $stats['submissions'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
        ")->fetchColumn();

    $stats['reviews'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM review_assignments
        ")->fetchColumn();

    $stats['published'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='published'
        ")->fetchColumn();

    $stats['active_reviewers'] =
        (int)$db->query("
            SELECT COUNT(DISTINCT reviewer_id)
            FROM review_assignments
            WHERE completed_at >=
                  DATE_SUB(
                      NOW(),
                      INTERVAL 365 DAY
                  )
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Digital Twin Simulation
    ------------------------------------------------
    */

    $stats['simulation_submissions'] =
        (int)round(
            $stats['submissions'] * 1.50
        );

    $stats['simulation_reviews'] =
        (int)round(
            $stats['reviews'] * 1.50
        );

    $stats['simulation_reviewers'] =
        (int)round(
            $stats['active_reviewers'] * 1.30
        );

    $stats['simulation_publications'] =
        (int)round(
            $stats['published'] * 1.40
        );

    /*
    ------------------------------------------------
    Capacity Gap Analysis
    ------------------------------------------------
    */

    $reviewCapacityGap =
        $stats['simulation_reviews']
        -
        (
            $stats['simulation_reviewers']
            * 3
        );

    $stats['capacity_gap'] =
        max(
            0,
            $reviewCapacityGap
        );

    /*
    ------------------------------------------------
    Digital Twin Index
    ------------------------------------------------
    */

    $stats['digital_twin_index'] =
        min(
            100,
            (int)(
                (
                    $stats['simulation_submissions']
                    +
                    $stats['simulation_reviews']
                    +
                    $stats['simulation_publications']
                ) / 100
            )
        );

    /*
    ------------------------------------------------
    Findings
    ------------------------------------------------
    */

    $findings = [];

    if (
        $stats['capacity_gap'] > 0
    ) {

        $findings[] = [
            'severity'=>'warning',
            'title'=>'Reviewer Capacity Gap',
            'message'=>
                'Projected reviewer shortage detected.'
        ];
    }

    if (
        $stats['digital_twin_index'] < 60
    ) {

        $findings[] = [
            'severity'=>'info',
            'title'=>'Growth Opportunity',
            'message'=>
                'Institutional growth capacity can be expanded.'
        ];
    }

    /*
    ------------------------------------------------
    Conference Simulation Matrix
    ------------------------------------------------
    */

    $rows =
        $db->query("
            SELECT

                c.id,

                COALESCE(
                    c.title_en,
                    c.title_ar,
                    c.short_name
                ) conference_title,

                COUNT(
                    DISTINCT s.id
                ) submissions

            FROM conferences c

            LEFT JOIN submissions s
                ON s.conference_id=c.id

            GROUP BY
                c.id,
                c.title_en,
                c.title_ar,
                c.short_name

            ORDER BY
                submissions DESC
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    foreach($rows as &$r)
    {
        $r['projected_submissions'] =
            (int)round(
                $r['submissions'] * 1.50
            );
    }

    unset($r);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/enterprise_institutional_digital_twin_center.php';

    $content =
        ob_get_clean();

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

public function enterpriseAutonomousOperationsControlCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stats = [];

    /*
    ------------------------------------------------
    Operational Assets
    ------------------------------------------------
    */

    $stats['submissions'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
        ")->fetchColumn();

    $stats['open_reviews'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM review_assignments
            WHERE status<>'completed'
        ")->fetchColumn();

    $stats['overdue_reviews'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM review_assignments
            WHERE status<>'completed'
              AND due_date IS NOT NULL
              AND due_date<CURDATE()
        ")->fetchColumn();

    $stats['camera_ready_queue'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE production_status='camera_ready_uploaded'
        ")->fetchColumn();

    $stats['approved_publications'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE production_status='approved'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Workflow Signals
    ------------------------------------------------
    */

    $stats['workflow_events'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submission_workflow_history
        ")->fetchColumn();

    $stats['activity_events'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submission_activity_log
        ")->fetchColumn();

    $stats['audit_events'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM audit_logs
        ")->fetchColumn();

    $stats['notifications'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM notifications
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Operational Findings
    ------------------------------------------------
    */

    $findings = [];

    if ($stats['overdue_reviews'] > 0) {

        $findings[] = [
            'severity' => 'danger',
            'title' => 'Overdue Reviews',
            'message' =>
                $stats['overdue_reviews']
                .' overdue reviews detected.'
        ];
    }

    if ($stats['camera_ready_queue'] > 0) {

        $findings[] = [
            'severity' => 'warning',
            'title' => 'Production Queue',
            'message' =>
                $stats['camera_ready_queue']
                .' submissions waiting for production processing.'
        ];
    }

    /*
    ------------------------------------------------
    Recommendations
    ------------------------------------------------
    */

    $recommendations = [];

    if ($stats['overdue_reviews'] > 0) {

        $recommendations[] =
            'Trigger reviewer reminder campaign.';
    }

    if ($stats['camera_ready_queue'] > 0) {

        $recommendations[] =
            'Process camera-ready submissions into production.';
    }

    if ($stats['audit_events'] < 100) {

        $recommendations[] =
            'Increase operational auditing coverage.';
    }

    /*
    ------------------------------------------------
    Automation Readiness
    ------------------------------------------------
    */

    $stats['automation_readiness'] =
        min(
            100,
            (int)(
                (
                    $stats['workflow_events']
                    +
                    $stats['activity_events']
                    +
                    $stats['audit_events']
                    +
                    $stats['notifications']
                ) / 100
            )
        );

    /*
    ------------------------------------------------
    Operational Risk Matrix
    ------------------------------------------------
    */

    $rows =
        $db->query("
            SELECT

                s.id,

                s.submission_no,

                COALESCE(
                    s.title,
                    s.title_en,
                    s.title_ar
                ) submission_title,

                s.status,

                s.production_status

            FROM submissions s

            WHERE
                s.status IN
                (
                    'accepted',
                    'under_review',
                    'revision_required',
                    'production',
                    'assigned_to_issue'
                )

            ORDER BY s.id DESC

            LIMIT 100
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/enterprise_autonomous_operations_control_center.php';

    $content =
        ob_get_clean();

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

public function enterpriseAiGovernanceDecisionIntelligenceCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stats = [];

    /*
    ------------------------------------------------
    Governance Signals
    ------------------------------------------------
    */

    $stats['roles'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM roles
        ")->fetchColumn();

    $stats['permissions'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM rbac_role_menu_permissions
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Reviewer Signals
    ------------------------------------------------
    */

    $stats['overdue_reviews'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM review_assignments
            WHERE status<>'completed'
              AND due_date IS NOT NULL
              AND due_date<CURDATE()
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Publication Signals
    ------------------------------------------------
    */

    $stats['camera_ready_queue'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE production_status='camera_ready_uploaded'
        ")->fetchColumn();

    $stats['approved_publications'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE production_status='approved'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Operational Signals
    ------------------------------------------------
    */

    $stats['workflow_events'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submission_workflow_history
        ")->fetchColumn();

    $stats['audit_events'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM audit_logs
        ")->fetchColumn();

    /*
    ------------------------------------------------
    AI Decision Score
    ------------------------------------------------
    */

    $stats['decision_intelligence_score'] =
        max(
            0,
            min(
                100,
                (
                    100
                    -
                    ($stats['overdue_reviews'] * 2)
                    -
                    ($stats['camera_ready_queue'])
                )
            )
        );

    /*
    ------------------------------------------------
    Executive Recommendations
    ------------------------------------------------
    */

    $recommendations = [];

    if ($stats['overdue_reviews'] > 0)
    {
        $recommendations[] = [
            'priority'=>'Critical',
            'domain'=>'Reviewer Operations',
            'action'=>'Escalate overdue reviews and notify track chairs.'
        ];
    }

    if ($stats['camera_ready_queue'] > 0)
    {
        $recommendations[] = [
            'priority'=>'High',
            'domain'=>'Publication Operations',
            'action'=>'Process pending camera-ready submissions.'
        ];
    }

    if ($stats['audit_events'] < 100)
    {
        $recommendations[] = [
            'priority'=>'Medium',
            'domain'=>'Governance',
            'action'=>'Increase audit coverage and monitoring.'
        ];
    }

    if ($stats['workflow_events'] < 100)
    {
        $recommendations[] = [
            'priority'=>'Medium',
            'domain'=>'Workflow',
            'action'=>'Expand workflow automation adoption.'
        ];
    }

    /*
    ------------------------------------------------
    Executive Risk Matrix
    ------------------------------------------------
    */

    $rows =
        $db->query("
            SELECT

                c.id,

                COALESCE(
                    c.title_en,
                    c.title_ar,
                    c.short_name
                ) conference_title,

                COUNT(
                    DISTINCT s.id
                ) submissions,

                COUNT(
                    DISTINCT ra.id
                ) reviews,

                SUM(
                    CASE
                    WHEN ra.status<>'completed'
                     AND ra.due_date IS NOT NULL
                     AND ra.due_date<CURDATE()
                    THEN 1
                    ELSE 0
                    END
                ) overdue_reviews

            FROM conferences c

            LEFT JOIN submissions s
                ON s.conference_id=c.id

            LEFT JOIN review_assignments ra
                ON ra.submission_id=s.id

            GROUP BY
                c.id,
                c.title_en,
                c.title_ar,
                c.short_name

            ORDER BY
                overdue_reviews DESC,
                submissions DESC
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/enterprise_ai_governance_decision_intelligence_center.php';

    $content =
        ob_get_clean();

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

public function enterpriseGlobalUniversityRankingResearchImpactIntelligenceCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stats = [];

    /*
    ------------------------------------------------
    Research Assets
    ------------------------------------------------
    */

    $stats['conferences'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM conferences
        ")->fetchColumn();

    $stats['submissions'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
        ")->fetchColumn();

    $stats['accepted_articles'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status IN
            (
                'accepted',
                'production',
                'assigned_to_issue',
                'published'
            )
        ")->fetchColumn();

    $stats['published_articles'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='published'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    DOI Assets
    ------------------------------------------------
    */

    $stats['articles_with_doi'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE COALESCE(doi,'')<>''
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Issue Assets
    ------------------------------------------------
    */

    $stats['issues'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM proceedings_issues
        ")->fetchColumn();

    $stats['issue_articles'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM proceedings_issue_articles
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Approved Galleys
    ------------------------------------------------
    */

    $stats['approved_galleys'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM production_galleys
            WHERE status='approved'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Ranking Readiness
    ------------------------------------------------
    */

    $doiIndex =
        $stats['published_articles'] > 0
        ? (
            $stats['articles_with_doi']
            /
            $stats['published_articles']
        ) * 100
        : 0;

    $publicationIndex =
        $stats['accepted_articles'] > 0
        ? (
            $stats['published_articles']
            /
            $stats['accepted_articles']
        ) * 100
        : 0;

    $issueIndex =
        $stats['published_articles'] > 0
        ? (
            $stats['issue_articles']
            /
            $stats['published_articles']
        ) * 100
        : 0;

    $stats['research_impact_index'] =
        (int)round(
            (
                $doiIndex
                +
                $publicationIndex
                +
                min(100,$issueIndex)
            ) / 3
        );

    $stats['ranking_readiness_index'] =
        $stats['research_impact_index'];

    /*
    ------------------------------------------------
    Findings
    ------------------------------------------------
    */

    $findings = [];

    if (
        $stats['articles_with_doi']
        <
        $stats['published_articles']
    ) {

        $findings[] = [
            'severity'=>'warning',
            'title'=>'DOI Coverage',
            'message'=>'Some published articles do not have DOI identifiers.'
        ];
    }

    if (
        $stats['ranking_readiness_index']
        < 60
    ) {

        $findings[] = [
            'severity'=>'info',
            'title'=>'Research Visibility',
            'message'=>'Institutional research visibility can be improved.'
        ];
    }

    /*
    ------------------------------------------------
    Conference Research Portfolio
    ------------------------------------------------
    */

    $rows =
        $db->query("
            SELECT

                c.id,

                COALESCE(
                    c.title_en,
                    c.title_ar,
                    c.short_name
                ) conference_title,

                COUNT(
                    DISTINCT s.id
                ) submissions,

                SUM(
                    CASE
                    WHEN COALESCE(s.doi,'')<>''
                    THEN 1
                    ELSE 0
                    END
                ) doi_articles,

                SUM(
                    CASE
                    WHEN s.status='published'
                    THEN 1
                    ELSE 0
                    END
                ) published_articles

            FROM conferences c

            LEFT JOIN submissions s
                ON s.conference_id=c.id

            GROUP BY
                c.id,
                c.title_en,
                c.title_ar,
                c.short_name

            ORDER BY
                published_articles DESC,
                submissions DESC
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/enterprise_global_university_ranking_research_impact_intelligence_center.php';

    $content =
        ob_get_clean();

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

public function enterpriseResearchExcellenceAccreditationIntelligenceCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stats = [];

    /*
    ------------------------------------------------
    Research Assets
    ------------------------------------------------
    */

    $stats['submissions'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
        ")->fetchColumn();

    $stats['accepted_articles'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status IN
            (
                'accepted',
                'production',
                'assigned_to_issue',
                'published'
            )
        ")->fetchColumn();

    $stats['published_articles'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='published'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    DOI Coverage
    ------------------------------------------------
    */

    $stats['doi_articles'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE COALESCE(doi,'')<>''
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Approved Galleys
    ------------------------------------------------
    */

    $stats['approved_galleys'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM production_galleys
            WHERE status='approved'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Review Quality Signals
    ------------------------------------------------
    */

    $stats['completed_reviews'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM review_assignments
            WHERE status='completed'
        ")->fetchColumn();

    $stats['active_reviewers'] =
        (int)$db->query("
            SELECT COUNT(DISTINCT reviewer_id)
            FROM review_assignments
            WHERE completed_at >=
                  DATE_SUB(
                      NOW(),
                      INTERVAL 365 DAY
                  )
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Excellence Metrics
    ------------------------------------------------
    */

    $publicationQuality =
        $stats['accepted_articles'] > 0
        ? (
            $stats['published_articles']
            /
            $stats['accepted_articles']
        ) * 100
        : 0;

    $doiCoverage =
        $stats['published_articles'] > 0
        ? (
            $stats['doi_articles']
            /
            $stats['published_articles']
        ) * 100
        : 0;

    $reviewCoverage =
        $stats['active_reviewers'] > 0
        ? min(
            100,
            (
                $stats['completed_reviews']
                /
                $stats['active_reviewers']
            )
        )
        : 0;

    $stats['research_excellence_index'] =
        (int)round(
            (
                $publicationQuality
                +
                min(100,$doiCoverage)
                +
                min(100,$reviewCoverage)
            ) / 3
        );

    $stats['accreditation_readiness_index'] =
        $stats['research_excellence_index'];

    /*
    ------------------------------------------------
    Findings
    ------------------------------------------------
    */

    $findings = [];

    if (
        $doiCoverage < 80
    ) {

        $findings[] = [
            'severity'=>'warning',
            'title'=>'DOI Coverage',
            'message'=>'DOI coverage is below accreditation target.'
        ];
    }

    if (
        $stats['research_excellence_index'] < 60
    ) {

        $findings[] = [
            'severity'=>'info',
            'title'=>'Research Excellence',
            'message'=>'Research excellence indicators can be improved.'
        ];
    }

    /*
    ------------------------------------------------
    Conference Excellence Matrix
    ------------------------------------------------
    */

    $rows =
        $db->query("
            SELECT

                c.id,

                COALESCE(
                    c.title_en,
                    c.title_ar,
                    c.short_name
                ) conference_title,

                COUNT(
                    DISTINCT s.id
                ) submissions,

                SUM(
                    CASE
                    WHEN s.status='published'
                    THEN 1
                    ELSE 0
                    END
                ) published_articles,

                SUM(
                    CASE
                    WHEN COALESCE(s.doi,'')<>''
                    THEN 1
                    ELSE 0
                    END
                ) doi_articles

            FROM conferences c

            LEFT JOIN submissions s
                ON s.conference_id=c.id

            GROUP BY
                c.id,
                c.title_en,
                c.title_ar,
                c.short_name

            ORDER BY
                published_articles DESC,
                submissions DESC
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/enterprise_research_excellence_accreditation_intelligence_center.php';

    $content =
        ob_get_clean();

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

public function enterpriseAcademicReputationGlobalVisibilityIntelligenceCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stats = [];

    /*
    ------------------------------------------------
    Research Visibility Assets
    ------------------------------------------------
    */

    $stats['conferences'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM conferences
        ")->fetchColumn();

    $stats['submissions'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
        ")->fetchColumn();

    $stats['published_articles'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='published'
        ")->fetchColumn();

    $stats['approved_articles'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE production_status='approved'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    DOI Coverage
    ------------------------------------------------
    */

    $stats['doi_articles'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE COALESCE(doi,'')<>''
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Proceedings Visibility
    ------------------------------------------------
    */

    $stats['issues'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM proceedings_issues
        ")->fetchColumn();

    $stats['issue_articles'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM proceedings_issue_articles
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Public Publication Assets
    ------------------------------------------------
    */

    $stats['public_galleys'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM production_galleys
            WHERE status='approved'
              AND is_public=1
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Visibility Indicators
    ------------------------------------------------
    */

    $doiVisibility =
        $stats['published_articles'] > 0
        ? (
            $stats['doi_articles']
            /
            $stats['published_articles']
        ) * 100
        : 0;

    $publicationVisibility =
        $stats['published_articles'] > 0
        ? (
            $stats['public_galleys']
            /
            $stats['published_articles']
        ) * 100
        : 0;

    $issueVisibility =
        $stats['published_articles'] > 0
        ? (
            $stats['issue_articles']
            /
            $stats['published_articles']
        ) * 100
        : 0;

    $stats['global_visibility_index'] =
        (int)round(
            (
                min(100,$doiVisibility)
                +
                min(100,$publicationVisibility)
                +
                min(100,$issueVisibility)
            ) / 3
        );

    $stats['academic_reputation_index'] =
        $stats['global_visibility_index'];

    /*
    ------------------------------------------------
    Findings
    ------------------------------------------------
    */

    $findings = [];

    if (
        $doiVisibility < 80
    ) {

        $findings[] = [
            'severity'=>'warning',
            'title'=>'DOI Visibility',
            'message'=>'Published content requires stronger DOI coverage.'
        ];
    }

    if (
        $publicationVisibility < 80
    ) {

        $findings[] = [
            'severity'=>'warning',
            'title'=>'Publication Exposure',
            'message'=>'Public publication availability can be improved.'
        ];
    }

    if (
        $stats['academic_reputation_index'] < 60
    ) {

        $findings[] = [
            'severity'=>'info',
            'title'=>'Academic Visibility',
            'message'=>'Institutional visibility indicators are below target.'
        ];
    }

    /*
    ------------------------------------------------
    Conference Visibility Portfolio
    ------------------------------------------------
    */

    $rows =
        $db->query("
            SELECT

                c.id,

                COALESCE(
                    c.title_en,
                    c.title_ar,
                    c.short_name
                ) conference_title,

                COUNT(
                    DISTINCT s.id
                ) submissions,

                SUM(
                    CASE
                    WHEN s.status='published'
                    THEN 1
                    ELSE 0
                    END
                ) published_articles,

                SUM(
                    CASE
                    WHEN COALESCE(s.doi,'')<>''
                    THEN 1
                    ELSE 0
                    END
                ) doi_articles

            FROM conferences c

            LEFT JOIN submissions s
                ON s.conference_id=c.id

            GROUP BY
                c.id,
                c.title_en,
                c.title_ar,
                c.short_name

            ORDER BY
                published_articles DESC,
                submissions DESC
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/enterprise_academic_reputation_global_visibility_intelligence_center.php';

    $content =
        ob_get_clean();

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

public function enterpriseResearchEcosystemCollaborationIntelligenceCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stats = [];

    /*
    ------------------------------------------------
    Ecosystem Assets
    ------------------------------------------------
    */

    $stats['conferences'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM conferences
        ")->fetchColumn();

    $stats['users'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM users
        ")->fetchColumn();

    $stats['submissions'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Reviewer Ecosystem
    ------------------------------------------------
    */

    $stats['reviewers'] =
        (int)$db->query("
            SELECT COUNT(DISTINCT user_id)
            FROM conference_reviewers
        ")->fetchColumn();

    $stats['active_reviewers'] =
        (int)$db->query("
            SELECT COUNT(DISTINCT reviewer_id)
            FROM review_assignments
            WHERE completed_at >=
                  DATE_SUB(
                      NOW(),
                      INTERVAL 365 DAY
                  )
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Track Chair Ecosystem
    ------------------------------------------------
    */

    $stats['track_chairs'] =
        (int)$db->query("
            SELECT COUNT(DISTINCT user_id)
            FROM track_chair_assignments
            WHERE is_active=1
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Collaboration Indicators
    ------------------------------------------------
    */

    $reviewerParticipation =
        $stats['reviewers'] > 0
        ? (
            $stats['active_reviewers']
            /
            $stats['reviewers']
        ) * 100
        : 0;

    $conferenceParticipation =
        $stats['conferences'] > 0
        ? (
            $stats['submissions']
            /
            $stats['conferences']
        )
        : 0;

    $stats['ecosystem_health_index'] =
        (int)round(
            (
                min(100,$reviewerParticipation)
                +
                min(100,$conferenceParticipation)
            ) / 2
        );

    $stats['collaboration_readiness_index'] =
        (int)round(
            (
                min(100,$reviewerParticipation)
                +
                min(100,($stats['track_chairs'] * 10))
            ) / 2
        );

    /*
    ------------------------------------------------
    Findings
    ------------------------------------------------
    */

    $findings = [];

    if (
        $reviewerParticipation < 50
    ) {

        $findings[] = [
            'severity'=>'warning',
            'title'=>'Reviewer Participation',
            'message'=>'Reviewer participation levels are below target.'
        ];
    }

    if (
        $stats['track_chairs'] < 5
    ) {

        $findings[] = [
            'severity'=>'info',
            'title'=>'Leadership Capacity',
            'message'=>'Track-chair ecosystem can be expanded.'
        ];
    }

    /*
    ------------------------------------------------
    Conference Ecosystem Matrix
    ------------------------------------------------
    */

    $rows =
        $db->query("
            SELECT

                c.id,

                COALESCE(
                    c.title_en,
                    c.title_ar,
                    c.short_name
                ) conference_title,

                COUNT(
                    DISTINCT s.id
                ) submissions,

                COUNT(
                    DISTINCT cr.user_id
                ) reviewers

            FROM conferences c

            LEFT JOIN submissions s
                ON s.conference_id=c.id

            LEFT JOIN conference_reviewers cr
                ON cr.conference_id=c.id

            GROUP BY
                c.id,
                c.title_en,
                c.title_ar,
                c.short_name

            ORDER BY
                submissions DESC,
                reviewers DESC
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/enterprise_research_ecosystem_collaboration_intelligence_center.php';

    $content =
        ob_get_clean();

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

public function enterpriseInstitutionalSustainabilityGrowthIntelligenceCenter()
{
    $this->requireAccess();

    $db =
        \App\Core\Database::getInstance();

    $stats = [];

    /*
    ------------------------------------------------
    Institutional Assets
    ------------------------------------------------
    */

    $stats['conferences'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM conferences
        ")->fetchColumn();

    $stats['submissions'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
        ")->fetchColumn();

    $stats['published_articles'] =
        (int)$db->query("
            SELECT COUNT(*)
            FROM submissions
            WHERE status='published'
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Reviewer Sustainability
    ------------------------------------------------
    */

    $stats['reviewers'] =
        (int)$db->query("
            SELECT COUNT(DISTINCT reviewer_id)
            FROM review_assignments
        ")->fetchColumn();

    $stats['active_reviewers'] =
        (int)$db->query("
            SELECT COUNT(DISTINCT reviewer_id)
            FROM review_assignments
            WHERE completed_at >=
                  DATE_SUB(
                      NOW(),
                      INTERVAL 365 DAY
                  )
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Leadership Sustainability
    ------------------------------------------------
    */

    $stats['track_chairs'] =
        (int)$db->query("
            SELECT COUNT(DISTINCT user_id)
            FROM track_chair_assignments
            WHERE is_active=1
        ")->fetchColumn();

    /*
    ------------------------------------------------
    Growth Indicators
    ------------------------------------------------
    */

    $reviewerSustainability =
        $stats['reviewers'] > 0
        ? (
            $stats['active_reviewers']
            /
            $stats['reviewers']
        ) * 100
        : 0;

    $publicationGrowth =
        $stats['submissions'] > 0
        ? (
            $stats['published_articles']
            /
            $stats['submissions']
        ) * 100
        : 0;

    $leadershipStrength =
        min(
            100,
            (
                $stats['track_chairs']
                * 10
            )
        );

    /*
    ------------------------------------------------
    Sustainability Index
    ------------------------------------------------
    */

    $stats['institutional_sustainability_index'] =
        (int)round(
            (
                min(100,$reviewerSustainability)
                +
                min(100,$publicationGrowth)
                +
                min(100,$leadershipStrength)
            ) / 3
        );

    /*
    ------------------------------------------------
    Growth Readiness
    ------------------------------------------------
    */

    $stats['growth_readiness_index'] =
        min(
            100,
            (int)(
                (
                    $stats['conferences']
                    * 5
                )
                +
                (
                    $stats['track_chairs']
                    * 3
                )
                +
                (
                    $stats['active_reviewers']
                    / 2
                )
            )
        );

    /*
    ------------------------------------------------
    Findings
    ------------------------------------------------
    */

    $findings = [];

    if (
        $reviewerSustainability < 60
    ) {

        $findings[] = [
            'severity'=>'warning',
            'title'=>'Reviewer Sustainability',
            'message'=>'Reviewer retention requires attention.'
        ];
    }

    if (
        $stats['track_chairs'] < 5
    ) {

        $findings[] = [
            'severity'=>'info',
            'title'=>'Leadership Capacity',
            'message'=>'Additional track-chair leadership is recommended.'
        ];
    }

    if (
        $stats['growth_readiness_index'] < 60
    ) {

        $findings[] = [
            'severity'=>'info',
            'title'=>'Growth Readiness',
            'message'=>'Institutional growth capacity can be expanded.'
        ];
    }

    /*
    ------------------------------------------------
    Sustainability Portfolio
    ------------------------------------------------
    */

    $rows =
        $db->query("
            SELECT

                c.id,

                COALESCE(
                    c.title_en,
                    c.title_ar,
                    c.short_name
                ) conference_title,

                COUNT(
                    DISTINCT s.id
                ) submissions,

                SUM(
                    CASE
                    WHEN s.status='published'
                    THEN 1
                    ELSE 0
                    END
                ) published_articles

            FROM conferences c

            LEFT JOIN submissions s
                ON s.conference_id=c.id

            GROUP BY
                c.id,
                c.title_en,
                c.title_ar,
                c.short_name

            ORDER BY
                submissions DESC
        ")
        ->fetchAll(\PDO::FETCH_ASSOC);

    ob_start();

    require BASE_PATH .
    '/app/views/admin/conference_home/enterprise_institutional_sustainability_growth_intelligence_center.php';

    $content =
        ob_get_clean();

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






}
