<?php
namespace Incoviba\nuevo\Proyecto;

use Incoviba\Common\Alias\NewModel;
use Incoviba\old\Proyecto\Proyecto as P;
use Carbon\Carbon;

/**
 * 
 * @author Aldarien
 * @property int $id
 * @property Proyecto $proyecto_id
 * @property string texto
 * @property DateTime inicio
 * @property DateTime cierre
 *
 */
class Tema extends NewModel
{
	protected static $_table = 'temas';
	
	public function proyecto()
	{
		$proyecto = $this->belongsTo(Proyecto::class)->findOne();
		if ($proyecto) {
			return $proyecto;
		}
		return $this->belongsTo(P::class)->findOne();
	}
	public function inicio()
	{
		return Carbon::parse($this->inicio, config('app.timezone'));
	}
	public function cierre()
	{
		return Carbon::parse($this->cierre, config('app.timezone'));
	}
	public function texto()
	{
		$text = $this->texto;
		$text = explode("\n", $text);
		foreach ($text as &$line) {
			$line = trim(rtrim($line, '.')) . '.';
			if ($line != ltrim($line, '-')) {
				$line = '&nbsp;' . $line;
			}
		}
		$text = implode('<br />', $text);
		
		preg_match_all('/\[\[.*\]\]/', $text, $matches);
		$search = [];
		$replace = [];
		if (count($matches[0]) > 0) {
			foreach ($matches[0] as $match) {
				$search []= $match;
				list($model, $where, $value) = explode(':', str_replace(['[',']'], ['', ''], $match));
				$class = '\\Incoviba\\old\\' . $model;
				$obj = model($class)->where($where, $value)->findOne();
				
				$str = $value;
				if ($obj->venta()) {
					$str = '<a href="';
					$str .= url('', ['p' => 'ventas', 'a' => 'show', 'venta' => $obj->venta()->id]);
					$str .=  '">' . $value . '</a>';
				}
				$replace []= $str;
			}
		}
		
		$text = str_replace($search, $replace, $text);
		
		return $text;
	}
}
?>