<?php
namespace App\Controller;

use App\Definition\Controller;
use Incoviba\old\Inmobiliaria\Inmobiliaria;
use Incoviba\old\Inmobiliaria\TipoSociedad;
use Incoviba\old\Common\Banco;

class Inmobiliarias
{
	use Controller;

	public static function list()
	{
		$inmobiliarias = model(Inmobiliaria::class)->orderByAsc('abreviacion')->findMany();
		return view('inmobiliarias.list', compact('inmobiliarias'));
	}
	public static function show()
	{
		$rut = get('rut');
		$inmobiliaria = model(Inmobiliaria::class)->findOne($rut);
		return view('inmobiliarias.show', compact('inmobiliaria'));
	}
	public static function add()
	{
		$sociedades = model(TipoSociedad::class)->findMany();
		return view('inmobiliarias.add', compact('sociedades'));
	}
	public static function agregar()
	{
		list($rut, $dv) = explode('-', str_replace('.', '', post('rut')));

		$inmobiliaria = model(Inmobiliaria::class)->findOne($rut);
		if ($inmobiliaria) {
			header('Location: ' . url('', ['p' => 'inmobiliarias', 'a' => 'show', 'rut' => $inmobiliaria->rut]));
			die();
		}

		$inmobiliaria = model(Inmobiliaria::class)->create();
		$inmobiliaria->rut = $rut;
		$inmobiliaria->dv = $dv;
		$inmobiliaria->razon = post('razon');
		$inmobiliaria->abreviacion = post('abrev');
		$inmobiliaria->sociedad = post('sociedad');

		$inmobiliaria->save();
		header('Location: ' . url('', ['p' => 'inmobiliarias', 'a' => 'show', 'rut' => $inmobiliaria->rut]));
	}
	public static function edit()
	{
		$sociedades = model(TipoSociedad::class)->findMany();
		$rut = get('rut');
		$inmobiliaria = model(Inmobiliaria::class)->findOne($rut);
		$bancos = model(Banco::class)->findMany();
		usort($bancos, function($a, $b) {
			return strcmp($a->nombre, $b->nombre);
		});
		return view('inmobiliarias.edit', compact('inmobiliaria', 'bancos', 'sociedades'));
	}
	public static function do_edit()
	{
		$rut = get('rut');
		$inmobiliaria = model(Inmobiliaria::class)->findOne($rut);
		foreach (post() as $field => $value) {
			if ($value != '' and $inmobiliaria->{$field} != $value) {
				$inmobiliaria->{$field} = $value;
			}
		}

		$inmobiliaria->save();
		header('Location: ' . nUrl('inmobiliarias', 'show', ['rut' => $inmobiliaria->rut]));
	}
}
?>
