<?php

namespace onespace\tools\widgets\ui\banner\base;

use Exception;
use onespace\tools\components\SelectedEstate;
use onespace\tools\widgets\ui\banner\base\BannerTemplate;
use onespace\tools\widgets\ui\banner\base\TopBanner;
use onespace\tools\widgets\ui\EstateLogo;
use onespace\tools\widgets\ui\ProfilePic;
use Yii;
use yii\widgets\Pjax;

/**
 * Draw the top banner with estate links. It contains user's personal information with narrow margins.
 * 
 * @author  Gareth Palmer <gareth@one-space.co.za>
 */

abstract class EstatesBaseBanner extends TopBanner implements BannerTemplate {

    /**
     * The type of estate banner, estate management, erf owner or both.
     * 
     * @var string  $type
     * 
     * @access  protected
     */

    protected string $type;

    /**
     * The id of the PJAX element if you need to specify one. Otherwise it'll randomly generate.
     * 
     * @var string  $pjax_id
     * 
     * @access  public
     */

    public string $pjax_id;


    /**
     * {@inheritdoc}
     * 
     * @access  public
     */

    public function init(): void {
        parent::init();
        $this->pjax_id ??= 'pj' . Yii::$app->security->generateRandomString(8);
    }


    /**
     * {@inheritdoc}
     * 
     * @return  string
     * 
     * @access  public
     */

    public function run(): string {
        if (!isset($this->type)) {
            throw new Exception('$this->type not set');
        }
        Pjax::begin([
            'id' => $this->pjax_id,
            'linkSelector' => '.narrow-banner a',
        ]);
        $bar = parent::run();
        if (isset($this->container_class)) {
            $bar .= " {$this->container_class}";
        }
        $bar .= " estates-banner narrow-banner'>";

        $estateClass = "\\{$this->namespace}\models\Estate";
        $estates = match ($this->type) {
            'admin' => [$estateClass::currentUser()->managerEstates()],
            'erf'   => [$estateClass::currentUser()->residentEstates()],
            'both' => [
                $estateClass::currentUser()->managerEstates(),
                $estateClass::currentUser()->residentEstates(),
            ],
            default => []
        };

        $selectedEstate = SelectedEstate::getCache(match ($this->type) {
            'erf' => 'r',
            default => 'm',
        });
        $selectedEstateId = $selectedEstate === false ? $estates[0][0]->id : $selectedEstate['id'];

        $uri = '/' . Yii::$app->request->pathInfo;
        $bar .= ProfilePic::widget([
            'userClass' => "\\{$this->namespace}\models\User",
            'options' => ['class' => "profile-pic-img"],
            'link'    => ['href' => 'javascript:void(0)'],
        ]);
        $bar .= '<div class="pp-vertical-rule"></div>';

        $contained = [];
        foreach ($estates as $entry) {
            foreach ($entry as $estate) {
                if (in_array($estate->id, $contained)) {
                    continue;
                }
                $contained[] = $estate->id;
                $sel = $selectedEstateId == $estate->id || Yii::$app->request->get('id') == $estate->id ? ' estate-selected' : '';
                $bar .= EstateLogo::widget([
                    'id'       => $estate->id,
                    'options'  => ['class' => "profile-pic-img{$sel}"],
                    'link'     => ['href' => $uri . "?select-estate={$estate->id}", 'title' => $estate->name],
                    'fallback' => 'house',
                    'drawover' => $this->generate_initials($estate->name),
                ]);
            }
        }
        $bar .= "</div>"; // container
        Pjax::end();
        return $bar;
    }


    /**
     * {@inheritdoc}
     * 
     * @return string
     * 
     * @access  public
     */

    public function banner_css(): string {
        return $this->minifyCss(file_get_contents(__DIR__ . '/../css/estate-banner.css'));
    }


    /**
     * Generate the initials in upper case from a parsed estate name.
     * 
     * @param string $estate_name
     * 
     * @return string
     * 
     * @access  private
     */

    private function generate_initials(string $estate_name): string {
        $parts = explode(' ', $estate_name);
        $initials = array_map(function ($en) {
            return substr($en, 0, 1);
        }, $parts);
        return strtoupper(implode('', $initials));
    }
}
