<?php

namespace App\Controllers;

use PDO;
use App\Core\Controller;
use App\Core\Database;
use App\Core\TenantContext;

class AdminHomepageStudioController extends Controller
{
    public function index()
    {
        /*
        ------------------------------------------------
        SESSION
        ------------------------------------------------
        */

        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        /*
        ------------------------------------------------
        AUTH
        ------------------------------------------------
        */

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

            header("Location: /easychair/login");
            exit;
        }

        /*
        ------------------------------------------------
        DB
        ------------------------------------------------
        */

        $db = Database::getInstance();

        /*
        ------------------------------------------------
        SUPERADMIN FALLBACK
        ------------------------------------------------
        */

        if (
            ($_SESSION['role'] ?? '') === 'super_admin'
            &&
            empty($_SESSION['conference_id'])
        ) {

            $stmtConf = $db->query("
                SELECT id
                FROM conferences
                ORDER BY id ASC
                LIMIT 1
            ");

            $firstConference =
                $stmtConf->fetch(PDO::FETCH_ASSOC);

            if ($firstConference) {

                $_SESSION['conference_id']
                    = (int)$firstConference['id'];

                $_SESSION['current_conference_id']
                    = (int)$firstConference['id'];
            }
        }

        /*
        ------------------------------------------------
        CONFERENCE CONTEXT
        ------------------------------------------------
        */

        $conferenceId = 0;

        if (class_exists(TenantContext::class)) {

            $conferenceId =
                (int)TenantContext::conferenceId();
        }

        if ($conferenceId <= 0) {

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

        if ($conferenceId <= 0) {

            die('Conference context missing.');
        }

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

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

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

        $conference =
            $stmt->fetch(PDO::FETCH_ASSOC) ?: [];

        /*
        ------------------------------------------------
        COUNTS
        ------------------------------------------------
        */

        $tables = [

            'blocks' =>
                'conference_homepage_blocks',

            'speakers' =>
                'conference_speakers',

            'sponsors' =>
                'conference_sponsors',

            'committees' =>
                'conference_committees',

            'themes' =>
                'conference_themes',

            'tracks' =>
                'tracks',
        ];

        $stats = [];

        foreach ($tables as $key => $table) {

            try {

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

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

                $stats[$key] =
                    (int)$stmt->fetchColumn();

            } catch (\Throwable $e) {

                $stats[$key] = 0;
            }
        }

        /*
        ------------------------------------------------
        MODULES
        ------------------------------------------------
        */

        $modules = [

            [
                'title' => 'Homepage Builder',
                'icon'  => 'fa-panorama',
                'count' => $stats['blocks'],
                'url'   =>
                    '/easychair/admin/conference-home-builder',
            ],

            [
                'title' => 'Homepage Sections',
                'icon'  => 'fa-layer-group',
                'count' => $stats['blocks'],
                'url'   =>
                    '/easychair/admin/homepage-sections',
            ],

            [
                'title' => 'Homepage Content',
                'icon'  => 'fa-pen-to-square',
                'count' => $stats['blocks'],
                'url'   =>
                    '/easychair/admin/homepage-content',
            ],

            [
                'title' => 'Homepage Designer',
                'icon'  => 'fa-palette',
                'count' => 1,
                'url'   =>
                    '/easychair/admin/homepage-design',
            ],

            [
                'title' => 'Conference Speakers',
                'icon'  => 'fa-microphone-lines',
                'count' => $stats['speakers'],
                'url'   =>
                    '/easychair/admin/conference-speakers',
            ],

            [
                'title' => 'Conference Sponsors',
                'icon'  => 'fa-handshake',
                'count' => $stats['sponsors'],
                'url'   =>
                    '/easychair/admin/conference-sponsors',
            ],

            [
                'title' => 'Conference Themes',
                'icon'  => 'fa-layer-group',
                'count' => $stats['themes'],
                'url'   =>
                    '/easychair/admin/conference-themes',
            ],

            [
                'title' => 'Tracks',
                'icon'  => 'fa-diagram-project',
                'count' => $stats['tracks'],
                'url'   =>
                    '/easychair/admin/tracks',
            ],

            [
                'title' => 'Committees',
                'icon'  => 'fa-users',
                'count' => $stats['committees'],
                'url'   =>
                    '/easychair/admin/conference-committees',
            ],
        ];

        /*
        ------------------------------------------------
        HOMEPAGE FLOW
        ------------------------------------------------
        */

        $stmt = $db->prepare("
            SELECT
                id,
                block_type,
                title_en,
                title_ar,
                sort_order,
                is_active
            FROM conference_homepage_blocks
            WHERE conference_id = ?
            ORDER BY sort_order ASC, id ASC
            LIMIT 20
        ");

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

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

        /*
        ------------------------------------------------
        VIEW
        ------------------------------------------------
        */

        ob_start();

        require BASE_PATH
            . '/app/views/admin/homepage_studio/index.php';

        $content =
            ob_get_clean();

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