<?php

/*  Copyright 2014-2015 Scott Paterson

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

/*
Autor: asanch92
shortcode: [c2em_update_num_ordre form_name="inscripciov2"]
Mostrar el contingut del què s'ha enviat pel formulari form_name, que haurà de tenir el camp "comprovar_tresorer" 
i que es mostrarà en formar de checkbox. Es podra actualitzar aquest camp
Actualiza el camp comprovar_tresorer dels enviaments que s'han en un formulari amb aquesta camp inclos en ell. 
S'ha de posar el shortcode [c2em_update_num_ordre form_name="inscripcio"] en una pagina per veure el contingut. Només hi podrà accedir amb permisos d'administrador
*/
include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
if ( is_plugin_active( 'contact-form-7-to-database-extension/contact-form-7-db.php' ) ) {

	add_shortcode( 'c2em_update_num_ordre', 'c2em_veure_num_ordre_html' ); 

	function c2em_veure_num_ordre_html($atts) {
		$content="";
		//Si l'usuari no es administrador, sortim
		if (!current_user_can('update_core')){
			$content="Has de tenir permisos d'administrador per veure aquesta pàgina. ";
			 return $content;
		}
		//Recuparem l'atribut del shortcode
		$var = shortcode_atts( array(
		    'form_name' => 'nom formulari',
		), $atts );

		//Recupareme el nom de la taula que crea CF7DB
		require_once (ABSPATH . '/wp-content/plugins/contact-form-7-to-database-extension/CF7DBPlugin.php');
		$plugin = new CF7DBPlugin;
		$tableName = $plugin->getSubmitsTableName();
		//Si s'ha enviat el formulari
		if (isset($_POST['cfdbc2emupdate']) &&
                    wp_verify_nonce($_REQUEST['_wpnonce'])) {
			
			global $wpdb;
			foreach ($_POST as $name => $value) { // busquem els checkboxes, 
				if ($value == 'initUncheck') {
                 	update_confirmacio('1', $name, $var, $tableName);
                }
				if ($value == 'initCheckHidden') {
                 	update_confirmacio('-1', $name, $var, $tableName);
                 }
			}
		}
	 
		
		
 		
		//contingut a mostrar en forma de taula html
		$content=c2em_show_form_sended($var, $tableName);
		
		return $content ;
	}	
	
	function update_confirmacio( $confirmacio, $name, $var, $tableName){
		// Dots and spaces in variable names are converted to underscores. For example <input name="a.b" /> becomes $_REQUEST["a_b"].
		// http://www.php.net/manual/en/language.variables.external.php
		// We are expecting a time value like '1300728460.6626' but will instead get '1300728460_6626'
		// so we need to put the '.' back in before going to the DB.
		global $wpdb;
		$name = str_replace('_', '.', $name);
		$wpdb->update($tableName, 
						array( 
							'field_value' => $confirmacio	// string
						), 
						array( 'form_name' => $var['form_name'] ,
								'field_name' => 'comprovar_tresorer',
								'submit_time' =>$name),
						array( 
							'%s'	// value1
						), 
						array( '%b', '%s', '%f' ) 
					);
	}
	//contingut a mostrar en forma de taula html
	function c2em_show_form_sended($var, $tableName){
		global $wpdb;
		//recuparem les files que te la taula (una per enviament, segons els submit_time)
		$submit_times = $wpdb->get_results( 
							$wpdb->prepare("select DISTINCT `submit_time` from `$tableName` where `form_name` = '%s' ORDER BY  `submit_time` DESC", $var['form_name']),
						ARRAY_N);	
		//Camps del formulari
		$field_names =$wpdb->get_results( 
							$wpdb->prepare("select DISTINCT `field_name` from `$tableName` where `form_name` = '%s' ORDER BY `field_order`", $var['form_name']),
						ARRAY_N);	
		if ( $submit_times && $field_names) {
			$content="<form action=".$_SERVER['REQUEST_URI']." method='post'> ";
			$content.=wp_nonce_field();
			$content.="<input name='cfdbc2emupdate' type='hidden' value='rows'/>
						<table id='taula'>
						<tbody>		
						<tr>";
			foreach ( $field_names as $field_name ){
				//no mostrem les dues ultimes columnes
				if($field_name[0]=="Submitted Login" || $field_name[0] == "Submitted From"){
					continue;
				}
				$content.="<th>". $field_name[0] ."</th>";			
			}
			$content.="</tr>";
		
			foreach ( $submit_times as $submit_time ){
				$content.="<tr>";
				$rows = $wpdb->get_results( 
							$wpdb->prepare("select `field_name`, `field_value` from `$tableName` 
										where `form_name` = '%s' and `submit_time` = %F ORDER BY `field_order`", 
										$var['form_name'], $submit_time[0]),ARRAY_N);
				if ( $rows ) {
					foreach ( $rows as $row ){
						if($row[0]=="Submitted Login" || $row[0] == "Submitted From"){
							continue;
						}
						/*Fem un checkbox amagat per controlar els que marquem i desmarquem i s'enviin tots*/
						if($row[0]=="comprovar_tresorer"){
							$content.="<td>";
							if($row[1]!='1'){
								//$content.="<input type='checkbox' id='hidden".$submit_time[0]."' value='checkhidden' checked='checked' style='display: none;'>";
								$content.="<input type='checkbox' name='".$submit_time[0]."' id='".$submit_time[0]."' value='initUncheck'>";
							}
							else{
								$content.="<input type='checkbox' name='".$submit_time[0]."' id='".$submit_time[0]."' value='initCheckHidden' style='display: none;' >";
								$content.="<input type='checkbox' name='initCheck' value='initCheck' checked='checked' >";
							}		
											
							$content.="</td>";
							
						}
						else{
							$content.="<td>".$row[1]."</td>";			
						}
					}
				}
				$content.="</tr>";
			}
		
		
			$content.="</tbody></table><br>
			
			<input type='submit' value='Actualitzar' id='actualitzar' name='cfdbc2emupdate' style='display: none;'>
			<br>
			</form>";
//<a	 href='' ><button  type='button' id='actualitzar' name='cfdbc2emupdate' onclick='this.form.submit()' disabled>Actualitza</button></a>
//<a	name='cfdbc2emupdate' onclick='this.form.submit()' id='actualitzar' href='' disabled >Actualitza</a>
			//Afegim les funcions jQuery que modificara-la taula, aconsegueixo posaro en el header pero no respon
			//add_action( 'wp_enqueue_scripts', 'add_my_script' );
			$content.="<script type='text/javascript' language='Javascript'>
                jQuery(document).ready(function() {
            		jQuery(':checkbox').click(function(){
						if(jQuery(this).attr('name')=='initCheck'){
							jQuery(this).prev().prop('checked', !jQuery(this).is( ':checked'));
						}
						jQuery('#actualitzar').show();
					});
                });

            </script>";

		}

		return $content;
	}
	
}
