<?php
require_once 'vendor/autoload.php';

	session_start();
	$userid = $_SESSION['uid'];
	openlog('ACCRED', LOG_PID, LOG_LOCAL0);
        // Should we preload with data ?
        $aid = $_GET['aid'];
        $isAdmin = $_SESSION['admin']==1;

	$isEditable = $_SESSION['allowedit']==1;
	if(!$userid) {
		syslog(LOG_ERR, "Unauthorized access to form page aid:$aid from : {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})");
		header('Location: accred_list');
		die();
	}
	if(!$isAdmin && $isEditable!=1) {
                syslog(LOG_ERR, "Unauthorized access to form page aid by non editable user :$aid from : {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})");
                header('Location: accred_list');
                die();
        }


	$uname = $_SESSION['name'];
	if($_POST['btncancel']) {
		header('Location: accred_list');
		die();
	}
	$prices = array( 
		'mer' => array('nor' => 60, 'vip' => 42, 'label' => 'Mercredi 7 juin'),
                'jeu' => array('nor' => 60, 'vip' => 42, 'label' => 'Jeudi 8 juin'),
                'ven' => array('nor' => 60, 'vip' => 42, 'label' => 'Vendredi 9 juin'),
                'sam' => array('nor' => 60, 'vip' => 42, 'label' => 'Samedi 10 juin'),
                'dim' => array('nor' => 40, 'vip' => 42, 'label' => 'Dimanche 11 juin')

	);
?>
<!doctype html>

<html>

    <head>

        <meta charset="utf-8">
<meta name="google-signin-client_id" content="538635499162-g21v86gk87qm863u03er6vnm3q15bl82.apps.googleusercontent.com">
<script src="https://apis.google.com/js/platform.js" async defer></script>

        <title>Nouvelle Demande / Edition de demande</title>

        <!-- load Zebra_Form's stylesheet file -->
	<link rel="stylesheet" href="./vendor/stefangabos/zebra_form/examples/public/css/reset.css">
	<link rel="stylesheet" href="./vendor/stefangabos/zebra_form/examples/public/css/style.css">
        <link rel="stylesheet" href="vendor/stefangabos/zebra_form/public/css/zebra_form.css">
       <link rel="stylesheet" type="text/css" href="accred_style.css">

    </head>

    <body>
<div class="right-blob">Bienvenue <?php echo $uname; ?></div>
<?php
 echo (isset($zf_error) ? $zf_error : (isset($error) ? $error : ''));
?>
<?php

// include the Zebra_Form class
require 'vendor/stefangabos/zebra_form/Zebra_Form.php';




$mysqli = new mysqli("localhost", "caribanaaccred", "welcome99", "caribanaaccred");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}


function show_results() {
global $redis;
global $mysqli;
global $aid;
global $userid;
global $isAdmin;
global $uname;

$username = $_SESSION['name'];
$status = '1';
$updateStatus = false;
if($_POST['btndelete']) {
	$query = "DELETE FROM submissions WHERE id=$aid";
	if(!$isAdmin) {
		$query .= " AND uid=$userid";
	}
	syslog(LOG_INFO, "Delete entry for aid:$aid by uid: $userid / $uname from: {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})");
	if (!$mysqli->query($query) ) {
    	echo "Unable to delete entry: (" . $mysqli->errno . ") " . $mysqli->error;
    	die("Argh");
}

}
if($_POST['btnfinalise']) {
	$status = '0';
	$updateStatus = true;
}
if($_POST['btnunfinalise']) {
        $status = '1';
        $updateStatus = true;
}
if($_POST['btnprocess'] && $isAdmin) {
        $status = '3';
        $updateStatus = true;
}
// Escape string, mostly in case of quotes
$d = $mysqli->real_escape_string(serialize($_POST));
if(!$aid) {
	$query = "INSERT INTO submissions (uid, status, name, created, formdata,modified) values('$userid',$status,'$username',null,'".$d."',NOW())";
        syslog(LOG_INFO, "Create entry by uid: $userid / $uname from: {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})");

}
else {
	$query = "UPDATE submissions set modifieduid=$userid,formdata='".$d."'";
	if($updateStatus) {
		$query .= ",status=$status ";
	}
	$query .= " WHERE id=$aid";
	if(!$isAdmin) {
		$query .= " AND uid=$userid";
	}
	syslog(LOG_INFO, "Update entry aid:$aid by uid: $userid / $uname from: {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})");
	$logquery = "INSERT INTO log (uid,aid,name,isadmin,operation,new,prev) SELECT '$userid',$aid,'$username', $isAdmin, 'update','".$d."', formdata FROM submissions WHERE ID=$aid";
}
$mysqli->query($logquery); 
if (!$mysqli->query($query) ) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
    die("Argh");
}

header('Location: accred_list');
die();
}

   // When editing an existing form, load data
   if($aid) {
	$query = "SELECT * from submissions WHERE ID=$aid";
	if(!$isAdmin) {
		$query .= " AND UID=$userid";
	}
	if (!$result = $mysqli->query($query) ) {
    		echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
    		die("Argh");
	}

	$row = $result->fetch_assoc(); 
	if(!$row) {
		syslog(LOG_ERR, "Failed to load entry aid:$aid by uid: $userid / $uname from: {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})");	
		header("location: accred_list");
		die();
	}
	syslog(LOG_INFO, "Load entry aid:$aid by uid: $userid / $uname from: {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})");
	$ar = unserialize($row['formdata']);
	// Return to list if we are not admin and trying to edit a finalised form. Shame on us
        if(!$isAdmin && $row['status']!=1) {
		header("location: accred_list");
		die();
	}
   }
   // instantiate a Zebra_Form object
    $form = new Zebra_Form('form');


    if(!$aid) {
	$ti = "Nouvelle commande";
    }
    else {
	$ti = 'Commande par '.$_SESSION['name'] . ', créée le '.$row['created'];
    }
    $form->add('label', 'label_titre','',$ti);
    $form->add('label', 'label_salutation', 'salutation', 'Salutation:');
    $obj = $form->add('select', 'salutation', $ar['salutation']);
    $obj->add_options(array(
        'Madame' => 'Madame',
        'Monsieur' => 'Monsieur',
    ));
    $obj->set_rule(array(
        'required' => array('error', 'La salutation est obligatoire!')
    ));


    // the label for the "name" element

    $form->add('label', 'label_name', 'nom', 'Nom:');

    // add the "name" element
    $obj = $form->add('text', 'nom', $ar['nom']);

    // set rules
    $obj->set_rule(array(

        // error messages will be sent to a variable called "error", usable in custom templates
        'required' => array('error', 'Le champ Nom est obligatoire!')

    ));

    // the label for the "name" element
    
    $form->add('label', 'label_prenom', 'prenom', 'Prenom:');

    // add the "name" element
    $obj = $form->add('text', 'prenom', $ar['prenom']);

    // set rules
    $obj->set_rule(array(

        // error messages will be sent to a variable called "error", usable in custom templates
        'required' => array('error', 'Le champ Prénom est obligatoire!')

    ));


    $form->add('label', 'label_soc', 'societe', 'Société:');

    // add the "name" element
    $obj = $form->add('text', 'societe', $ar['societe']);

    // set rules
    $obj->set_rule(array(

        // error messages will be sent to a variable called "error", usable in custom templates
        'required' => array('error', 'Le champ Société est obligatoire!')

    ));


    // "email"
    $form->add('label', 'label_email', 'email', 'Adresse e-mail:');
    $obj = $form->add('text', 'email', $ar['email']);
    $obj->set_rule(array(
        'required'  =>  array('error', 'Adresse email est obligatoire!'),
        'email'     =>  array('error', "L'adresse e-mail n'a pas l'air correcte..."),
    ));

    $obj = $form->add('select', 'nature_prest', $ar['nature_prest']);
    $obj->add_options(array(
        'Concours' => 'Concours',
        'Contrat Partenaires' => 'Contrat Partenaire',
  	'Echange Festival' => 'Echange Festival',
	'Autre' => 'Autre'
    ));
    $obj->set_rule(array(
        'required' => array('error', 'La nature de la prestation est obligatoire!')
    ));

    $obj = $form->add('select', 'presta_concours', $ar['presta_concours']);
    $obj->add_options(array(
        'Concours Caribana' => 'Concours Caribana',
        'Concours Médias' => 'Concours médias',
        'Autre' => 'Autre'
    ));
    $obj->set_rule(array(
        'required' => array('error', 'La type de concours  est obligatoire!'),
        'dependencies'   =>  array(array(
            'nature_prest' =>  'Concours',
        ), 'mycallback, 1'),

    ));

    $form->add('label', 'label_why', 'why', 'Précisions');
    $obj = $form->add('textarea', 'why',$ar['why']);
    $obj->set_rule(array(
        'required'  =>  array('error', 'Merci de préciser la nature de la prestation!'),
    ));
 // "digits"
    $form->add('label', 'label_nor_tot', 'nor_tot', 'Total nombre entrées:');
    $obj = $form->add('text', 'nor_tot',$ar['nor_tot'],array('readonly' => 'readonly', 'size' => '5'));
    $obj->set_attributes(array('class'=>'num'), false);
    $form->add('label', 'label_vip_tot', 'vip_tot', 'Total accès VIP:');
    $obj = $form->add('text', 'vip_tot',$ar['vip_tot'],array('readonly' => 'readonly', 'size' => '5'));
    $obj->set_attributes(array('class'=>'num'), false);
    $form->add('label', 'label_presta_tot', 'presta_tot', 'Total Prestations CHF:');
    $obj = $form->add('text', 'presta_tot',$ar['presta_tot'],array('readonly' => 'readonly', 'size' => '5'));
    $obj->set_attributes(array('class'=>'num'), false);

    $days = array('mer','jeu','ven','sam','dim');
    foreach($days as $one) {
	$form->add('label', 'label_digits', $one.'_nor', 'Digits:');
    	$obj = $form->add('text', $one.'_nor', $ar[$one.'_nor']);
    	$obj->set_rule(array(
        	'digits'    => array('', 'error', 'Accepts only digits (0 to 9)')
    	));
    	$obj->set_attributes(array('class'=>'num_nor num_prest num'), false);
    	$form->add('note', 'note_digits', $one.'_nor', 'Accepts only digits (0 to 9)');

       	$form->add('label', 'label_digits', $one.'_vip', 'Digits:');
        $obj = $form->add('text', $one.'_vip', $ar[$one.'_vip']);
        $obj->set_rule(array(
                'digits'    => array('', 'error', 'Accepts only digits (0 to 9)')
        ));
    	$obj->set_attributes(array('class'=>'num_vip num_prest num'), false);
        $form->add('note', 'note_digits', $one.'_vip', 'Accepts only digits (0 to 9)');

    }

     
    // VIP gratuit ?
    $form->add('label', 'label_vip_gratuit', 'vip_gratuit', 'Gratuité des billets VIP:');
    $obj = $form->add('checkbox', 'vip_gratuit', 'oui' );
    if($ar['vip_gratuit']=='oui') {
	$obj->set_attributes(array('checked'=>'checked'));
    }
    // Paiement
    $form->add('label', 'label_type_paiement', 'type_paiement', 'Type de paiement:');
    $obj = $form->add('select', 'type_paiement', $ar['type_paiement']);
    $obj->add_options(array(
        'Offert' => 'Offert',
        'Payant' => 'Payant',
    ));
    $obj->set_rule(array(
        'required' => array('error', 'Veuillez choisir un type de paiement')
    ));

    $form->add('label', 'label_choix_paiement_payant', 'choix_paiement_payant', 'Choix de paiement:');
    $obj = $form->add('select', 'choix_paiement_payant', $ar['choix_paiement_payant']);

    $obj->add_options(array(
        'Cash' => 'Cash aux accréditations',
        'Autre' => 'Autre'
    ));
    $obj->set_rule(array(
        'required' => array('error', 'Le choix de paiement payant est obligatoire!'),
        'dependencies'   =>  array(array(
            'type_paiement' =>  'Payant',
        ), 'mycallback, 3'),

    ));

    $form->add('label', 'label_paiement_autre', 'paiement_autre', 'Autre');
    $obj = $form->add('textarea', 'paiement_autre', $ar['paiement_autre']);
    $obj->set_rule(array(
        'required'  =>  array('error', 'Merci de préciser la nature du paiement!'),
       'dependencies'   =>  array(array(
            'choix_paiement_payant' =>  'Autre',
        ), 'mycallback, 4'),
    ));

   // Distribution
    $form->add('label', 'label_distribution', 'distribution', 'Distribution:');
    $obj = $form->add('select', 'distribution', $ar['distribution']);
    $obj->add_options(array(
        'Accreditations' => 'Retirer aux accréditations',
        'Poste' => 'Envoyer par la poste',
    ));
    $obj->set_rule(array(
        'required' => array('error', 'Veuillez choisir un mode de distributions')
    ));

    $form->add('label', 'label_adresse_distrib', 'adresse_distrib', 'Adresse de distribution');
    $obj = $form->add('textarea', 'adresse_distrib', $ar['adresse_distrib']);
    $obj->set_rule(array(
        'required'  =>  array('error', 'Merci de fournir une adresse de distribution'),
       'dependencies'   =>  array(array(
            'distribution' =>  'Poste',
        ), 'mycallback, 5'),
    ));

/*
    // "department"
    $form->add('label', 'label_department', 'department', 'Department:');
    $obj = $form->add('select', 'department', '', array('other' => true));
    $obj->add_options(array(
        'Marketing',
        'Operations',
        'Customer Service',
        'Human Resources',
        'Sales Department',
        'Accounting Department',
        'Legal Department',
    ));
    $obj->set_rule(array(
        'required' => array('error', 'Department is required!')
    ));

    // "room"
    $form->add('label', 'label_room', 'room', 'Which room would you like to reserve:');
    $obj = $form->add('radios', 'room', array(
        'A' =>  'Room A',
        'B' =>  'Room B',
        'C' =>  'Room C',
    ));
    $obj->set_rule(array(
        'required' => array('error', 'Room selection is required!')
    ));

    // "extra"
    $form->add('label', 'label_extra', 'extra', 'Extra requirements:');
    $obj = $form->add('checkboxes', 'extra[]', array(
        'flipchard'     =>  'Flipchard and pens',
        'plasma'        =>  'Plasma TV screen',
        'beverages'     =>  'Coffee, tea and mineral water',
    ));

    // "date"
    $form->add('label', 'label_date', 'date', 'Reservation date');
    $date = $form->add('date', 'date');
    $date->set_rule(array(
        'required'      =>  array('error', 'Date is required!'),
        'date'          =>  array('error', 'Date is invalid!'),
    ));

    // date format
    // don't forget to use $date->get_date() if the form is valid to get the date in YYYY-MM-DD format ready to be used
    // in a database or with PHP's strtotime function!
    $date->format('M d, Y');

    // selectable dates are starting with the current day
    $date->direction(1);

    $form->add('note', 'note_date', 'date', 'Date format is M d, Y');
*/
    // "submit"
    $form->add('submit', 'btnsubmit', 'Enregistrer');
    if($row['status']==1) {
    	$form->add('submit', 'btnfinalise', 'Enregistrer et Finaliser');
    }
    if($row['status']==0 && $isAdmin) {
        $form->add('submit', 'btnprocess', 'Marquer comme traité');
    }

    // Admins can un-finalise
    if($isAdmin && $row['status']==0 && $aid) {
	    $form->add('submit', 'btnunfinalise', 'Enregistrer et rendre éditable');
    }
    // $form->add('submit', 'btncancel', 'Annuler');
    $form->add('button', 'btncancel', 'Annuler', 'button', array('onClick' => 'self.location="accred_list"'));
    // Only show Delete if existing entry is edited
    if($aid) {
    	$form->add('submit','btndelete','Supprimer');
	// $form->add('button','btndelete','Supprimer','submit');
    }

    // if the form is valid
    if ($form->validate()) {
        // show results
        show_results();

    // otherwise
    } else
        // generate output using a custom template
        // $form->render('*horizontal');
	$form->render('custom-template.php');
?>
        <!-- we're loading the JavaScript files at the bottom of the page so we don't delay page rendering -->

        <!-- try to load jQuery from CDN server and fallback to local source if not available -->
        <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script  type="text/javascript" >window.jQuery || document.write('<script src="path/to/jquery-1.9.1.min.js"><\/script>')</script>


        <!-- load Zebra_Form's JavaScript file -->
        <script type="text/javascript"  src="vendor/stefangabos/zebra_form/public/javascript/zebra_form.js"></script>
	<script type="text/javascript">


    var mycallback = function(value, segment) {
        $segment = $('.optional' + segment);
        if (value) $segment.show();
        else $segment.hide();
    }

$(document).ready(function(){ 

var $form = $('#form'),
    $summands = $('.num_prest');
    var $sumDisplay = null,
    $summandsNor = $form.find('.num_nor'),
    $summandsVip = $form.find('.num_vip'),

    $sumDisplayNor = $('#nor_tot');
    $sumDisplayVip = $('#vip_tot');
    $vip_gratuit = $('#vip_gratuit_oui');

    function recalc() {
        var grat = $vip_gratuit.prop('checked');
	var cntNor=0,cntVip=0;
	var sumNor = 0;
	var sumVip = 0;
    var sum = 0, price=0;
    $summands.each(function ()
    {   
        var value = Number($(this).val());
	if($(this).hasClass('num_nor')) {
		if (!isNaN(value)) {
			price = Number($(this).parent().parent().find('.prixnor').html().substring(4));
			cntNor += value;
			sumNor += price*value;
		}
	} else if($(this).hasClass('num_vip')) {
                if (!isNaN(value)) {
			price = Number($(this).parent().parent().find('.prixvip').html().substring(4));
			cntVip += value;
			sumVip += price*value;
		}
        }
    });
    $sumDisplayNor.val(cntNor);
    $sumDisplayVip.val(cntVip);

    $amntDisplay = $('#presta_tot');
    var value = sumNor; 

    if(grat==false) {
       value += sumVip;
    }
    $amntDisplay.val(value);

  }

$form.delegate('#vip_gratuit_oui', 'change', recalc );
$form.delegate('.num_prest', 'change', recalc); 
});
</script>
    </body>

</html>

