<?php

namespace App\Core;

use App\Core\Database;

class EnterpriseController extends Controller
{
    /**
     * Database connection
     */
    protected function db()
    {
        return Database::getInstance();
    }

    /**
     * JSON response
     */
    protected function json($data, int $status = 200): void
    {
        if (ob_get_length()) {
            ob_end_clean();
        }

        http_response_code($status);

        header('Content-Type: application/json; charset=utf-8');

        echo json_encode(
            $data,
            JSON_UNESCAPED_UNICODE |
            JSON_PRETTY_PRINT
        );

        exit;
    }

    /**
     * HTTP redirect
     */
    protected function redirect(string $url): void
    {
        header('Location: ' . $url);
        exit;
    }

    /**
     * Flash message
     */
    protected function flash(string $type, string $message): void
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        $_SESSION['flash'] = [
            'type' => $type,
            'message' => $message
        ];
    }

    /**
     * Current request method
     */
    protected function isPost(): bool
    {
        return ($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST';
    }

    /**
     * Current authenticated user
     */
    protected function user(): array
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        return $_SESSION['user'] ?? [];
    }

    /**
     * Current role
     */
    protected function role(): string
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        return (string)(
            $_SESSION['conference_role']
            ??
            $_SESSION['role']
            ??
            $_SESSION['user_role']
            ??
            ''
        );
    }

    /**
     * Transaction helpers
     */
    protected function begin(): void
    {
        $this->db()->beginTransaction();
    }

    protected function commit(): void
    {
        if ($this->db()->inTransaction()) {
            $this->db()->commit();
        }
    }

    protected function rollback(): void
    {
        if ($this->db()->inTransaction()) {
            $this->db()->rollBack();
        }
    }
}
