<?php

namespace App\Controllers;

use PDO;

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

class HomepageSectionsController 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',
            [
                'sections' => $sections
            ]
        );
    }

    public function toggle()
    {

        $db = Database::getInstance();

        $id =
            (int)($_GET['id'] ?? 0);

        $stmt = $db->prepare("
            UPDATE conference_home_sections
            SET enabled =
                CASE
                    WHEN enabled = 1 THEN 0
                    ELSE 1
                END
            WHERE id = ?
        ");

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

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

        exit;
    }

    public function moveUp()
    {
        $this->move(-10);
    }

    public function moveDown()
    {
        $this->move(10);
    }

    private function move(int $delta)
    {

        $db = Database::getInstance();

        $id =
            (int)($_GET['id'] ?? 0);

        $stmt = $db->prepare("
            UPDATE conference_home_sections
            SET sort_order = sort_order + ?
            WHERE id = ?
        ");

        $stmt->execute([
            $delta,
            $id
        ]);

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

        exit;
    }

}
