<?php

class DHVCForm_Export_Form_Entries 
{
    public function __construct()
    {
        add_action('admin_init', array( $this, 'export_form_entries'));
    }
    
    public function export_form_entries()
    {
        if ( isset( $_GET['action'], $_GET['nonce'] ) && wp_verify_nonce( wp_unslash( $_GET['nonce'] ), 'dhvc-export-form-entries' ) && 'dhvc-export-form-entries' === wp_unslash( $_GET['action'] ) ) {
            if(!class_exists('DHVCFormQuery')){
                require_once (DHVC_FORM_DIR.'/includes/db.php');
            }
            if(!function_exists('dhvc_form_is_xhr')){
                require_once (DHVC_FORM_DIR.'/includes/functions.php') ;
            }
            $this->export();
        }
        return;
    }
    
    protected function export() 
    {
        global $dhvcform_db;
        
        $form_id = addslashes($_GET['form_id']);
        
        $form = get_post($form_id);
        
        if (empty($form))
        {
            wp_die("No submissions to export");
            exit;
        }
        
        $file_name= $this->get_filename($form);
        
        $this->send_headers($file_name);
        
        //Prepare data that will be exported.
        $form_control = get_post_meta($form->ID,'_form_control',true);
        if($form_control){
           $form_control_arr = $form_control;
            $entries = $dhvcform_db->get_entries($form->ID,'submitted','desc',0);
            $export_data_rows = array();
            $export_data_headers = array();
            $i=0;
            foreach ($entries as $i=>$entry){
                $entry_data = (array) maybe_unserialize($entry->entry_data);
                $j=0;
                $data_row=array();
                foreach ($form_control_arr as $control){
                    $control_name = $control['control_name'];
                    
                    if ($control_name !='' && !in_array($control['tag'], dhvc_form_ignore_fields())){
                        
                        $control_label = !empty($control['control_label']) ? $control['control_label'] : $control_name;
                        
                        if(!in_array($control_label, $export_data_headers)){
                            $export_data_headers[] = $control_label;
                        }
                        
                        if(isset($entry_data[$control_name])){
                            if('dhvc_form_file'== $control['tag']){
                                $file_data = $entry_data[$control_name];
                                $data_row[$j] = isset($file_data['file_name']) ? $file_data['file_name'] : '';
                            }else{
                                $data_row[$j] = is_array($entry_data[$control_name]) ? implode(', ', $entry_data[$control_name]) : $entry_data[$control_name];
                            }
                        }else{
                            $data_row[$j] = '';
                        }
                        $j++;
                    }
                }
                array_unshift($data_row,$entry->form_url,mysql2date( 'd M Y (H:i)',$entry->submitted,true ));
                $export_data_rows[$i] = $data_row;
                $i++;
            }
            
            array_unshift($export_data_headers, __('Form URL', 'dhvc-form'),__('Submitted', 'dhvc-form'));
            array_unshift($export_data_rows, $export_data_headers);
            $export_data = $export_data_rows;
            //Write csv data
            ob_start();
            $buffer = fopen("php://output", 'w');
            foreach($export_data as $val)
            {
                fputcsv($buffer, $val);
            }
            fclose($buffer);
            
            echo ob_get_clean();
        }
        die;
    }
    
    protected function get_filename($form)
    {
        return sanitize_file_name(get_the_title($form->ID).'-Submissions.csv');
    }
    
    /**
     * Set the export headers.
     */
    protected function send_headers($file_name) {
        if ( function_exists( 'gc_enable' ) ) {
            gc_enable();
        }
        if ( function_exists( 'apache_setenv' ) ) {
            @apache_setenv( 'no-gzip', 1 );
        }
        @ini_set( 'zlib.output_compression', 'Off' ); 
        @ini_set( 'output_buffering', 'Off' );
        @ini_set( 'output_handler', '' );
        ignore_user_abort( true );
        $this->set_time_limit( 0 );
        $this->nocache_headers();
        header( 'Content-Type: text/csv; charset=utf-8' );
        header( 'Content-Disposition: attachment; filename=' . $file_name );
        header( 'Pragma: no-cache' );
        header( 'Expires: 0' );
    }
    
    protected function set_time_limit( $limit = 0 ) {
        if ( function_exists( 'set_time_limit' ) && false === strpos( ini_get( 'disable_functions' ), 'set_time_limit' ) && ! ini_get( 'safe_mode' ) ) {
            @set_time_limit( $limit );
        }
    }
    
    protected function nocache_headers()
    {
        $this->maybe_define_constant( 'DONOTCACHEPAGE', true );
        $this->maybe_define_constant( 'DONOTCACHEOBJECT', true );
        $this->maybe_define_constant( 'DONOTCACHEDB', true );
        nocache_headers();
    }
    
    protected function maybe_define_constant( $name, $value ) {
        if ( ! defined( $name ) ) {
            define( $name, $value );
        }
    }
}

new DHVCForm_Export_Form_Entries;