<?php

namespace bff\modules\geo\models;

use Geo;
use bff\db\illuminate\Model;
use bff\db\illuminate\LangsColumns;
use bff\db\illuminate\casts\Separated;

/**
 * Geo: region city metro station model
 * @copyright Tamaranga
 */
class MetroStation extends Model
{
    use LangsColumns;

    protected $table = Geo::TABLE_REGIONS_METRO_STATIONS;

    public $timestamps = false;

    protected $casts = [
        'nearby' => Separated::class,
    ];

    public function langColumns()
    {
        return ['title'];
    }

    public function branches()
    {
        $in = new MetroStationIn();
        return $this->belongsToMany(MetroBranch::class, $in->getTable(), 'station_id', 'branch_id');
    }

    protected static function booted()
    {
        parent::booted();

        $parents = null;
        $inserting = false;
        static::saving(function ($self) use (&$parents, &$inserting) {
            /** @var $self static */
            $inserting = empty($self->id);
            if (isset($self->parents)) {
                $parents = $self->parents;
                unset($self->parents);
            }
        });

        static::saved(function ($self) use (&$parents, &$inserting) {
            /** @var $self static */
            if ($parents) {
                $in = new MetroStationIn();
                $insert = function ($branch) use ($self) {
                    $in = new MetroStationIn();
                    $data = [
                        'branch_id' => $branch,
                        'station_id' => $self->id,
                        'num' => (int)$in->where('branch_id', $branch)->max('num') + 1,
                    ];
                    $in->fill($data)->save();
                };
                if ($inserting) {
                    foreach ($parents as $k => $v) {
                        if (empty($v)) {
                            continue;
                        }
                        $insert($k);
                    }
                } else {
                    $exist = $in
                        ->where('station_id', $self->id)
                        ->get()
                        ->keyBy('branch_id')
                        ->toArray();

                    foreach ($parents as $k => $v) {
                        if (empty($v)) {
                            continue;
                        }
                        if (isset($exist[$k])) {
                            unset($exist[$k]);
                        } else {
                            $insert($k);
                        }
                    }
                }
                if (! empty($exist)) {
                    foreach ($exist as $v) {
                        $in->where([
                            'station_id' => $self->id,
                            'branch_id' => $v['branch_id'],
                        ])->delete();
                    }
                }
            }
        });
    }
}