<?php

namespace App\Controllers;

use PDO;

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

class AdminHomepageSectionsController extends Controller
{
    public function index()
    {
        $db = Database::getInstance();

        $conferenceId =
            TenantContext::conferenceId();

        $stmt = $db->prepare("
            SELECT *
            FROM conference_home_sections
            WHERE conference_id = ?
            ORDER BY sort_order ASC
        ");

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

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

        $this->render(
            'admin/homepage_sections/index',
            compact('sections')
        );
    }

    public function edit()
    {
        $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);

        $this->render(
            'admin/homepage_sections/edit',
            compact('section')
        );
    }

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

        $stmt = $db->prepare("
            UPDATE conference_home_sections
            SET
                title_en = ?,
                title_ar = ?,
                subtitle_en = ?,
                subtitle_ar = ?,
                icon_class = ?,
                theme_name = ?,
                enabled = ?
            WHERE id = ?
            LIMIT 1
        ");

        $stmt->execute([

            $_POST['title_en'] ?? null,
            $_POST['title_ar'] ?? null,

            $_POST['subtitle_en'] ?? null,
            $_POST['subtitle_ar'] ?? null,

            $_POST['icon_class'] ?? null,
            $_POST['theme_name'] ?? null,

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

            (int)$_POST['id']
        ]);

        $_SESSION['success'] =
            'Homepage section updated';

        header(
            'Location: /easychair/admin/homepage-sections'
        );

        exit;
    }
}
