<?php

namespace Garradin\Plugin\Facturation;

use Garradin\DB;
use Garradin\DynamicList;
use Garradin\Plugin;
use Garradin\UserException;
use Garradin\Utils;

class Client
{
	private $keys = [
		'nom',
		'adresse',
		'code_postal',
		'ville',
		'telephone',
		'email'
	];

	private $config = [
		'unique_client_name' => false,
		'validate_cp' => true
	];

	public function __construct()
	{
		$plugin = new Plugin('facturation');
		$this->config['unique_client_name'] = $plugin->getConfig('unique_client_name') ?: false;
		$this->config['validate_cp'] = $plugin->getConfig('validate_cp') ?: false;
	}

	public function _checkFields(&$data)
	{
		foreach($this->keys as $key)
		{
			if(isset($data[$key]) && is_string($data[$key]))
			{
				$data[$key] = trim($data[$key]);

				if($data[$key] == '' && ($key != 'telephone' && $key != 'email'))
				{
					throw new UserException('Le champs '.$key.' doit être renseigné.');
				}

				if($key == 'ville')
				{
					$data[$key] = strtoupper($data[$key]);
				}
				elseif ($key == 'code_postal')
				{
					if($this->config['validate_cp'] && !preg_match('/^(F-)?((2[A|B])|[0-9]{2})(\s)?[0-9]{3}$/', $data[$key]))
					{
						throw new UserException('Le code postal est erroné.');
					}
				}
				elseif ($key == "telephone")
				{
					$data[$key] = Utils::normalizePhoneNumber($data[$key]);
				}
				elseif ($key == 'email')
				{
					$data[$key] = strtolower($data[$key]);
					if ($data[$key] != '' && !filter_var($data[$key], FILTER_VALIDATE_EMAIL))
					{
						throw new UserException(sprintf('Adresse email invalide "%s".', $data[$key]));
					}
				}
			}
			elseif($key != 'telephone' && $key != 'email')
			{
				throw new UserException('Le champs '.$key.' doit être renseigné.');
			}
		}
	}


	public function add($data = [])
	{
		$db = DB::getInstance();

		$this->_checkFields($data);

		if($this->config['unique_client_name'] && isset($data['nom']) && $db->test('plugin_facturation_clients', 'nom = ? COLLATE NOCASE', $data['nom']))
		{
			throw new UserException('La valeur du champ nom est déjà utilisée, hors ce champ doit être unique à chaque client.');
		}

		$db->insert('plugin_facturation_clients', $data);
		return $db->lastInsertRowId();
	}

	public function get($id)
	{
		$db = DB::getInstance();

		return $db->first('SELECT *, strftime(\'%s\', date_creation) AS date_creation
			FROM plugin_facturation_clients WHERE id = ? LIMIT 1;', (int)$id);
	}

	public function listAll()
	{
		return DB::getInstance()->get('SELECT *, strftime(\'%s\', date_creation) AS date_creation FROM plugin_facturation_clients');
	}

	public function list(): DynamicList
	{
		$columns = [
			'id' => [
				'label' => 'Numéro',
			],
			'nom' => [
				'label' => 'Nom',
			],
			'adresse' => [
				'label' => 'Adresse',
			],
			'code_postal' => [
				'label' => 'Code postal',
			],
			'ville' => [
				'label' => 'Ville',
			],
			'telephone' => [
				'label' => 'Téléphone',
			],
			'email' => [
				'label' => 'E-Mail',
			],
			'nb_documents' => [
				'label' => 'Nombre de documents',
				'select' => '(SELECT COUNT(*) FROM plugin_facturation_factures WHERE receveur_id = c.id)',
			],
		];

		$tables = 'plugin_facturation_clients AS c';

		$list = new DynamicList($columns, $tables);
		$list->orderBy('id', false);
		$list->setPageSize(1000);
		return $list;
	}

	public function edit($id, $data = [])
	{
		$db = DB::getInstance();

		$this->_checkFields($data);

		if($this->config['unique_client_name'] && isset($data['nom']) && $db->test('plugin_facturation_clients', 'nom = ? COLLATE NOCASE AND id != ?', $data['nom'], (int)$id))
		{
			throw new UserException('La valeur du champ nom est déjà utilisée, hors ce champ doit être unique à chaque client.');
		}

		return $db->update('plugin_facturation_clients', $data, $db->where('id', (int)$id));
	}

	public function isDeletable($id): bool
	{
		$f = new Facture;
		return !$f->hasDocs(0, $id);
	}

	public function delete($id)
	{
		if(!$this->isDeletable($id))
		{
			return false;
		}

		return DB::getInstance()->delete('plugin_facturation_clients', 'id = '. (int)$id);
	}
}