<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;

final class AdminActionsTenantController extends Controller
{
    private function guard(): void {
        if (function_exists('require_admin_or_chair_tenant')) {
            require_admin_or_chair_tenant();
        } else {
            require_admin_or_chair();
        }
        require_org_context();

        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
            http_response_code(405);
            echo "Method Not Allowed";
            exit;
        }
    }

    private function logErr(string $msg): void {
        $f = BASE_PATH . '/storage/logs/app_error.log';
        @file_put_contents($f, '['.date('Y-m-d H:i:s')."] ACTION ERROR: ".$msg."\n", FILE_APPEND);
    }

    public function saveHomepage(): void {
        $this->guard();
        try {
            (new AdminHomepageTenantController())->save();
        } catch (\Throwable $e) {
            $this->logErr("saveHomepage: ".$e->getMessage()." @ ".$e->getFile().":".$e->getLine());
            http_response_code(500);
            echo "Internal error";
        }
    }

    public function saveHomepageBlocks(): void {
        $this->guard();
        try {
            (new AdminHomepageBlocksTenantController())->save();
        } catch (\Throwable $e) {
            $this->logErr("saveHomepageBlocks: ".$e->getMessage()." @ ".$e->getFile().":".$e->getLine());
            http_response_code(500);
            echo "Internal error";
        }
    }

    public function saveSession(): void
    {
        $this->guard();

        $confId = (int)($_POST['conference_id'] ?? 0);
        if ($confId <= 0) {
            $this->logErr("saveSession: Missing conference_id. POST keys=".implode(',', array_keys($_POST)));
            http_response_code(400);
            echo "Missing conference_id";
            exit;
        }

        try {
            (new AdminScheduleTenantController())->save();
        } catch (\Throwable $e) {
            $this->logErr("saveSession: ".$e->getMessage()." @ ".$e->getFile().":".$e->getLine());
            http_response_code(500);
            echo "Internal error";
        }
    }
}
