<?php
/**
 * @author Sumon Naskar
 * @copyright Fastinfo Group
 * @version 22-Jun-2024
 */
defined('BASEPATH') or exit('No direct script access allowed');
date_default_timezone_set('Asia/Kolkata'); 
require APPPATH . 'helpers/SyncCurl.php';
class ManageLeads extends CI_Controller
{
	
	function __construct()
	{
		parent::__construct();
		$this->load->model('Leads_Model');
        $this->load->helper('fipay');
        $this->load->helper('custom_validation_check');
	}

	public function FBLeadsFetch(){

        date_default_timezone_set('Asia/Kolkata');
        $strtime = strtotime(date("Y-m-d H:i:s",strtotime(' -5 minutes ')));

        $rect_data = $this->Leads_Model->get_active_fb_forms();
        
        foreach($rect_data as $rect){
            // echo "<pre>";print_r($rect);die();
            extract((array)$rect); 
            $result = $this->fetch_leads_curl($form_id);
            
            // echo "<pre>";print_r($result);die();
            $name = $mail=$mobile=''; $insert_count=0; $city = $email = $desire_loan = $loan_type = null;
            foreach($result->data as $data){
                $lead_crt_dtm = date('Y-m-d H:i:s',strtotime($data->created_time));
                $fb_lead_id = $data->id;
                foreach ($data->field_data as $key => $fieldDataValue){
                    if($fieldDataValue->name=='full_name'){
                        $name = $fieldDataValue->values[0];
                    }
                    if($fieldDataValue->name=='email'){
                        $email = $fieldDataValue->values[0];
                    }
                    if( in_array($fieldDataValue->name,['phone_number','phone'])){
                        $phone = substr($fieldDataValue->values[0],-10);
                    }
                    if($fieldDataValue->name=='your_desire_loan_amount'){
                        $desire_loan = $fieldDataValue->values[0];
                    }
                    if($fieldDataValue->name=='which_type_of_loan_you_need?'){
                        $loan_type = $fieldDataValue->values[0];
                    }
                    if($fieldDataValue->name=='state'){
                        $state = $fieldDataValue->values[0];
                    }
                }

                if (empty($name) || empty($email) || empty($phone) ) {
                    echo "Name,Email, Phone no are always required.";
                    continue;
                }

                $check_array = ['phone'=>$phone, 'lead_created_at'=>$lead_crt_dtm];
                $check = $this->Leads_Model->checkalreadyInsertedLeads($check_array,'fb_leads');
                if($check==0){
                    $insert_data=[
                             'fb_lead_id'=>$fb_lead_id,
                             'name'=>$name,
                             'phone'=>$phone,
                             'email'=>$email,
                             'state'=>$state,
                             'loan_type'=>$loan_type,
                             'desire_loan'=>$desire_loan,
                             'form_id'=>$form_id,
                             'campaign_id'=>$campaign_id,
                             'lead_created_at'=>$lead_crt_dtm,
                             'fetched_at'=>date('Y-m-d H:i:s')
                            ];
                        // echo "<pre>";print_r($insert_data); continue; //die();
                    $insert = $this->Leads_Model->insertData($insert_data,'fb_leads');
                    if($insert){
                        $insert_count++;
                    }
                }

            }

            if($insert_count==0){
                echo "No data against Form Id: ".$form_id." at ".date('Y-m-d H:i:s');
            }else{
                echo $insert_count. ' leads updated against Form Id: '.$form_id;
            }
        }

        
    }

    private function fetch_leads_curl($formId){

        date_default_timezone_set('Asia/Kolkata');
        $strtime = strtotime(date("Y-m-d H:i:s",strtotime(' -5 minutes ')));
        $access_token = FB_AD_ACCESS_TOKEN;

        $data = array(
            'filtering' => json_encode(array(
                array(
                    'field' => 'time_created',
                    'operator' => 'LESS_THAN',
                    'value' => $strtime
                )
            )),
            'access_token' => $access_token
        );

        $url = 'https://graph.facebook.com/v19.0/' . $formId . '/leads?' .http_build_query($data);

        $response = SyncCurl::url($url)->withMethod('GET')->send();
        $result = json_decode($response);
        return $result;
    }

    public function TransferFbLeadsAsFresh(){

        $leads=$this->Leads_Model->get_fb_not_transferred_leads();
        if(empty($leads)){
            echo "All Leads Transferred";
            exit();
        }
        $data=[];
        $transfer=$duplicate=0;
        foreach($leads as $val){
            $name = $val->name;
            $email = $val->email;
            if (!isValidName($name)) {
                if(isValidEmail($email)){
                    $email_arr = explode("@",$email);
                    $name = $email_arr[0];
                }else{
                    $name = "Unknown";
                }
            }
            $desire_loan = $val->desire_loan;
            switch ($desire_loan) {
                case '₹50,000__–_₹1_lakh':
                    $loan_amount = '50000';
                    break;

                case '₹1_lakh_–_₹5_lakhs':
                    $loan_amount = '100000';
                    break;

                case '₹5_lakhs_–_₹10_lakhs':
                    $loan_amount = '500000';
                    break;

                case '₹10_lakhs+':
                    $loan_amount = '1000000';
                    break;
                
                default:
                    $loan_amount = null;
                    break;
            }
            $data = array(
                'name'        => $name,
                'email'       => $email,
                'phone'       => $val->phone,
                'state'       => 'Other',
                'fip_id'     => generateCustId(),
                'service'     => 'FIPAY',
                'act_date_time'  => $val->fetched_at,
                'source'      =>    '3',
                'loan_amount'   => $loan_amount
            );

            $insert = $this->Leads_Model->insertData($data,'user_raw_leads');
            if($insert){
                $cond_data=['id'=>$val->id];
                $update_data=['is_transfer'=>1];
                $this->Leads_Model->update_tbl_data($cond_data,$update_data,'fb_leads');
                $transfer++;
                
            }
        }
        echo 'Transferred: '.$transfer.' - Duplicate: '.$duplicate;
    }
}