<?php
namespace ProVM\KI;

use Carbon\Carbon;
use ProVM\Common\Implementation\Model;

class Producto extends Model {
  protected $id;
  protected $nombre;
  protected $segmento;
  protected $direccion;
  protected $valor;
  protected $bono;
  protected $rentabilidad;
  protected $cuota;
  protected $entrega;
  protected $estado;
  protected $unidades;
  protected $modelos;
  protected $tamaños;
  protected $descripcion;
  protected $publicacion;

  public function valor(float $valor = -1) {
    if ($valor == -1) {
      return $this->valor;
    }
    $this->valor = number_format($valor, 0, ',', '.');
  }
  public function tamaños(int $min = -1, int $max = -1) {
    if ($min == -1) {
      return $this->tamaños;
    }
    if ($max == -1) {
      $max = $min;
    }
    $this->tamaños = $min . ' - ' . $max . ' m²';
  }
  public function entrega(\DataTime $fecha = null) {
    if ($fecha === null) {
      return Carbon::parse(implode('-', array_reverse(explode('/', $this->entrega))) . '-01');
    }
    $this->entrega = $fecha->format('%m/%Y');
  }
  public function publicacion(\DateTime $fecha = null) {
    if ($fecha === null) {
      return Carbon::parse($this->publicacion);
    }
    $this->publicacion = implode(' ', [
      $fecha->day,
      'de',
      ucwords($fecha->locale('es')->isoFormat('MMMM')) . ',',
      $fecha->year
    ]);
  }
  protected $destacado;
  public function destacado(bool $destacado = null) {
    if ($destacado === null) {
      if ($this->destacado === null) {
        $destacados = $this->factory->get('destacados.json');
        $this->destacado = (array_search($this->id, $destacados) !== false);
      }
      return $this->destacado;
    }
    $this->destacado = $destacado;
  }
  protected $image_folder;
  public function setImageFolder(string $folder) {
    $this->image_folder = implode(DIRECTORY_SEPARATOR, [
      $folder,
      'assets',
      'images',
      mb_strtolower($this->nombre)
    ]);
  }
  protected $imagenes;
  public function imagenes() {
    if ($this->imagenes === null) {
      $folder = $this->image_folder;
      $this->imagenes = [];
      if (!file_exists($folder)) {
        return $this->imagenes;
      }
      $files = new \DirectoryIterator($folder);
      foreach ($files as $file) {
        if ($file->isDir()) {
          continue;
        }
        $this->imagenes []= $file->getFilename();
      }
      sort($this->imagenes);
    }
    return $this->imagenes;
  }
  public function addImagen($file) {
    if (!file_exists($this->image_folder)) {
      mkdir($this->image_folder);
    }
    $filename = implode(DIRECTORY_SEPARATOR, [
      $this->image_folder,
      $file->getClientFilename()
    ]);
    $file->moveTo($filename);
    if ($this->imagenes === null) {
      $this->imagenes = [];
    }
    $this->imagenes []= $file->getClientFilename();
    return file_exists($filename);
  }
  public function deleteImagen(string $file) {
    $filename = implode(DIRECTORY_SEPARATOR, [
      $this->image_folder,
      $file
    ]);
    if (!file_exists($filename)) {
      return false;
    }
    $status = unlink($filename);

    if (count(scandir($this->image_folder)) == 2) {
      rmdir($this->image_folder);
    }
    return $status;
  }
  protected $imagen;
  public function imagen() {
    if ($this->imagen === null) {
      $this->imagen = 'default.jpg';
      $img = $this->imagenes();
      if (count($img) > 0) {
        $this->imagen = $img[0];
      }
    }
    return $this->imagen;
  }
  public function map($data): Model {
    $this->id = $data->id ?? null;
    $this->nombre = $data->nombre;
    $this->segmento = $data->segmento;
    $this->direccion = new Direccion();
    $this->direccion->map($data);
    $this->valor($data->valor);
    $this->bono = $data->bono;
    $this->rentabilidad = $data->rentabilidad;
    $this->cuota = $data->cuota;
    $this->entrega = $data->entrega;
    $this->estado = $data->estado;
    $this->unidades = $data->unidades;
    $this->modelos = $data->modelos;
    $this->tamaños = $data->tamaños;
    $this->descripcion = $data->descripcion;
    $this->publicacion = $data->publicacion;
    return $this;
  }
  public function jsonSerialize() {
    $arr = [
      'id' => $this->id,
      'nombre' => $this->nombre,
      'segmento' => $this->segmento,
      'valor' => $this->valor,
      'bono' => $this->bono,
      'rentabilidad' => $this->rentabilidad,
      'cuota' => $this->cuota,
      'entrega' => $this->entrega,
      'estado' => $this->estado,
      'unidades' => $this->unidades,
      'modelos' => $this->modelos,
      'tamaños' => $this->tamaños,
      'descripcion' => $this->descripcion,
      'publicacion' => $this->publicacion
    ];
    $arr = array_merge($arr, $this->direccion->jsonSerialize());
    return $arr;
  }
  public function save() {
    $this->changeDestacado();
    return parent::save();
  }
  public function delete() {
    $filename = implode(DIRECTORY_SEPARATOR, [
      $this->factory->getFolder(),
      'destacados.json'
    ]);
    $destacados = json_decode(trim(file_get_contents($filename)));
    foreach ($destacados as $i => $id) {
      if ($id == $this->id) {
        unset($destacados[$i]);
      }
    }
    sort($destacados);
    file_put_contents($filename, json_encode($destacados));
    foreach ($this->imagenes() as $imagen) {
      $this->deleteImagen($imagen);
    }

    return parent::delete();
  }
  public function changeDestacado() {
    $filename = implode(DIRECTORY_SEPARATOR, [
      $this->factory->getFolder(),
      'destacados.json'
    ]);
    $destacados = json_decode(trim(file_get_contents($filename)));

    $changed = false;
    if (!$this->destacado()) {
      foreach ($destacados as $i => $id) {
        if ($id == $this->id) {
          unset($destacados[$i]);
          $changed = true;
          break;
        }
      }
    } else {
      $found = false;
      foreach ($destacados as $i => $id) {
        if ($id == $this->id) {
          $found = true;
          break;
        }
      }
      if (!$found) {
        $destacados []= $this->id;
        $changed = true;
      }
    }

    if ($changed) {
      sort($destacados);
      file_put_contents($filename, json_encode($destacados));
    }
  }
}
