<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class MY_Loader extends CI_Loader
{
    protected $_layout    = 'layouts/main'; // default layout
    protected $_in_layout = false;          // guard anti rekursif

    public function set_layout($layout) { $this->_layout = $layout; return $this; }
    public function disable_layout()    { $this->_layout = FALSE;   return $this; }

    public function partial($view, $vars = [], $return = FALSE) {
        return $this->_ci_load([
            '_ci_view'   => $view,
            '_ci_vars'   => $this->_ci_prepare_view_vars($vars),
            '_ci_return' => $return
        ]);
    }

    public function view($view, $vars = [], $return = FALSE)
    {
        if ($this->_layout === FALSE || $this->_in_layout === TRUE) {
            return $this->_ci_load([
                '_ci_view'   => $view,
                '_ci_vars'   => $this->_ci_prepare_view_vars($vars),
                '_ci_return' => $return
            ]);
        }

        $content = $this->_ci_load([
            '_ci_view'   => $view,
            '_ci_vars'   => $this->_ci_prepare_view_vars($vars),
            '_ci_return' => TRUE
        ]);

        $layout_vars = is_array($vars) ? $vars : [];
        $layout_vars['content_for_layout'] = $content;

        $this->_in_layout = true;
        $out = $this->_ci_load([
            '_ci_view'   => $this->_layout,
            '_ci_vars'   => $this->_ci_prepare_view_vars($layout_vars),
            '_ci_return' => $return
        ]);
        $this->_in_layout = false;

        return $out;
    }
}
