<?php

namespace Garradin;

require_once __DIR__ . '/_inc.php';

$session->requireAccess('compta', Membres::DROIT_ECRITURE);

use Garradin\DB;

$cats = new Compta\Categories;
$tpl->assign('moyens_paiement', $cats->listMoyensPaiement());
$tpl->assign('moyen_paiement', f('moyen_paiement') ?: 'ES');

if (f('add'))
{
	$form->check('ajout_facture', [
		'type' => 'required|in:facture,devis',
		'numero_facture' => 'required|string',
		'date_emission' => 'required|date',
		'date_echeance' => 'required|date',
		// 'reglee' => '',
		// 'archivee' => '',
		'base_receveur' => 'required|in:membre,client',
		// 'client' => '',
		// 'membre' => '',
		'moyen_paiement' => 'required|in:' . implode(',', array_keys($cats->listMoyensPaiement())),
		'designation' => 'array|required',
		'prix' => 'array|required'
	]);

	if (!$form->hasErrors())
	{
		try
		{
			if ( count(f('designation')) !== count(f('prix')) )
			{
				throw new UserException('Nombre de désignations et de prix reçus différent.');
	    }

	    $truc = [
		    'numero' =>f('numero_facture'),
		    'date_emission' => f('date_emission'),
		    'date_echeance' => f('date_echeance'),
		    'reglee' => f('reglee') == 'on'?1:0,
		    'archivee' => f('archivee') == 'on'?1:0,
		    'moyen_paiement' => f('moyen_paiement'),
		    'toto' => 0
	    ];

	    if (f('type') == 'facture')
	    {
		    $truc['type_facture'] = 1;
	    }
	    elseif (f('type') == 'devis')
	    {
		    $truc['type_facture'] = 0;
	    }

	    foreach(f('designation') as $k=>$value)
	    {
		    $truc['contenu'][$k]['designation'] = $value;
		    $truc['contenu'][$k]['prix'] = f('prix')[$k];
		    $truc['toto'] += f('prix')[$k];
	    }
	    $truc['total'] = $truc['toto'];
	    unset($truc['toto']);

	    if (f('base_receveur') == 'client')
	    {
		    $truc['receveur_membre'] = 0;
		    $truc['receveur_id'] = f('client');
	    }
	    elseif (f('base_receveur') == 'membre')
	    {
		    $truc['receveur_membre'] = 1;
		    $truc['receveur_id'] = f('membre');
	    }

	    $id = $facture->add($truc);

	    Utils::redirect(PLUGIN_URL . 'facture.php?id='.(int)$id);

	}
	catch(UserException $e)
	{
		$form->addError($e->getMessage());
	}
    }

}


$tpl->assign('type', f('type') ?: '');
$tpl->assign('numero_facture', f('numero_facture') ?: '');
$tpl->assign('date_emission', f('date_emission') ?: '');
$tpl->assign('date_echeance', f('date_echeance') ?: '');
$tpl->assign('reglee', f('reglee') ?: 'off');
$tpl->assign('base_receveur', f('base_receveur') ?: '');
$tpl->assign('client_id', f('client') ?: -1);
$tpl->assign('membre_id', f('membre') ?: -1);
$designations = [];
$prix = [];
if (($d = f('designation')) && ($p = f('prix')))
{
	foreach($d as $k=>$v)
	{
		if ($v == '' && $p[$k] == 0)
		{
			continue;
		}
		$designations[] = $v;
		$prix[] = $p[$k];
	}
}
$tpl->assign('designations', $designations);
$tpl->assign('prix', $prix);

$tpl->assign('membres', (array)DB::getInstance()->get('SELECT id, nom FROM membres WHERE id_categorie != -2 NOT IN (SELECT id FROM membres_categories WHERE cacher = 1);'));
$tpl->assign('clients', $client->listAll());

$tpl->display(PLUGIN_ROOT . '/templates/facture_ajouter.tpl');