<?php
namespace App\Controllers;

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

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

use App\Core\Database;

class PublicConferenceBusinessController
{
    private function db()
    {
        return Database::getInstance();
    }

    private function conference(): array
    {
        $id = (int)($_GET['conference_id'] ?? $_GET['id'] ?? 0);

        if ($id <= 0 && !empty($_SESSION['conference_id'])) {
            $id = (int)$_SESSION['conference_id'];
        }

        if ($id <= 0) {
            http_response_code(404);
            exit("Conference required.");
        }

        $stmt = $this->db()->prepare("SELECT * FROM conferences WHERE id=? LIMIT 1");
        $stmt->execute([$id]);
        $conference = $stmt->fetch(\PDO::FETCH_ASSOC);

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

        return $conference;
    }

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

    public function index()
    {

        /*
|--------------------------------------------------------------------------
| PUBLIC CONFERENCE PAGE
|--------------------------------------------------------------------------
|
| NEVER redirect guests/public visitors.
| Only apply dashboard redirects to authenticated users.
|
*/

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

    if (
        function_exists('ec_scope_role')
        &&
        ec_scope_role() !== 'superadmin'
    ) {

        /*
        KEEP NORMAL INTERNAL RBAC FLOW
        */

        if (function_exists('ec_scope_auto_select_conference')) {
            // ec_scope_auto_select_conference(true);
        }

    }

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

/*
|--------------------------------------------------------------------------
| SUPERADMIN BUSINESS OVERRIDE
|--------------------------------------------------------------------------
*/

$isSuperAdmin =
    (
        ec_is_superadmin()
    );

/*
|--------------------------------------------------------------------------
| FORCE CONFERENCE CONTEXT
|--------------------------------------------------------------------------
*/

$_SESSION['conference_id']
    = $cid;

$_SESSION['current_conference_id']
    = $cid;

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

$_SESSION['conference_short_name']
    = $conference['short_name']
    ?? '';

        $committees = $this->rows("
    SELECT
        id,
        committee_type,
        full_name_ar,
        full_name_en,
        affiliation_ar,
        affiliation_en,
        role_title_ar,
        role_title_en,
        image_path,
        sort_order
    FROM conference_committee_people
    WHERE conference_id=?
      AND org_id=?
      AND is_visible=1
    ORDER BY committee_type, sort_order, id
", [$cid, $orgId]);

        $sessions = $this->rows("
            SELECT 
                s.*,
                d.day_date,
                COALESCE(d.title_ar,d.title_en) AS day_title,
                COALESCE(v.name_ar,v.name_en,s.room_name) AS venue_name,
                COALESCE(t.title_ar,t.title_en) AS theme_title,
                COALESCE(s.chair_name_ar,s.chair_name_en,CONCAT(COALESCE(u.first_name,''),' ',COALESCE(u.last_name,''))) AS chair_name,
                COALESCE(pc.papers_count,0) AS papers_count
            FROM conference_sessions s
            LEFT JOIN conference_days d ON d.id = COALESCE(s.day_id, s.conference_day_id)
            LEFT JOIN conference_venues v ON v.id = COALESCE(s.venue_id, s.room_id)
            LEFT JOIN conference_themes t ON t.id = COALESCE(s.theme_id, s.track_id)
            LEFT JOIN users u ON u.id = s.chair_user_id
            LEFT JOIN (
                SELECT session_id, COUNT(*) AS papers_count
                FROM conference_session_papers
                GROUP BY session_id
            ) pc ON pc.session_id=s.id
            WHERE s.conference_id=?
              AND s.org_id=?
              AND (s.is_published=1 OR s.is_active=1)
            ORDER BY COALESCE(d.day_date,s.session_date), s.start_time, s.sort_order, s.id
        ", [$cid, $orgId]);

        $sessionPapers = $this->rows("
            SELECT 
                sp.*,
                sub.submission_no,
                COALESCE(sub.title,sub.title_en,sub.title_ar) AS paper_title,
                COALESCE(sp.presenter_name,sub.author_name) AS presenter
            FROM conference_session_papers sp
            JOIN submissions sub ON sub.id = sp.submission_id
            WHERE sp.conference_id=?
              AND sp.org_id=?
            ORDER BY sp.session_id, sp.presentation_order, sp.id
        ", [$cid, $orgId]);

        $papersBySession = [];
        foreach ($sessionPapers as $p) {
            $papersBySession[(int)$p['session_id']][] = $p;
        }

        $issues = $this->rows("
            SELECT i.*, COALESCE(ac.articles_count,0) AS articles_count
            FROM proceedings_issues i
            LEFT JOIN (
                SELECT issue_id, COUNT(*) AS articles_count
                FROM proceedings_issue_articles
                GROUP BY issue_id
            ) ac ON ac.issue_id=i.id
            WHERE i.conference_id=?
              AND i.org_id=?
              AND i.status IN ('published','open','draft')
            ORDER BY i.publication_date DESC, i.id DESC
        ", [$cid, $orgId]);

        $issueArticles = $this->rows("
            SELECT 
                a.*,
                sub.submission_no,
                COALESCE(sub.title,sub.title_en,sub.title_ar) AS article_title,
                sub.author_name,
                g.file_path AS galley_file,
                g.original_filename AS galley_name
            FROM proceedings_issue_articles a
            JOIN submissions sub ON sub.id=a.submission_id
            LEFT JOIN production_galleys g ON g.id=a.galley_id
            WHERE a.conference_id=?
              AND a.org_id=?
            ORDER BY a.issue_id, a.article_order, a.id
        ", [$cid, $orgId]);

        $articlesByIssue = [];
        foreach ($issueArticles as $a) {
            $articlesByIssue[(int)$a['issue_id']][] = $a;
        }

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

/*
=========================================================
PACK 660 — LIVE PUBLIC SYNCHRONIZATION
=========================================================
*/

/*
---------------------------------------------------------
COMMITTEES
---------------------------------------------------------
*/

$committees = [];

try {

    $stmtCommittees = $db->prepare("
        SELECT
            id,
            committee_type,

            full_name_ar,
            full_name_en,

            role_title_ar AS title_ar,
            role_title_en AS title_en,

            affiliation_ar,
            affiliation_en,

            image_path,
            sort_order

        FROM conference_committee_people
        WHERE conference_id = ?
          AND is_visible = 1
        ORDER BY
            committee_type,
            sort_order,
            id
    ");

    $stmtCommittees->execute([
        (int)$conference['id']
    ]);

    $committees =
        $stmtCommittees->fetchAll(\PDO::FETCH_ASSOC);

} catch (\Throwable $e) {

    error_log(
        'PUBLIC COMMITTEE PEOPLE ERROR: '
        . $e->getMessage()
    );
}

/*
---------------------------------------------------------
SESSIONS
---------------------------------------------------------
*/

$sessions = [];

try {

    $stmtSessions = $db->prepare("
        SELECT *
        FROM conference_sessions
        WHERE conference_id = ?
        AND is_active = 1
        AND is_published = 1
        ORDER BY
            session_date ASC,
            start_time ASC,
            sort_order ASC
    ");

    $stmtSessions->execute([
        (int)$conference['id']
    ]);

    $sessions =
        $stmtSessions->fetchAll(\PDO::FETCH_ASSOC);

} catch (\Throwable $e) {

    error_log(
        'PUBLIC SESSION ERROR: '
        . $e->getMessage()
    );
}

/*
---------------------------------------------------------
IMPORTANT DATES
---------------------------------------------------------
*/

$timelineItems = [];

$timelineMap = [

    'submission_start' =>
        'Submission Opening',

    'submission_end' =>
        'Submission Deadline',

    'review_start' =>
        'Review Start',

    'review_end' =>
        'Review Deadline',

    'decision_date' =>
        'Acceptance Notification',

    'camera_ready_deadline' =>
        'Camera Ready Deadline',

    'start_date' =>
        'Conference Start',

    'end_date' =>
        'Conference End',
];

foreach ($timelineMap as $field => $label) {

    if (!empty($conference[$field])) {

        $timelineItems[] = [

            'label' => $label,

            'date' =>
                $conference[$field]
        ];
    }
}

/*
---------------------------------------------------------
PROCEEDINGS
---------------------------------------------------------
*/


/*
---------------------------------------------------------
LIVE ANALYTICS ENGINE
---------------------------------------------------------
*/

$liveAnalytics = [

    'submissions' => 0,
    'accepted' => 0,
    'tracks' => 0,
    'reviewers' => 0,
    'sessions' => 0,
    'committees' => 0,
    'acceptance_rate' => 0
];

try {

    /*
    -----------------------------------------------------
    SUBMISSIONS
    -----------------------------------------------------
    */

    $stmt = $db->prepare("
        SELECT COUNT(*)
        FROM submissions
        WHERE conference_id = ?
    ");

    $stmt->execute([
        (int)$conference['id']
    ]);

    $liveAnalytics['submissions'] =
        (int)$stmt->fetchColumn();

    /*
    -----------------------------------------------------
    ACCEPTED
    -----------------------------------------------------
    */

    $stmt = $db->prepare("
        SELECT COUNT(*)
        FROM submissions
        WHERE conference_id = ?
        AND (
            status = 'accepted'
            OR decision = 'accepted'
        )
    ");

    $stmt->execute([
        (int)$conference['id']
    ]);

    $liveAnalytics['accepted'] =
        (int)$stmt->fetchColumn();

    /*
    -----------------------------------------------------
    TRACKS
    -----------------------------------------------------
    */

    $stmt = $db->prepare("
        SELECT COUNT(*)
        FROM tracks
        WHERE conference_id = ?
        AND is_active = 1
    ");

    $stmt->execute([
        (int)$conference['id']
    ]);

    $liveAnalytics['tracks'] =
        (int)$stmt->fetchColumn();

/*
-----------------------------------------------------
REVIEWERS
-----------------------------------------------------
*/

try {

    $stmt = $db->prepare("
        SELECT COUNT(DISTINCT reviewer_id)
        FROM reviews
        WHERE conference_id = ?
    ");

    $stmt->execute([
        (int)$conference['id']
    ]);

    $liveAnalytics['reviewers'] =
        (int)$stmt->fetchColumn();

} catch (\Throwable $e) {

    $liveAnalytics['reviewers'] = 0;
}    


    /*
    -----------------------------------------------------
    SESSIONS
    -----------------------------------------------------
    */

    $stmt = $db->prepare("
        SELECT COUNT(*)
        FROM conference_sessions
        WHERE conference_id = ?
        AND is_active = 1
    ");

    $stmt->execute([
        (int)$conference['id']
    ]);

    $liveAnalytics['sessions'] =
        (int)$stmt->fetchColumn();

    /*
    -----------------------------------------------------
    COMMITTEES
    -----------------------------------------------------
    */

    $committees = [];

try {

    $stmt = $db->prepare("
        SELECT
            id,
            committee_type,
            full_name_ar,
            full_name_en,
            affiliation_ar,
            affiliation_en,
            role_title_ar,
            role_title_en,
            image_path,
            sort_order
        FROM conference_committee_people
        WHERE conference_id = ?
          AND org_id = ?
          AND is_visible = 1
        ORDER BY
            committee_type,
            sort_order,
            id
    ");

    $stmt->execute([
        (int)$conference['id'],
        (int)$conference['org_id']
    ]);

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

} catch (\Throwable $e) {

    error_log(
        'PUBLIC COMMITTEE PEOPLE ERROR: '
        . $e->getMessage()
    );
}
    $liveAnalytics['committees'] =
        (int)$stmt->fetchColumn();

    /*
    -----------------------------------------------------
    ACCEPTANCE RATE
    -----------------------------------------------------
    */

    if (
        $liveAnalytics['submissions'] > 0
    ) {

        $liveAnalytics['acceptance_rate'] =
            round(

                (
                    $liveAnalytics['accepted']
                    /
                    $liveAnalytics['submissions']
                ) * 100,

                1
            );
    }

} catch (\Throwable $e) {

    error_log(
        'LIVE ANALYTICS ERROR: '
        . $e->getMessage()
    );
}
$issues = [];
$articlesByIssue = [];

try {

    $stmtIssues = $db->prepare("
        SELECT *
        FROM issues
        WHERE conference_id = ?
        ORDER BY id DESC
    ");

    $stmtIssues->execute([
        (int)$conference['id']
    ]);

    $issues =
        $stmtIssues->fetchAll(\PDO::FETCH_ASSOC);

} catch (\Throwable $e) {

    error_log(
        'PUBLIC ISSUES ERROR: '
        . $e->getMessage()
    );
}
        
require BASE_PATH . '/app/views/public/conference_business.php';
    }

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

    if (!$slug) {

        http_response_code(404);
        die("Conference not found.");
    }

    /*
    --------------------------------------------------
    LOAD CONFERENCE
    --------------------------------------------------
    */

    $stmt = $db->prepare("
        SELECT *
        FROM conferences
        WHERE slug = ?
        LIMIT 1
    ");

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

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

    if (!$conference) {

        http_response_code(404);
        die("Conference not found.");
    }

    /*
    --------------------------------------------------
    FORCE CONFERENCE ID
    --------------------------------------------------
    */

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

    /*
    --------------------------------------------------
    DIRECTLY RENDER PUBLIC PAGE
    --------------------------------------------------
    */

    return $this->index();
}

}
