<?php

namespace App\Core;

abstract class Controller
{
    protected array $data = [];

    protected function view(string $view, array $data = [], string $layout = 'main'): void
    {
        echo View::render($view, $data, $layout);
    }

    protected function viewPartial(string $view, array $data = []): void
    {
        echo View::render($view, $data, null);
    }

    protected function json(array $data, int $statusCode = 200): void
    {
        http_response_code($statusCode);
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
        exit;
    }

    protected function redirect(string $url): void
    {
        header("Location: {$url}");
        exit;
    }

    protected function getCurrentUser(): ?array
    {
        if (!isset($_SESSION['isLoggedIn']) || $_SESSION['isLoggedIn'] !== true) {
            return null;
        }

        return [
            'id' => $_SESSION['user_id'] ?? null,
            'email' => $_SESSION['user_email'] ?? '',
            'full_name' => $_SESSION['full_name'] ?? '',
            'phone' => $_SESSION['user_phone'] ?? '',
            'city' => $_SESSION['user_city'] ?? '',
            'is_admin' => $_SESSION['isAdmin'] ?? false,
            'login_time' => $_SESSION['login_time'] ?? null
        ];
    }

    protected function isAuthenticated(): bool
    {
        return isset($_SESSION['isLoggedIn']) && $_SESSION['isLoggedIn'] === true;
    }

    protected function isAdmin(): bool
    {
        return $this->isAuthenticated() && isset($_SESSION['isAdmin']) && $_SESSION['isAdmin'] === true;
    }

    protected function requireAuth(): void
    {
        if (!$this->isAuthenticated()) {
            $redirect = urlencode($_SERVER['REQUEST_URI']);
            $this->redirect("/login?redirect={$redirect}");
        }
    }

    protected function requireAdmin(): void
    {
        if (!$this->isAdmin()) {
            $this->redirect('/login');
        }
    }

    protected function getPost(?string $key = null, $default = null)
    {
        if ($key === null) {
            return $_POST;
        }
        return $_POST[$key] ?? $default;
    }

    protected function getQuery(?string $key = null, $default = null)
    {
        if ($key === null) {
            return $_GET;
        }
        return $_GET[$key] ?? $default;
    }

    protected function setFlash(string $type, string $message): void
    {
        $_SESSION['flash'][$type] = $message;
    }

    protected function getFlash(string $type): ?string
    {
        $message = $_SESSION['flash'][$type] ?? null;
        unset($_SESSION['flash'][$type]);
        return $message;
    }
}
