<?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()
    //) {

      //  return $this->sections();
    //}
        $this->requireAccess();
	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;
}
    $stmt = $db->prepare("

        UPDATE conference_home_sections

        SET

            section_title_en = ?,
            section_title_ar = ?,

            title_en = ?,
            title_ar = ?,

            subtitle_en = ?,
            subtitle_ar = ?,

            icon_class = ?,
            theme_name = ?,
background_type = ?,
background_value = ?,
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['icon_class'] ?? ''),

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

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

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 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);

    $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,

            icon_class,

            theme_name,

            sort_order,

            enabled

        )

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

    ");

    $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['icon_class'] ?? 'fa-cube'),

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

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

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

    ]);

    $_SESSION['success'] =
        'Homepage section created 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");
}

/* =========================================================
 * 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 versions()
{
    $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'
]

);

}

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

echo
json_encode(

\App\Services\HomepageMarketplaceService::catalog(

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

)

);

exit;
}

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 branches()
{
$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;

}






}
