<?php

namespace App\Core;

use App\Config\Database;
use App\Helpers\Url;

abstract class Controller
{
    protected $db;
    protected $baseUrl;

    public function __construct()
    {
        $this->db = Database::getInstance()->getConnection();
        // Use absolute URL when available so views that print $baseUrl render full links
        $this->baseUrl = rtrim(Url::to(''), '/');
    }

    protected function view($view, $data = [], $useLayout = true)
    {
        $data['baseUrl'] = $this->baseUrl;
        $viewPath = __DIR__ . '/../../resources/views/' . $view . '.php';

        if (file_exists($viewPath)) {
            if ($useLayout) {
                ob_start();
                extract($data);
                require $viewPath;
                $content = ob_get_clean();
                require __DIR__ . '/../../resources/views/layouts/app.php';
            } else {
                extract($data);
                require $viewPath;
            }
        } else {
            echo "View not found: " . $viewPath;
        }
    }

    protected function redirect($url)
    {
        Url::redirect($url);
    }

    protected function json($data, $status = 200)
    {
        http_response_code($status);
        header('Content-Type: application/json');
        echo json_encode($data);
        exit;
    }

    protected function input($key = null)
    {
        $data = array_merge($_GET, $_POST);
        if ($key) {
            return isset($data[$key]) ? $data[$key] : null;
        }
        return (object) $data;
    }
}
