<?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 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 =
    (
        ec_is_superadmin()
    );

$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
        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
    FROM conference_committee_people
    WHERE conference_id = ?
      AND org_id = ?
      AND is_visible = 1
    ORDER BY
        committee_type,
        sort_order,
        id
", [$cid, $orgId]);


//$committees = [];

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

/*
|--------------------------------------------------------------------------
| CMS SECTIONS
|--------------------------------------------------------------------------
*/

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

/*
|--------------------------------------------------------------------------
| PACK1012
| Committee Images Source
|--------------------------------------------------------------------------
*/

$groupedCommittees = [];

try {

    $db = $this->db();

    $stmt = $db->prepare("
        SELECT *
        FROM conference_committee_people
        WHERE conference_id = ?
        AND org_id = ?
        AND is_visible = 1
        ORDER BY committee_type,
                 sort_order,
                 id
    ");

    $stmt->execute([
        $cid,
        $orgId
    ]);

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

    foreach ($committeeRows as $row) {

        $type =
            strtolower(
                trim(
                    (string)(
                        $row['committee_type']
                        ?? 'other'
                    )
                )
            );

        $groupedCommittees[$type][] =
            $row;
    }

} catch (\Throwable $e) {

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

/*
|--------------------------------------------------------------------------
| PACK1020
| Live CMS Sections from /admin/conference-home/sections
|--------------------------------------------------------------------------
*/

$cmsSections = [];

try {

    $db = $this->db();

    $cmsTables = [
        'conference_home_sections',
        'conference_homepage_sections',
        'conference_public_sections',
        'conference_homepage_cms_sections'
    ];

    $cmsTable = '';

    foreach ($cmsTables as $candidateTable) {

        $check = $db->prepare("
            SELECT COUNT(*)
            FROM information_schema.tables
            WHERE table_schema = DATABASE()
              AND table_name = ?
        ");

        $check->execute([$candidateTable]);

        if ((int)$check->fetchColumn() > 0) {
            $cmsTable = $candidateTable;
            break;
        }
    }

    if ($cmsTable !== '') {

        $colStmt = $db->prepare("
            SELECT column_name
            FROM information_schema.columns
            WHERE table_schema = DATABASE()
              AND table_name = ?
        ");

        $colStmt->execute([$cmsTable]);

        $cols = array_map(
            static fn($r) => (string)$r['column_name'],
            $colStmt->fetchAll(\PDO::FETCH_ASSOC)
        );

        $has = static function (string $col) use ($cols): bool {
            return in_array($col, $cols, true);
        };

        $keyCol =
            $has('section_key') ? 'section_key' :
            ($has('section_code') ? 'section_code' :
            ($has('section_type') ? 'section_type' :
            ($has('block_type') ? 'block_type' :
            ($has('type') ? 'type' : 'id'))));

        $activeCol =
            $has('is_active') ? 'is_active' :
            ($has('is_enabled') ? 'is_enabled' :
            ($has('is_visible') ? 'is_visible' : ''));

        $orderCol =
            $has('sort_order') ? 'sort_order' :
            ($has('display_order') ? 'display_order' : 'id');

        $where = [
            "conference_id = ?"
        ];

        $params = [
            $cid
        ];

        if ($has('org_id')) {
            $where[] = "org_id = ?";
            $params[] = $orgId;
        }

        if ($activeCol !== '') {
            $where[] = $activeCol . " = 1";
        }

        $sql =
            "SELECT *,
                    " . $keyCol . " AS section_key
             FROM " . $cmsTable . "
             WHERE " . implode(" AND ", $where) . "
             ORDER BY " . $orderCol . " ASC, id ASC";

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

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

} catch (\Throwable $e) {

    error_log(
        'PACK1020 CMS SECTIONS ERROR: ' .
        $e->getMessage()
    );
}

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

    public function submit()
    {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }

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

        $key = trim($_GET['id'] ?? '');

        if ($key === '') {
            die('Conference not specified.');
        }

        $stmt = $db->prepare("
            SELECT id, org_id, slug, short_name
            FROM conferences
            WHERE slug = ?
               OR short_name = ?
               OR id = ?
            LIMIT 1
        ");

        $stmt->execute([
            $key,
            $key,
            ctype_digit($key) ? (int)$key : 0
        ]);

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

        if (!$conf) {
            die('Conference not found.');
        }

        $_SESSION['submit_conference_id'] = (int)$conf['id'];
        $_SESSION['conference_id'] = (int)$conf['id'];
        $_SESSION['org_id'] = (int)$conf['org_id'];
        $_SESSION['submit_slug'] = $key;

        $target = '/easychair/author/submit?id=' . (int)$conf['id'];

        if (empty($_SESSION['user_id'])) {
            header('Location: /easychair/login?continue=' . urlencode($target));
            exit;
        }

        header('Location: ' . $target);
        exit;
    }

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

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        exit;
    }

    $referer =
        $_SERVER['HTTP_REFERER']
        ?? '/easychair';

    try {

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

        $name =
            trim(
                (string)(
                    $_POST['full_name']
                    ?? ''
                )
            );

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

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

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

        if (
            $conferenceId <= 0
            ||
            $name === ''
            ||
            $email === ''
            ||
            $message === ''
        ) {

            $_SESSION['quick_response_status'] = [
                'type' => 'danger',
                'message' => 'Please complete all required fields.'
            ];

            header('Location: ' . $referer);
            exit;
        }

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

            $_SESSION['quick_response_status'] = [
                'type' => 'danger',
                'message' => 'Please enter a valid email address.'
            ];

            header('Location: ' . $referer);
            exit;
        }

        $stmt =
            $this->db()->prepare("
                INSERT INTO conference_contact_messages
                (
                    conference_id,
                    full_name,
                    email,
                    subject,
                    message,
                    ip_address,
                    user_agent
                )
                VALUES
                (
                    ?,?,?,?,?,?,?
                )
            ");

        $stmt->execute([
            $conferenceId,
            $name,
            $email,
            $subject,
            $message,
            $_SERVER['REMOTE_ADDR'] ?? '',
            $_SERVER['HTTP_USER_AGENT'] ?? ''
        ]);

        $recipient =
            'info@julms.com';

        try {

            $sectionStmt =
                $this->db()->prepare("
                    SELECT settings_json
                    FROM conference_home_sections
                    WHERE conference_id = ?
                      AND section_key = 'quick_response_form'
                      AND enabled = 1
                    ORDER BY id DESC
                    LIMIT 1
                ");

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

            $settingsRaw =
                (string)(
                    $sectionStmt->fetchColumn()
                    ?: ''
                );

            $settings =
                json_decode(
                    $settingsRaw,
                    true
                );

            if (
                is_array($settings)
                &&
                !empty($settings['recipient_email'])
                &&
                filter_var(
                    $settings['recipient_email'],
                    FILTER_VALIDATE_EMAIL
                )
            ) {
                $recipient =
                    $settings['recipient_email'];
            }

        } catch (\Throwable $settingsError) {

            error_log(
                'QUICK RESPONSE SETTINGS ERROR: '
                . $settingsError->getMessage()
            );
        }

        $safeSubject =
            $subject !== ''
            ? $subject
            : 'Conference Contact Form';

        $mailBody =
            '<div style="font-family:Arial,Tahoma,sans-serif;line-height:1.7">'
            . '<h2>New Conference Inquiry</h2>'
            . '<p><strong>Name:</strong> '
            . htmlspecialchars($name, ENT_QUOTES, 'UTF-8')
            . '</p>'
            . '<p><strong>Email:</strong> '
            . htmlspecialchars($email, ENT_QUOTES, 'UTF-8')
            . '</p>'
            . '<p><strong>Subject:</strong> '
            . htmlspecialchars($safeSubject, ENT_QUOTES, 'UTF-8')
            . '</p>'
            . '<p><strong>Message:</strong><br>'
            . nl2br(
                htmlspecialchars(
                    $message,
                    ENT_QUOTES,
                    'UTF-8'
                )
            )
            . '</p>'
            . '</div>';

        try {

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

            if (!function_exists('send_mail_smtp')) {
                throw new \RuntimeException(
                    'send_mail_smtp function not found'
                );
            }

            send_mail_smtp(
                $recipient,
                'Conference Inquiry: ' . $safeSubject,
                $mailBody
            );

            $_SESSION['quick_response_status'] = [
                'type' => 'success',
                'message' => 'Your message has been sent successfully.'
            ];

        } catch (\Throwable $mailError) {

            error_log(
                'QUICK RESPONSE MAIL ERROR: '
                . $mailError->getMessage()
            );

            $_SESSION['quick_response_status'] = [
                'type' => 'warning',
                'message' => 'Your message was saved, but email delivery failed.'
            ];
        }

    } catch (\Throwable $e) {

        error_log(
            'QUICK RESPONSE ERROR: '
            . $e->getMessage()
        );

        $_SESSION['quick_response_status'] = [
            'type' => 'danger',
            'message' => 'Unable to send your request. Please try again.'
        ];
    }

    header('Location: ' . $referer);
    exit;
}

}
