if ($user_id != '') {
            $check_user_id = array();
            $check_user_id = Call_distribution::CheckMainUserId($user_id);
            echo $check_user_id . "****" . $each_user["name"];
            echo "<br/>";
            unset($fields);
            $fields["name"] = $each_user["name"];
            $fields["email"] = $each_user["email"];
            $fields["phone"] = $each_user["phone"];
            $fields["is_deleted"] = '0';
            if ($each_user['active_flag']) {
                $fields["is_active"] = '1';
            } else {
                $fields["phone"] = '';
                $fields["is_active"] = '0';
            }
            if ($check_user_id != '') {
                $fields = _escapeArray($fields);
                if ($each_user['active_flag']) {
                    unset($fields['phone']);
                }
                qu("pd_users", $fields, " id = '{$check_user_id}' ");
            } else {
                $fields["pd_id"] = $user_id;
                $fields = _escapeArray($fields);
                qi("pd_users", $fields);
            }
        }
    }
}
die;
     } elseif ($cat_count == 3 && $category == 'B') {
         $category = 'C';
     } elseif ($cat_count == 3 && $category == 'C') {
         qi("activity_log", _escapeArray(array("log" => "We had tried 3 times call for group-C.", "deal_id" => $each_call['deal_id'])));
         continue;
     }
     if ($category != 'A' && $category != 'B' && $category != 'C') {
         $category = 'A';
     }
     $query = "select count(*) as count from agent_call_dialed where deal_id='" . $each_call['deal_id'] . "' AND  DATE(`created_at`) = CURDATE() AND created_at>NOW() - INTERVAL 1 MINUTE order by created_at desc";
     $last_call = qs($query);
     echo $query;
     d($last_call);
     if ($last_call['count'] > 0) {
         echo "call in progress";
         qi("activity_log", _escapeArray(array("log" => "we can try only after 5 minutes.", "deal_id" => $each_call['deal_id'])));
         continue;
     } else {
         echo "call need to dial";
         echo "<Br>" . $last_agent_call_dial[0]['customer_phone'];
         $apiCall = new callWebhook();
         $all_agent_arr_unique = explode(",", $last_agent_call_dial[0]['agent_numbers']);
         $new_agent_numbers = array();
         foreach ($all_agent_arr_unique as $each_value) {
             $new_agent_numbers[] = $each_value;
         }
         d($new_agent_numbers);
         $apiCall->callNow($last_agent_call_dial[0]['customer_phone'], $new_agent_numbers, $each_call['deal_id'], "1", $category);
         die;
     }
 }
<?php

//Twilio Website Number: (516) 210-2005
$apiPD = new apiPipeDrive();
$agent_numbers = $apiPD->getAgentByDealSource(37);
$fields['from'] = $_REQUEST['From'];
$fields['CallSid'] = $_REQUEST['CallSid'];
$insertId = qi("website_number_dials", _escapeArray($fields));
header("content-type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>
<Response>

    <?php 
if (count($agent_numbers) == 0) {
    ?>
        <Say>Thank you for calling leadpropel.com</Say>
        <Say>Sorry, All agents are busy at the moment.</Say>
        <Say>We will call back later.</Say>
        <Say>Thank you</Say>
    <?php 
} else {
    ?>
        <Dial action="<?php 
    echo _U . "website_number_dial_status?params=" . $insertId . "--00--status";
    ?>
">
            <?php 
    foreach ($agent_numbers as $each) {
        ?>
                <Number url="<?php 
 public function callNow($phone_value, $agent_numbers, $dealId, $is_redial = "0", $group = "A")
 {
     $account_sid = ACCOUNT_SID;
     $auth_token = AUTH_TOKEN;
     //$account_sid = 'AC4878ef9ccad9ce3b980fdd4d1d0f42ca';
     //$auth_token = 'ea532dd88a9ee7fb43259da56a40a38f';
     $call_status = qs("select *,value as call_status from config where `key` = 'CALL_STATUS'");
     if (strtolower($call_status['call_status']) != "on") {
         qi("test", array("t" => "call distribution is off.", "payload" => "someone is trying to call without permission!!!"));
         die;
     }
     if ($phone_value == '') {
         qi("activity_log", _escapeArray(array("log" => "Call can not be generated. Phone value is blank", "deal_id" => $dealId)));
         die;
     }
     if (IS_DEV_ENV && $is_redial == "0") {
         $agent_numbers = array(TOLL_FREE_NO);
         $phone_value = AGENT_NO;
     }
     if (count($agent_numbers) == 0) {
         return;
     }
     include _PATH . "/Services/Twilio.php";
     $agent_numbers_arr = $agent_numbers;
     $agent_numbers = implode(",", $agent_numbers_arr);
     $agent_numbers_search = implode("','", $agent_numbers_arr);
     $filter_agent_number = self::filterAgentsByGroup($agent_numbers_search, $group);
     //d($agent_numbers);
     //d($filter_agent_number);
     if (empty($filter_agent_number['agent'])) {
         qi("activity_log", _escapeArray(array("log" => "We have no agents for group '{$group}' or any lower level. ", "deal_id" => $dealId)));
         qu("agent_call_dialed", array("is_aborted" => "1"), "deal_id='" . $dealId . "'");
         qu("voice_call", array("in_progress" => "0"), "deal_id='" . $dealId . "'");
         die;
     }
     qi("agent_call_dialed", _escapeArray(array("agent_numbers" => $agent_numbers, "deal_id" => $dealId, "is_redial" => $is_redial, "customer_phone" => $phone_value, "category" => $filter_agent_number['group'])));
     $client = new Services_Twilio($account_sid, $auth_token);
     $deal_sid_data = q("select * from deal_sid where status!='R' AND status!='C' AND deal_id='{$dealId}'");
     qu("deal_sid", array("status" => "C"), " status!='R' AND status!='C' AND deal_id='{$dealId}'");
     foreach ($deal_sid_data as $each_sid) {
         $call = $client->account->calls->get($each_sid['sid']);
         $call->update(array("Status" => "completed"));
     }
     try {
         foreach ($filter_agent_number['agent'] as $key => $each_agent) {
             //foreach ($agent_numbers_arr as $key => $each_agent) {
             //echo $each_agent."<br>";
             $url_agent_calling = _U . "DialingAgent?";
             $url_agent_received = _U . "ReceivedAgent?";
             $params = "agent_numbers=" . $agent_numbers . "&dealId=" . $dealId . "&phone_value=" . $phone_value . "&cur_agent=" . $each_agent;
             $url_agent_calling .= $params;
             $url_agent_received .= $params;
             $call = $client->account->calls->create(TWILIO_PHONE_NUMBER, $each_agent, $url_agent_received, array("Method" => "GET", "StatusCallback" => $url_agent_calling, "StatusCallbackMethod" => "POST", "StatusCallbackEvent" => array("ringing", "completed"), "Timeout" => "25"));
             echo $call->sid . "<br>";
             //sleep(2);
         }
         echo "<br>We are calling on " . $phone_value;
         die;
     } catch (Exception $e) {
         // Failed calls will throw
         echo $e;
         die;
     }
 }
             $fields['cust_name'] = $each_deal['person_id']['name'];
             $fields['cust_email'] = $each_deal['person_id']['email'][0]['value'];
             $fields['stage_id'] = $each_deal['stage_id'];
             $fields['source'] = _e($source[$each_deal['c2a6fc3129578b646ae55717ed15f03ce3ee4df0']]['label'], "");
             $fields['status'] = $each_deal['status'];
             $fields['curr_stage'] = $stage[$each_deal['stage_id']]['name'];
             $fields['initial_move_stage'] = $filter_stage_name;
             $fields['stage_order_nr'] = $stage[$each_deal['stage_id']]['order_nr'];
             $duplicate = qs("select * from dashboard_stage_entering_deals where deal_id = '{$fields['deal_id']}' and initial_move_stage = '{$fields['initial_move_stage']}'");
             if (!empty($duplicate)) {
                 unset($fields['reference']);
                 qu("dashboard_stage_entering_deals", _escapeArray($fields), "deal_id= '{$fields['deal_id']}' and initial_move_stage = '{$fields['initial_move_stage']}'");
                 echo "<br> Record Update for deal: " . $fields['deal_id'];
             } else {
                 $fields['date'] = _mysqlDate();
                 qi("dashboard_stage_entering_deals", _escapeArray($fields));
                 echo "<br>Record Insert for deal: " . $fields['reference'];
             }
         }
         echo "new call<Br><Br><br>";
         $start_record_from += $no_of_records;
         $deal_data = array();
         $deal_data = $apiPD->getFilterDeals($filter_id, $start_record_from, $no_of_records);
         $deal_data = json_decode($deal_data, "true");
     } else {
         echo "no more records";
         break;
     }
 }
 if (!$deal_data['success']) {
     echo "<br>Error - " . $filter_stage_name . " - " . $deal_data['error'];
<?php

$params = explode("--", $_REQUEST['params']);
if (isset($params[2]) && $params[2] == "status") {
    $fields['CallStatus'] = $_REQUEST['CallStatus'];
    qu("website_number_dials", _escapeArray($fields), "id='" . $params[0] . "'");
} else {
    $fields['dial_agent'] = $params[1];
    qu("website_number_dials", _escapeArray($fields), "id='" . $params[0] . "'");
}
header("content-type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>
<Response><Say>Good Bye</Say>
</Response>
    <?php 
die;
        $dealId = $each_data['deal_id'];
        $apiCall = new callWebhook();
        $apiCall->callNow($phone_value, $new_agent_numbers, $dealId, "0");
        echo "<br><br>Call Generated -<br>Agents:";
        d($new_agent_numbers);
        echo "<br>Customer Phone:";
    }
}
$agent_call_detail = q("SELECT deal_id,customer_phone, is_mail_send,COUNT(id) FROM `agent_call_dialed` where is_redial='0'  AND modified_at>=CURRENT_DATE  - INTERVAL 1 DAY GROUP BY deal_id HAVING COUNT(id)>=5");
foreach ($agent_call_detail as $each_data) {
    if ($each_data['is_mail_send'] == '0') {
        $apiPD = new apiPipeDrive();
        $deal_data = json_decode($apiPD->getDealInfo($each_data['deal_id']));
        $source_id = isset($deal_data->data->c2a6fc3129578b646ae55717ed15f03ce3ee4df0) ? $deal_data->data->c2a6fc3129578b646ae55717ed15f03ce3ee4df0 : '';
        //qi("call_detail",  _escapeArray(array("deal_id"=>$each_data['deal_id'],"recording_duration"=>"0","source_id"=>$source_id)));
        qu("agent_call_dialed", _escapeArray(array("is_mail_send" => "1")), " deal_id='{$each_data['deal_id']}'");
        $dealId = $each_data['deal_id'];
        //$dealId = "5232";// Test Mode
        $apiPD = new apiPipeDrive();
        $deal_data = $apiPD->getDealInfo($dealId);
        $deal_data = json_decode($deal_data);
        $deal_amount = number_format($deal_data->data->value, 2);
        $deal_amount = $deal_amount . ' ' . $deal_data->data->currency;
        $organization = $deal_data->data->org_name;
        $customer_name = $deal_data->data->person_name;
        $customer_phone = $each_data['customer_phone'];
        ob_start();
        $mail_subject = $mail_heading = "Missed Customer Call";
        include _PATH . "instance/front/tpl/missed_call_mail_template.php";
        $content = ob_get_contents();
        ob_end_clean();
    <Response><Say>You had not press any key. We have no other agents to call!</Say></Response>
<?php 
        $agent_name = 'agent';
        $agent_detail = qs("select * from pd_users where phone like '%" . $cur_agent . "%'");
        if (isset($agent_detail)) {
            $agent_name = $agent_detail['name'];
        }
        $message = '<b>Note: </b><br>Call went into voicemail of <b>' . $agent_name . "</b>. System will call again in <b>10 minutes</b>.";
        sendNote($dealId, $message);
        die;
    }
} elseif ($_REQUEST['Digits'] == 1) {
    qu("voice_call", array("in_progress" => "0"), "deal_id='" . $dealId . "'");
    //Set in_progress=0 because call process is completed
    $agent_call_dialed_data = qs("select id from agent_call_dialed where deal_id='{$dealId}' order by id desc");
    qu("agent_call_dialed", _escapeArray(array("received_agent" => $cur_agent, "is_received" => "1")), "id='" . $agent_call_dialed_data['id'] . "'");
    $account_sid = ACCOUNT_SID;
    $auth_token = AUTH_TOKEN;
    include _PATH . "/Services/Twilio.php";
    $client = new Services_Twilio($account_sid, $auth_token);
    $url = _U . "DialingCustomer?";
    try {
        $params = "agent_numbers=" . $agent_numbers . "&dealId=" . $dealId . "&phone_value=" . $phone_value . "&cur_agent=" . $cur_agent;
        $url = $url . $params;
        $call = $client->account->calls->get($_REQUEST['CallSid']);
        $call->update(array("Url" => $url, "Method" => "POST"));
        echo $call->to;
    } catch (Exception $e) {
        // Failed calls will throw
        echo $e;
        die;
<?php

/**
 * Admin side Login file
 * 
 * 
 * @version 1.0
 * @package lysoft
 * 
 */
//$jsInclude = "home.js.php";
//_R(lr('dashboard'));
$urlArgs = _cg("url_vars");
if (isset($_REQUEST['txt_sms'])) {
    unset($fields);
    $fields['sms'] = $_REQUEST['txt_sms'];
    $fields['activity'] = $_REQUEST['ddl_type'];
    $fields['agent'] = $_REQUEST['ddl_agent'];
    qi("messages", _escapeArray($fields));
    $_SESSION['greetings_msg'] = 'Record Added successfully!';
}
$message_list = q("SELECT * FROM  `messages`");
_cg("page_title", "SMS Text");
            $new['call_handled'] = '0';
            $a = qi("call_detail", $new);
            //echo "<br>-" . $each_deal['is_updated'] . "-added-" . $each_deal['deal_id'];
        }
    }
    $apiPD = new apiPipeDrive();
    $agent_call_dialed = q("select * from agent_call_dialed where is_updated='0'");
    foreach ($agent_call_dialed as $each_deal) {
        $deal_data = $apiPD->getDealInfo($each_deal['deal_id']);
        $deal_data = json_decode($deal_data);
        //d($deal_data);
        $person_id = isset($deal_data->data->person_id->value) ? $deal_data->data->person_id->value : '';
        $org_id = isset($deal_data->data->org_id->value) ? $deal_data->data->org_id->value : '';
        $source_id = isset($deal_data->data->c2a6fc3129578b646ae55717ed15f03ce3ee4df0) ? $deal_data->data->c2a6fc3129578b646ae55717ed15f03ce3ee4df0 : '';
        $cust_name = isset($deal_data->data->person_id->name) ? $deal_data->data->person_id->name : '';
        $add_time = isset($deal_data->data->add_time) ? $deal_data->data->add_time : '';
        $add_time = date("Y-m-d H:i:s", strtotime($add_time) - 3600 * 4);
        $cust_email = isset($deal_data->data->person_id->email[0]->value) ? $deal_data->data->person_id->email[0]->value : '';
        $org_name = isset($deal_data->data->org_name) ? $deal_data->data->org_name : '';
        $created_at = qs("select created_at from agent_call_dialed where deal_id='{$each_deal['deal_id']}' order by id asc limit 0,1");
        $call_detail_fields['source_id'] = $source_id;
        $call_detail_fields['customer_name'] = $cust_name;
        $call_detail_fields['customer_email'] = $cust_email;
        $call_detail_fields['org_name'] = $org_name;
        $call_detail_fields['deal_id'] = $each_deal['deal_id'];
        $call_detail_fields['deal_added'] = $add_time;
        $call_detail_fields['created_at'] = $created_at['created_at'];
        $call_detail_id = qu('call_detail', _escapeArray($call_detail_fields), "deal_id='{$each_deal['deal_id']}'");
        $call_detail_id = qu('agent_call_dialed', array("is_updated" => '1'), "deal_id='{$each_deal['deal_id']}'");
    }
}
$apiPD->assignOrganization($org_id, $agent_id);
$call_detail_data = q("select * from call_detail where sid='{$_REQUEST['CallSid']}'");
$call_detail_fields['agent_phone'] = $cur_agent;
$call_detail_fields['agent_id'] = $agent_id;
$call_detail_fields['agent_name'] = $agent_name;
$call_detail_fields['status'] = isset($_REQUEST['CallStatus']) ? $_REQUEST['CallStatus'] : '';
$call_detail_fields['customer_phone'] = $phone_value;
$call_detail_fields['source_id'] = $source_id;
$call_detail_fields['customer_name'] = $cust_name;
$call_detail_fields['customer_email'] = $cust_email;
$call_detail_fields['org_name'] = $org_name;
$call_detail_fields['deal_id'] = $dealId;
$call_detail_fields['deal_added'] = $add_time;
$call_detail_fields['sid'] = $_REQUEST['CallSid'];
$call_detail_id = qi('call_detail', _escapeArray($call_detail_fields));
qu("agent_call_dialed", _escapeArray(array("is_updated" => "1")), "deal_id='" . $dealId . "'");
$fields['subject'] = 'Call';
$fields['done'] = '1';
$fields['type'] = 'call';
$fields['deal_id'] = $dealId;
// Test Deal Id - $fields['deal_id'] = '4586';
$fields['person_id'] = $person_id;
$fields['org_id'] = $org_id;
$param = http_build_query(array('call_detail_id' => $call_detail_id));
//$fields['note'] = "<iframe src='https://www.leadpropel.com/".FOLDER_RUN."playAudio?".$param."' width='380' height='110'></iframe>";
$fields['note'] = "<span call-recording-id-{$call_detail_id}>Call Recording: <br>We are loading call recording.</span>";
$data = $apiPD->createActivity($fields);
$activity_data = json_decode($data);
if (isset($activity_data->success) && $activity_data->success) {
    qu('call_detail', array("activity_id" => $activity_data->data->id), "id='{$call_detail_id}'");
}
             $fields['source'] = _e($source[$each_deal['c2a6fc3129578b646ae55717ed15f03ce3ee4df0']]['label'], "");
             $fields['status'] = $each_deal['status'];
             $fields['curr_stage'] = $stage[$each_deal['stage_id']]['name'];
             //$fields['initial_move_stage'] = $filter_stage_name;
             $fields['stage_order_nr'] = $stage[$each_deal['stage_id']]['order_nr'];
             $duplicate = qs("select * from dashboard_pipedrive_deals where deal_id = '{$fields['deal_id']}' and initial_move_stage = '{$fields['initial_move_stage']}'");
             if (!empty($duplicate)) {
                 unset($fields['reference']);
                 qu("dashboard_pipedrive_deals", _escapeArray($fields), "deal_id= '{$fields['deal_id']}' and initial_move_stage = '{$fields['initial_move_stage']}'");
                 echo "<br> Record Update for deal: " . $fields['deal_id'];
             } else {
                 $fields['pipedrive_added_date'] = $each_deal['add_time'];
                 $dt = new DateTime($each_deal['add_time']);
                 $dt->setTimezone($tz);
                 $fields['added_date'] = $dt->format('Y-m-d H:i:s');
                 qi("dashboard_pipedrive_deals", _escapeArray($fields));
                 echo "<br>Record Insert for deal: " . $fields['reference'];
             }
         }
         echo "new call<Br><Br><br>";
         $start_record_from += $no_of_records;
         $deal_data = array();
         $deal_data = $apiPD->getFilterDeals($filter_id, $start_record_from, $no_of_records);
         $deal_data = json_decode($deal_data, "true");
     } else {
         echo "no more records";
         break;
     }
 }
 if (!$deal_data['success']) {
     echo "<br>Error - " . $filter_stage_name . " - " . $deal_data['error'];