<?php

class BaseController
{
    /** @var View */
    protected $view;

    public function __construct()
    {
        // Use the shared View class defined in bootstrap/app.php
        $this->view = new View(VIEWS_PATH . '/');
    }
    protected function render(string $view, array $data = []): void
    {
        // Strip ".php" if passed
        $view = preg_replace('/\.php$/', '', $view);

        // DEBUG: resolve the file path we *expect*
        $viewPath  = rtrim(VIEWS_PATH, '/');
        $viewFile  = $viewPath . '/' . $view . '.php';
        $real      = realpath($viewFile);
        $exists    = file_exists($viewFile) ? 'yes' : 'no';

        error_log('BaseController::render view     = ' . $view);
        error_log('BaseController::render VIEWS_PATH = ' . VIEWS_PATH);
        error_log('BaseController::render viewFile   = ' . $viewFile);
        error_log('BaseController::render realpath   = ' . ($real ?: 'false'));
        error_log('BaseController::render exists?    = ' . $exists);

        try {
            echo $this->view->render($view, $data);
        } catch (Exception $e) {
            error_log("BaseController::render error: " . $e->getMessage());
            echo "<h1>Application Error</h1>";
            echo "<p>View not found: " . htmlspecialchars($view) . "</p>";
            if (!empty($_ENV['APP_DEBUG']) && $_ENV['APP_DEBUG'] === 'true') {
                echo "<pre>" . htmlspecialchars($e->getMessage()) . "</pre>";
            }
        }
    }


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

    protected function authCheck(): void
    {
        if (empty($_SESSION['user_id'])) {
            header('Location: /lead-management/public/login');
            exit;
        }
    }

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