<?php

function donation_menu() {
	$items = array();
	$items['admin/donations'] = array(
		'title' => 'Donations',
		'page callback' => 'drupal_get_form',
		'page arguments' => array('donation_form'),
		'type' => MENU_CALLBACK,
		'access arguments' => array('administer users'),		
		'access callback' => TRUE,    
	);
	
  return $items;
}


function donation_form($form, &$form_state){
$form['#method'] = 'get';
	$form['start_date'] = array(
		'#type' => 'date',
		'#title' => 'Start Date',		
		'#required' => TRUE,
		'#value' => $_GET['start_date'],
    );
	$form['end_date'] = array(
		'#type' => 'date', 
		'#title' => 'End Date',		
		'#required' => TRUE,
		'#value' => $_GET['end_date'],
    );
	
	 $form['submit_button'] = array(
            '#type' => 'submit',
            '#value' => t('Export')
    ); 
	
	$form['html'] = array(
            '#type' => 'markup',
            '#markup' => 'OR '
    ); 
	
	$form['submit_button1'] = array(
            '#type' => 'submit',
            '#value' => t('Filter'),
			'#name' => t('op1')
    );
	
	$op = isset($_GET['op']) ? $_GET['op'] : null;
	$op1 = isset($_GET['op1']) ? $_GET['op1'] : null;
	
	 $sort = 'DESC';
		  $order = 'da.id';
	if($op=='Export'){
		$start_date = strtotime($_GET['start_date']['day']."-".$_GET['start_date']['month']."-".$_GET['start_date']['year']);
		$end_date 	= strtotime($_GET['end_date']['day']."-".$_GET['end_date']['month']."-".$_GET['end_date']['year']." 23:59:59");		
		if($start_date >= $end_date){
			form_set_error('start_date', t('Start date should not be greater than end date.'));
		}else{
			export_data($start_date,$end_date);
		}
	}
	if($op1=='Filter'){
		$start_date1 = strtotime($_GET['start_date']['day']."-".$_GET['start_date']['month']."-".$_GET['start_date']['year']);
		$end_date1 	= strtotime($_GET['end_date']['day']."-".$_GET['end_date']['month']."-".$_GET['end_date']['year']." 23:59:59");		
	
	}
	/*
	*  Filter Process End
	*/

	$output = "";
// Select table
  $query = db_select("donations	", "da");
  $query->fields("da", array('id','existing_sponsor','sponsor_id','frequency_of_donation','title','gender','first_name','last_name','email','phone_no','address','country','pincode','state','city','date_of_birth','pan','citizenship','claiming_tax_exemption','newsletter', 'donate_id', 'donate_title', 'donate_option_id', 'donate_option_title', 'currency', 'amount', 'auth_status', 'status_reason', 'payment_return_date', 'child_num', 'supportyear', 'donateotheroption', 'created'));
	if(!empty($start_date1)){
	
		$query->condition('created', $start_date1,'>');
	}
	if(!empty($end_date1)){
		$query->condition('created', $end_date1,'<');
	}
  $query->orderBy($order, $sort);
  // For pagination
  $limit = 10;
  $query = $query->extend('TableSort')->extend('PagerDefault')->limit($limit);
// Execute query

  $result = $query->execute();
 //echo $query->__toString() . "\n";
 
 
// Prepare table header
  //$header = array('SN','Addon',  'price(Rs)','operations');
  $header = array(
		  array(
			"data" => t('SN'),
		  ),
		   
		  array(
			"data" => t('Name'),			
		  ),
		  array(
			"data" => t('Email'),			
		  ),
		   array(
			"data" => t('Citizenship'),			
		  ),
		 array(
			"data" => t('Donation'),			
		 ),
		 array(
			"data" => t('For Donation'),			
		  ),
		  array(
			"data" => t('Donation date'),			
		  ),
		  array(
			"data" => t('Donation Details'),			
		  )
		);
  

$rows = array();
  
$i=1;
if(isset($_GET['page'])){
  $i = ($_GET['page']*$limit)+$i;
}
// Looping for filling the table row

  while($data = $result->fetchObject()){
	 
   
    // Fill the table rows
    $rows[] = array(
		$i,
		$data->first_name . ' ' . $data->last_name,
		$data->email,		
		$data->citizenship,
		$data->donate_title,
		$data->donate_option_title,
		date("d F, Y", $data->created),
		'<b>Auth Status:</b> ' . $data->auth_status . "<br/>" .
		'<b>Status Reason:</b> ' . $data->status_reason . "<br/>" .
		'<b>Payment Return Date:</b> ' . $data->payment_return_date . "<br/>" .
		'<b>Amount:</b> ' . $data->amount . "<br/>" .
		'<b>Currency:</b> ' . $data->currency		
      	
    );
$i++;
}


// Output of table with the paging
  $output = theme_table(
    array(
      "header" =>$header,
      "rows" => $rows,
      "attributes" => array(),
      "sticky" => true, // Table header will be sticky
      "caption" => "",
      "colgroups" => array(),
      "empty" => t("Table has no row!") // The message to be displayed if table is empty
    )
  ).theme("pager");
  
   //$render = (drupal_get_form('payments_export_form'));
   // return drupal_render($render) . $output;
    //print drupal_render(drupal_get_form('request_quote_export_form'));
	$form_state['result'] = $output; 
	//$form_state['result'] = donation_callback();
	
	// return drupal_render($form) . donation_callback();
	$form['result'] = array(
		'#type'=>'item',
		'#markup'=>$output,
		); 
	return $form;
	
	
	
}

 function donation_form_submit($form, &$form_state){		
	//print_r($form_state);	
	//print_r($_GET);	
    $form_state['rebuild']  = TRUE;
}


function export_data($start_date, $end_date){
	$query  = db_select("donations", "da");
    $query->fields("da", array(
        'id',
        'first_name',
        'last_name',
        'email',
		'frequency_of_donation',
        'citizenship',
        'donate_title',
        'donate_option_title',
        'currency',
        'amount',
        'created',
        'auth_status',
        'status_reason',
        'payment_return_date'
    ))
	->condition('created', $start_date,'>')
	->condition('created', $end_date,'<');
	$query->orderBy("da.id", "DESC");
	
	$result = $query->execute();	
	$rows = $result->fetchAll();
	//echo $query->__toString() . "\n";
	//die($start_date."|".$end_date);
	#print_r($rows);
	//exit;

	$ctr = 0;
	if ($rows) {
		$str = "Name\tEmail\tFrequency of Donation\tCitizenship\tDonation Title\tDonation Option Title\tCurrency\tAmount\tDonation Date\tAuth Status\tReason\tPayment Return Date\t\n";
		foreach ($rows as $row):			
			if($row->auth_status==300){
			$status = "Success";
			}else if($row->auth_status==''){
			$status = "Incomplete";
			}else{
			$status = "Fail";
			}
			$str .= clear_string($row->first_name)." ".clear_string($row->last_name) . "\t " . clear_string($row->email) . "\t " . clear_string($row->frequency_of_donation) . "\t" . clear_string($row->citizenship) . "\t" . clear_string($row->donate_title). "\t" . clear_string($row->donate_option_title). "\t" . clear_string($row->currency). "\t" . $row->amount ."\t" . date('d F, Y', $row->created) ."\t" . $status ."\t" . $row->status_reason ."\t" . $row->payment_return_date . "\t\n";
		endforeach;
		
		header("Pragma: public");
		header("Expires: 0");
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		header("Content-Type: application/force-download");
		header("Content-Type: application/octet-stream");
		header("Content-Type: application/download");
		header("Content-type: application/ms-excel");
		header("Content-Disposition: attachment; filename=online-payments.xls"); 
		header("Content-Transfer-Encoding: binary ");		
		echo $str;
		die;
	}else{
		drupal_set_message("No Records Found.",'error');
	}
}

function clear_string($str) {
    if ($str) {
        $str = trim(preg_replace('/\s\s+/', ' ', str_replace(array("\n", "\r"), " ", $str)));
        return $str;
    } else {
        return ' ';
    }
}