<?php 
/****************************************
/*  Author  : Kvvaradha
/*  Module  : Kvcodes CRM
/*  E-mail  : admin@kvcodes.com
/*  Version : 1.0
/*  Http    : www.kvcodes.com
*****************************************/

function ImportLeads($data){
    $crm_salutation_data = array(
        'Mr'  =>  1, 
        'Ms' =>  2,
        'Mrs' =>  3,
        'Dr' =>  4,
        'Prof' =>  5,
        'Other' => 6
    );
    
    $existingLeads = array();
    $vj=1;
    foreach($data as $singleData){
        if($vj == 1){
            $vj++;
            continue;
        }
        $LeadArray = array();
        if(GetSingleValue('kv_crm_leads', 'lead_id', array('email' => $singleData[3])) == false){
            if(is_numeric($singleData[0]))
                $LeadArray['salutation'] = $singleData[0];
            else
                $LeadArray['salutation'] = $crm_salutation_data[$singleData[0]];

            $LeadArray['first_name'] = $singleData[1];
            $LeadArray['last_name'] = $singleData[2];
            $LeadArray['email'] = $singleData[3];
            $LeadArray['curr_code'] = $singleData[4];
            $LeadArray['work_phone'] = $singleData[5];
            $LeadArray['mobile_phone'] = $singleData[6];
            $LeadArray['address2'] = $singleData[7];
            $LeadArray['addr_line1'] = $singleData[8];
            $LeadArray['addr_line2'] = $singleData[9];
            $LeadArray['city'] = $singleData[10];
            $LeadArray['state'] = $singleData[11];

            if($singleData[12]){
                if(is_numeric($singleData[12]))  //Country
                    $LeadArray['country'] = $singleData[12];
                else{
                    $country_id = GetSinglevalue('kv_crm_country', 'id', array('local_name' => $singleData[12]));
                    if($country_id)
                        $LeadArray['country'] = $country_id;
                    else
                        $LeadArray['country'] = Insert('kv_crm_country', array('local_name' => $singleData[12]));
                }
            }

            $LeadArray['client'] = $singleData[13];
            $LeadArray['title'] = $singleData[14];
            $LeadArray['website'] = $singleData[15];

            if($singleData[16]){
                if(is_numeric($singleData[16]))  // Lead Source
                    $LeadArray['lead_source_id'] = $singleData[16];
                else{
                    $country_id = GetSinglevalue('kv_crm_picklist_values', 'id2', array('description' => $singleData[16], 'picklist_values' => 1));
                    if($country_id)
                        $LeadArray['lead_source_id'] = $country_id;
                    else{
                        $id2 = GetNextPickNumber(1);
                        $LeadArray['lead_source_id'] = Insert('kv_crm_picklist_values', array('picklist_id' => 1, 'id2' => $id2,'description' => $singleData[16]));
                    }
                }
            }

            if($singleData[17]){
                if(is_numeric($singleData[17]))  // Industry List
                    $LeadArray['industry_id'] = $singleData[17];
                else{
                    $country_id = GetSinglevalue('kv_crm_picklist_values', 'id', array('description' => $singleData[17], 'picklist_values' => 2));
                    if($country_id)
                        $LeadArray['industry_id'] = $country_id;
                    else{
                        $id2 = GetNextPickNumber(2);
                        $LeadArray['industry_id'] = Insert('kv_crm_picklist_values', array('picklist_id' => 2, 'id2' => $id2, 'description' => $singleData[17]));
                    }
                }
            }

            if($singleData[18]){
                if(is_numeric($singleData[18]))  // Business Type
                    $LeadArray['lead_status_id'] = $singleData[18];
                else{
                    $country_id = GetSinglevalue('kv_crm_picklist_values', 'id', array('description' => $singleData[18], 'picklist_values' => 3));
                    if($country_id)
                        $LeadArray['lead_status_id'] = $country_id;
                    else{
                        $id2 = GetNextPickNumber(2);
                        $LeadArray['lead_status_id'] = Insert('kv_crm_picklist_values', array('picklist_id' => 3, 'id2' => $id2, 'description' => $singleData[18]));
                    }
                }
            }

            if($singleData[19]){
                if(is_numeric($singleData[19]))
                    $LeadArray['added_by'] = $singleData[19];
                else
                    $LeadArray['added_by'] = GetSinglevalue('users', 'id', array('user_id' => $singleData[19]));

                if(!$LeadArray['added_by'])
                    $LeadArray['added_by'] = $_SESSION['wa_current_user']->user;
            } else 
                $LeadArray['added_by'] = $_SESSION['wa_current_user']->user;

            if($singleData[20]){
                if(is_numeric($singleData[20]))
                    $LeadArray['managed_by'] = $singleData[20];
                else
                    $LeadArray['managed_by'] = GetSinglevalue('users', 'id', array('user_id' => $singleData[20]));

                if(!$LeadArray['managed_by'])
                    $LeadArray['managed_by'] = $_SESSION['wa_current_user']->user;

            } else 
                $LeadArray['managed_by'] = $_SESSION['wa_current_user']->user;

            if($singleData[21] && is_numeric($singleData[21])){
                $LeadArray['is_converted'] = $singleData[21];
            } else 
                $LeadArray['is_converted'] = 0;

            $LeadArray['note'] = $singleData[22];

            if($singleData[23]){
                $LeadArray['date'] = date('Y-m-d', strtotime($singleData[23]));
            } else 
                $LeadArray['date'] = date('Y-m-d');

            //Insert it into Leads table.
            Insert('kv_crm_leads', $LeadArray);
        }else
            $existingLeads[] = $singleData[3];
    }
    return (!empty($existingLeads)? $existingLeads : false);
}


function ImportOpportunities($data) {
	    
    $existingOppors = array();
    foreach($data as $singleData){
        $OpporArray = array();
        if(GetSingleValue('kv_crm_opportunities', 'opportunity_id', array('opportunity_name' => $singleData[0])) == false){
            
            $OpporArray['opportunity_name'] = $singleData[0];
            $OpporArray['organization_name'] = $singleData[1];
            $OpporArray['amount'] = $singleData[2];
            $OpporArray['amount_curr_abrev'] = $singleData[3];
            $OpporArray['type'] = $singleData[4];

            if($singleData[5]){
                $OpporArray['expected_close_date'] = date('Y-m-d', strtotime($singleData[5]));
            } else 
                $OpporArray['expected_close_date'] = date('Y-m-d');

            if($singleData[6]){
                if(is_numeric($singleData[6]))  // Oppor Source
                    $OpporArray['lead_source'] = $singleData[6];
                else{
                    $country_id = GetSinglevalue('kv_crm_picklist_values', 'id', array('description' => $singleData[6], 'picklist_values' => 1));
                    if($country_id)
                        $OpporArray['lead_source'] = $country_id;
                    else{
                         $id2 = GetNextPickNumber(1);
                        $OpporArray['lead_source'] = Insert('kv_crm_picklist_values', array('picklist_id' => 1, 'id2' => $id2, 'description' => $singleData[6]));
                    }
                }
            }

            if($singleData[7]){
                if(is_numeric($singleData[7]))
                    $OpporArray['assign_to'] = $singleData[7];
                else
                    $OpporArray['assign_to'] = GetSinglevalue('users', 'id', array('user_id' => $singleData[7]));

                if(!$OpporArray['assign_to'])
                    $OpporArray['assign_to'] = $_SESSION['wa_current_user']->user;
            } else 
                $OpporArray['assign_to'] = $_SESSION['wa_current_user']->user;

            if($singleData[8]){
                if(is_numeric($singleData[8]))  // Sales Stage
                    $OpporArray['sale_stage'] = $singleData[8];
                else{
                    $country_id = GetSinglevalue('kv_crm_picklist_values', 'id', array('description' => $singleData[8], 'picklist_values' => 5));
                    if($country_id)
                        $OpporArray['sale_stage'] = $country_id;
                    else{
                         $id2 = GetNextPickNumber(5);
                        $OpporArray['sale_stage'] = Insert('kv_crm_picklist_values', array('picklist_id' => 5, 'id2' => $id2, 'description' => $singleData[8]));
                    }
                }
            }

            $OpporArray['probability'] = $singleData[9];
            $OpporArray['forecast_amount'] = $singleData[10];
            $OpporArray['forecast_curr_abrev'] = $singleData[11];
            $OpporArray['contact_id'] = $singleData[12];
            $OpporArray['custome_info'] = $singleData[13];            
            $OpporArray['description'] = $singleData[14];
          	
          	if($singleData[15]){
                if(is_numeric($singleData[15]))  // Status
                    $OpporArray['status_id'] = $singleData[15];
                else{
                    $country_id = GetSinglevalue('kv_crm_picklist_values', 'id', array('description' => $singleData[15], 'picklist_values' => 5));
                    if($country_id)
                        $OpporArray['status_id'] = $country_id;
                    else{
                         $id2 = GetNextPickNumber(5);
                        $OpporArray['status_id'] = Insert('kv_crm_picklist_values', array('picklist_id' => 5, 'id2' => $id2, 'description' => $singleData[15]));
                    }
                }
            }  

          	if($singleData[16]){
                $OpporArray['crt_date'] = date('Y-m-d', strtotime($singleData[16]));
            } else 
                $OpporArray['crt_date'] = date('Y-m-d');

            if($singleData[17]){
                $OpporArray['upd_date'] = date('Y-m-d', strtotime($singleData[17]));
            } else 
                $OpporArray['upd_date'] = date('Y-m-d');
           
            if($singleData[18]){
                if(is_numeric($singleData[18]))  // Customer Id
                    $OpporArray['cust_id'] = $singleData[18];
                else{
                    $debtor_id = GetSinglevalue('debtors_master', 'debtor_no', array('name' => $singleData[18]));
                    if($debtor_id)
                        $OpporArray['cust_id'] = $debtor_id;
                    else
                        $OpporArray['cust_id'] = 0;
                }
            }           

            //Insert it into Oppors table.
            Insert('kv_crm_opportunities', $OpporArray);
        }else
            $existingOppors[] = $singleData[1];
    }
    return (!empty($existingOppors)? $existingOppors : false);
}

function ImportProjects($data) {
    
}

function ImportCustomers($data) {
    
}

function ImportSuppliers($data) {
    
}

function ImportTasks($data) {
    
}

//Export Functions
function ExportLeads($company_name) {
    $allRecords = GetAll('kv_crm_leads');
    
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="Leads-'.$company_name.'.csv"');

    $fp = fopen('php://output', 'wb');

    $headerLine = array("ID", "Salutation","Firstname","Lastname","email","currency Code","Work Phone","Mobile Phone","Address 2","Address line 1","Address line 2","City","State","Country","Client","Title","Website","Lead Source","Industry","Status","Added By","Managed By","Converted to Customer","Note","Date");
    fputcsv($fp, $headerLine);
    foreach($allRecords as $line) {
        $val = array();
        foreach($line as $key => $single){
            if($single == '' || $single === null || empty($single))
                $val[] = 'NULL';
            else
                $val[] = htmlspecialchars($single);
        }
        //display_error(json_encode($val));
        fputcsv($fp, $val, ',', ' ');
    }

    fclose($fp);
    exit;
}

function ExportProjects($company_name) {
    $allRecords = GetAll('kv_crm_projects');
    
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="Projects-'.$company_name.'.csv"');

    $fp = fopen('php://output', 'wb');

    $headerLine = array("Project Code", "Project Title", "Description", "Status", "Customer", "Branch", "Sales Account", "Inventory Account", "COGS Account", "Adjustment Account", "WIP Account", "Dimension", "Dimension 2", "Flag", "Unit", "Billed", "Billing Type", "Start Date", "End Date", "Project Created", "Date Finished", "Progress", "Progress From Tasks", "Project Cost", "Rate Per Hour", "Estimated Hours", "Added From", "Inactive", "Members");
    fputcsv($fp, $headerLine);
    foreach($allRecords as $line) {
        $val = array();
       

        $members = GetAll('kv_crm_projectmembers', array('project_id' => $line['id']));
        if($members){
            $mem_ids = array();
            foreach($members as $member){
                $mem_ids[] = $member['staff_id'];
            }
            $members =serialize($mem_ids);
            $members =str_replace("&quot;", '"', $members);
        }else
            $members ='';
        unset($line['id']);
        $line['members'] = $members;
        foreach($line as $key => $single){
            if($single == '' || $single === null || empty($single))
                $val[] = 'NULL';
            else
                $val[] = htmlspecialchars($single);
        }
        //$val_last =str_replace("&quot;", '"', end($val));
        //array_pop($val);
       // $val[] = $val_last;
        fputcsv($fp, $val, ',', ' ');
    }

    fclose($fp);
    exit;
}

function ExportCustomers($company_name) {
    
}

function ExportSuppliers($company_name) {
    
}

function ExportTasks($company_name) {
    $allRecords = GetAll('kv_crm_tasks');
    
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="Tasks-'.$company_name.'.csv"');

    $fp = fopen('php://output', 'wb');

    $headerLine = array("Name", "Description", "Priority", "Date Added", "Start Date", "Due Date", "Date Finished", "Added From", "Status", "Type ID", "Type", "Billable", "Billed", "Invoice ID", "Hourly Rate", "Staff ID");
    fputcsv($fp, $headerLine);
    foreach($allRecords as $line) {
        $val = array();
        unset($line['id']);
        unset($line['cycles']);
        unset($line['total_cycles']);
        unset($line['last_recurring_date']);
        unset($line['custom_recurring']);
        unset($line['is_public']);
        unset($line['milestone']);
        unset($line['kanban_order']);
        unset($line['visible_to_client']);
        unset($line['deadline_notified']);
        foreach($line as $key => $single){
            if($single == '' || $single === null || empty($single))
                $val[] = 'NULL';
            else
                $val[] = htmlspecialchars($single);
        }
       
        fputcsv($fp, $val, ',', ' ');
    }

    fclose($fp);
    exit;
}

function ExportOpportunities($company_name) {
    $allRecords = GetAll('kv_crm_opportunities');
    
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="Opportunities-'.$company_name.'.csv"');

    $fp = fopen('php://output', 'wb');

    $headerLine = array("Opportunity Name", "Organization Name", "Amount", "Currrency", "Type", "Close Date", "Lead Source", "Assigned To", "Sales Stage", "Probability", "Forcase Amount", "Forcast Curr", "Contact ID", "Customer Info", "Description", "Status", "Created Date", "Updated Date", "Customer ID");
    fputcsv($fp, $headerLine);
    foreach($allRecords as $line) {
        $val = array();
        unset($line['id']);
        
        foreach($line as $key => $single){
            if($single == '' || $single === null || empty($single))
                $val[] = 'NULL';
            else
                $val[] = htmlspecialchars($single);
        }
       
        fputcsv($fp, $val, ',', ' ');
    }

    fclose($fp);
    exit;
}