<?php
/**
 * ASISMA CRM - Controlador Base del MVC
 */
abstract class Controller {

    protected function render($view, $data = array()) {
        extract($data);

        $viewFile = ROOT_DIR . '/app/views/' . $view . '.php';
        if (!file_exists($viewFile)) {
            throw new Exception("La vista '{$view}' no existe.");
        }

        $pageTitle = isset($data['title']) ? $data['title'] : 'ASISMA CRM';

        ob_start();
        require $viewFile;
        $content = ob_get_clean();

        require_once ROOT_DIR . '/app/views/layout/app.php';
    }

    protected function renderPartial($view, $data = array()) {
        extract($data);

        $viewFile = ROOT_DIR . '/app/views/' . $view . '.php';
        if (!file_exists($viewFile)) {
            throw new Exception("La vista '{$view}' no existe.");
        }

        require $viewFile;
    }

    protected function json($data, $statusCode = 200) {
        if (ob_get_length()) {
            ob_clean();
        }

        http_response_code($statusCode);
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode($data);
        exit;
    }

    protected function redirect($route) {
        $route = ltrim($route, '/');
        header("Location: " . APP_URL . "/" . $route);
        exit;
    }

    protected function input($key, $default = null) {
        $value = null;
        if (isset($_POST[$key])) {
            $value = $_POST[$key];
        } elseif (isset($_GET[$key])) {
            $value = $_GET[$key];
        } else {
            return $default;
        }

        if (is_array($value)) {
            return array_map(array($this, 'sanitizeValue'), $value);
        }

        return $this->sanitizeValue($value);
    }

    private function sanitizeValue($value) {
        return htmlspecialchars(trim($value), ENT_QUOTES, 'UTF-8');
    }

    protected function isAdmin() {
        return SessionHelper::isAdmin();
    }

    protected function getTenantFilter($tableAlias = '') {
        if ($this->isAdmin()) {
            return " 1=1 ";
        }

        $franquiciadoId = SessionHelper::getFranquiciadoId();
        if (!$franquiciadoId) {
            return " 1=0 ";
        }

        $prefix = !empty($tableAlias) ? "`{$tableAlias}`." : "";
        return " {$prefix}`franquiciado_id` = " . intval($franquiciadoId) . " ";
    }
}
