<?php

class Af2AjaxLeads {

    function __construct() {}

    public function af2_handle_leads_export($lead_list){
        $form_leads = $headers = $header_label = array();
        $headers = array('_id','_date','_name','_mail','_phone');
        $header_label = array(
            '_id' => __('ID', 'af2_multilanguage'),
            '_date' => __('Date / Time', 'af2_multilanguage'),
            '_name' => __('Lead Name', 'af2_multilanguage'),
            '_mail' => __('Lead E-mail', 'af2_multilanguage'),
            '_phone' => __('Lead Phone', 'af2_multilanguage'),
        );

        foreach( $lead_list as $lead ) {
            foreach( $lead['_af2_detailed'] as $detail ) {
                if( in_array($detail['id'], $headers) ) continue;
                
                array_push($headers, $detail['id']);
                $header_label[$detail['id']] = $detail['label'];
            }
        } 

        $form_leads = $lead_list;

        $this->af2_do_lead_export($form_leads, $headers, $header_label, 'leads');
    }

    public function af2_handle_single_lead_export($post_content){
        $form_leads = $headers = $header_label = array();
        $headers = array('label','value');
        $header_label = array(
            'label' => __('Question', 'af2_multilanguage'),
            'value' => __('Answer', 'af2_multilanguage'),
        );

        $form_leads = $post_content;

        $this->af2_do_lead_export($form_leads, $headers, $header_label, 'lead');
    }

    private function af2_do_lead_export($form_leads, $headers, $header_label, $label) {
        $res = array();
        $headers = array_unique($headers);
        $new_header = array();
        foreach ($headers as $head){
            if(!empty($header_label[$head])){
                $new_header[] = $header_label[$head];
            }else{
                $new_header[] = $head;
            }
        }
        $output = fopen("php://output",'w');
        header('Content-Type: application/csv');
        header('Content-Disposition: attachment; filename="'.time().'_'.$label.'.csv"');

        fputcsv($output,$new_header);
        if (!empty($form_leads)) {
            foreach ($form_leads as $lead) {
                $res = array();
                foreach ($headers as $key) {
                    $val = !empty($lead[$key]) ? $lead[$key] : '-';
                    if(is_array($val)) {
                        $res[] = implode(", ", $val);
                    } else {
                        $res[] = $val;
                    }
                }
                fputcsv($output,$res);
            }
        }
        fclose($output);
        exit();
    }
}
