<?php
namespace App\Controllers;

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

use App\Core\Database;

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

    private function slug(): string
    {
        $slug = trim((string)($_GET['slug'] ?? ''));

        if ($slug === '') {
            $path = parse_url($_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH);
            $path = trim((string)$path, '/');
            $parts = explode('/', $path);
            $idx = array_search('c', $parts, true);
            if ($idx !== false && !empty($parts[$idx + 1])) {
                $slug = $parts[$idx + 1];
            }
        }

        return $slug;
    }

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

        if ($slug !== '') {
            $stmt = $this->db()->prepare("
                SELECT c.*, o.name AS org_name, o.logo_path AS org_logo, o.banner_path AS org_banner
                FROM conferences c
                LEFT JOIN organizations o ON o.id = c.org_id
                WHERE c.slug = ?
                  AND c.is_active = 1
                LIMIT 1
            ");
            $stmt->execute([$slug]);
        } else {
            $stmt = $this->db()->prepare("
                SELECT c.*, o.name AS org_name, o.logo_path AS org_logo, o.banner_path AS org_banner
                FROM conferences c
                LEFT JOIN organizations o ON o.id = c.org_id
                WHERE c.id = ?
                  AND c.is_active = 1
                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 home()
    {
        $conference = $this->conference();
        $cid = (int)$conference['id'];
        $orgId = (int)$conference['org_id'];

/*
|--------------------------------------------------------------------------
| SUPERADMIN HOMEPAGE OVERRIDE
|--------------------------------------------------------------------------
*/

$isSuperAdmin =
    (
        ($_SESSION['role'] ?? '')
        === 'super_admin'
    );

$conferenceRole =
    $_SESSION['conference_role']
    ?? '';

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

$_SESSION['conference_id']
    = $cid;

$_SESSION['current_conference_id']
    = $cid;

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

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

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

        $committees = $this->rows("
            SELECT *
            FROM conference_committees
            WHERE conference_id = ?
              AND org_id = ?
              AND is_active = 1
            ORDER BY committee_type, sort_order, id
            LIMIT 12
        ", [$cid, $orgId]);

        $themes = $this->rows("
            SELECT *
            FROM conference_themes
            WHERE conference_id = ?
              AND org_id = ?
              AND is_active = 1
            ORDER BY theme_type, sort_order, id
        ", [$cid, $orgId]);

/*
|--------------------------------------------------------------------------
| SPEAKERS
|--------------------------------------------------------------------------
*/

$speakers = $this->rows("
    SELECT *
    FROM conference_speakers
    WHERE conference_id = ?
    ORDER BY id ASC
    LIMIT 12
", [$cid]);

/*
|--------------------------------------------------------------------------
| SPONSORS
|--------------------------------------------------------------------------
*/

$sponsors = $this->rows("
    SELECT *
    FROM conference_sponsors
    WHERE conference_id = ?
      AND is_active = 1
    ORDER BY sort_order ASC, id ASC
", [$cid]);

/*
|--------------------------------------------------------------------------
| TRACKS / THEMES
|--------------------------------------------------------------------------
*/

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

        require BASE_PATH . '/app/views/public/conference_home_slug.php';
    }

    public function redirectRegister()
    {
        $conference = $this->conference();
        header("Location: /easychair/register?conference=" . urlencode($conference['slug']));
        exit;
    }

    public function program()
    {
        $conference = $this->conference();
        header("Location: /easychair/conference/program?conference_id=" . (int)$conference['id']);
        exit;
    }

    public function proceedings()
    {
        $conference = $this->conference();
        header("Location: /easychair/conference/proceedings?conference_id=" . (int)$conference['id']);
        exit;
    }
}
