}
             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;
             }
         }
     } else {
         echo "Deal Id: " . $each_call['deal_id'];
         echo "<div style='color:black;'>Call In Voice Mail.<br><br></div>";
     }
 } else {
<?php

$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."));
    die;
}
_errors_on();
# Get Pipedrive API object
$apiPD = new apiPipeDrive();
$apiCall = new callWebhook();
# Set default timezone
date_default_timezone_set('America/New_York');
# receive the payload
$payload = file_get_contents('php://input');
$data = json_decode(@$payload, true);
//Getting Deal Info and change stage if pipeline id is '1' (i.e. for "Leads")
$deal_info = $apiPD->getDealInfo($data['current']['id']);
$deal_info = json_decode($deal_info, TRUE);
if ($deal_info['data']['pipeline_id'] == "1") {
    $deal_info = $apiPD->modifyDeal($data['current']['id'], array("stage_id" => "1"));
}
// store into the database
//qi("pd_push_notification_log", array("payload" => _escape($payload)));
# now, identify if that is hot lead then get the number of customer and start calling the customer
# c2a6fc3129578b646ae55717ed15f03ce3ee4df0 - this is key for custom attribute/field - "Source"
$deal_source = $data['current']['c2a6fc3129578b646ae55717ed15f03ce3ee4df0'];
if (in_array($deal_source, array('37')) || 1) {
    # Get Person ID
    $person_id = $data['current']['person_id'];
    # Get Deal ID
            $last_updated_record = q("select *,(NOW()  - INTERVAL 5 MINUTE) as ccc,NOW()  from agent_call_dialed where deal_id='{$each_data['deal_id']}' AND modified_at<=NOW()   - INTERVAL 5 MINUTE order by modified_at DESC");
            d($last_updated_record);
            if (count($last_updated_record) == 0) {
                echo "wait to call";
                continue;
            } else {
                echo "dial";
            }
        } else {
            echo "<br>Total Count:  " . $each_data['total_call'];
        }
        $redial_data = qs("select * from agent_call_dialed where deal_id='{$each_data['deal_id']}' order by id ASC");
        $phone_value = $redial_data['customer_phone'];
        $new_agent_numbers = explode(",", $redial_data['agent_numbers']);
        $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'];
 }
 $curr_agent_arr = explode(",", $voice_calls['curr_agent']);
 $all_agent_arr = explode(",", $voice_calls['all_agents']);
 $all_agent_arr_unique = array_unique($all_agent_arr);
 $new_agent_numbers = array();
 foreach ($all_agent_arr_unique as $each_value) {
     if (in_array($each_value, $curr_agent_arr)) {
         echo "<br>duplicate: " . $each_value;
     } else {
         echo "<br>call to: " . $each_value;
         $new_agent_numbers[] = $each_value;
     }
 }
 if (count($new_agent_numbers) > 0) {
     qu("voice_call", array("in_progress" => "1"), "deal_id='" . $each_call['deal_id'] . "'");
     $apiCall = new callWebhook();
     echo "cust: " . $first_voice_call[0]['customer_phone'] . "<br>";
     echo "Agents: <br>";
     d($new_agent_numbers);
     $apiCall->callNow($first_voice_call[0]['customer_phone'], $new_agent_numbers, $each_call['deal_id'], "1", $cate);
 } else {
     qu("voice_call", array("is_aborted" => "2"), "deal_id='" . $each_call['deal_id'] . "'");
     $data = qs("select * From pd_users where is_active='1' and is_default='1' order by name asc");
     $dealId = $each_call['deal_id'];
     if (!empty($data)) {
         $apiPD = new apiPipeDrive();
         $agent_id = $data['pd_id'];
         $deal_data = json_decode($apiPD->getDealInfo($dealId));
         $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 : '';
         $apiPD->assignDeal($dealId, $agent_id);
<?php

if (isset($_REQUEST['click_to_call']) && $_REQUEST['click_to_call'] == 1) {
    $fields['deal_id'] = $_REQUEST['dealId'];
    $fields['agent_phone'] = removeCellFormat($_REQUEST['agent_phone']);
    $fields['agent_name'] = $_REQUEST['agent_name'];
    $fields['customer_phone'] = removeCellFormat($_REQUEST['customer_phone']);
    $click_to_call_id = qi("click_to_call", $fields);
    $callWebhook = new callWebhook();
    $sid = $callWebhook->click_to_call($click_to_call_id);
    $data = array("id" => $click_to_call_id, "sid" => $sid);
    json_die(true, $data);
}
$dealId = $_REQUEST['dealId'];
$phone_count = $_REQUEST['phone_count'];
$contact_list = array();
$is_cust_number = 0;
for ($index = 1; $index <= $phone_count; $index++) {
    $is_cust_number = 1;
    $contact_list[] = removeCellFormat($_REQUEST['phone_' . $index]);
}
$conversation_list = q("select * from text_conversation where deal_id='{$dealId}' order by messageTime asc");
$agent_name = $_REQUEST['agent_name'];
$agent = qs("select * from pd_users where name='{$agent_name}'");
if (empty($agent) || $agent['phone'] == '' && $agent['cell'] == '') {
    $is_agent_number = 0;
} else {
    $is_agent_number = 1;
    $agent_no = $agent['phone'] == '' ? $agent['cell'] : $agent['phone'];
    $agent_no = formatCellDash($agent_no);
}
<?php

_errors_on();
$apiPD = new apiPipeDrive();
$apiCall = new callWebhook();
# Set default timezone
date_default_timezone_set('America/New_York');
# receive the payload
//Test Mode  - Remove comment on Live
$payload = file_get_contents('php://input');
$data = json_decode(@$payload, true);
//Test Mode - Delete following static code
//$payload1='{"v":1,"matches_filters":null,"meta":{"v":1,"action":"added","object":"activity","id":19126,"company_id":501009,"user_id":990918,"host":"sprout2.pipedrive.com","timestamp":1454411818,"permitted_user_ids":["*"],"trans_pending":false,"is_bulk_update":false},"retry":0,"current":{"id":19126,"company_id":501009,"user_id":990918,"done":false,"type":"text","reference_type":"none","reference_id":null,"due_date":"2016-02-02","due_time":"","duration":"","add_time":"2016-02-0211:16:58","marked_as_done_time":"","subject":"Dave Jay - (918)460-312","deal_id":4586,"org_id":4058,"person_id":4421,"active_flag":true,"update_time":"2016-02-0211:16:58","gcal_event_id":null,"google_calendar_id":null,"google_calendar_etag":null,"person_name":"DaveTest","org_name":"DaveTest","note":"Thisistest","deal_title":"DaveTestdeal","assigned_to_user_id":990918,"created_by_user_id":990918,"owner_name":"DaveJay(Programmer)","person_dropbox_bcc":"*****@*****.**","deal_dropbox_bcc":"*****@*****.**","participants":[],"updates_story_id":128972,"parties":[{"id":3108,"activity_id":19126,"party_id":3108,"active_flag":true,"add_time":"2016-02-0211:16:58","update_time":null,"name":"DaveJay(Programmer)","address":"*****@*****.**","person_id":null,"user_id":990918},{"id":3109,"activity_id":19126,"party_id":3109,"active_flag":true,"add_time":"2016-02-0211:16:58","update_time":null,"name":"DaveTest","address":"","person_id":4421,"user_id":null}]},"previous":null,"event":"added.activity"}';
//$data = json_decode($payload1,true);
if ($data['meta']['host'] == 'api.pipedrive.com' || $data['current']['type'] != 'text' || $data['current']['subject'] == 'SMS - Replied By Customer') {
    die;
}
$activity_id = $data['meta']['id'];
$person_id = $data['current']['person_id'];
$person_data = $apiPD->getPersonInfo($person_id);
$person_data = json_decode($person_data, true);
$message = $data['current']['note'];
$deal_id = $data['current']['deal_id'];
$org_id = $data['current']['org_id'];
$subject = $data['current']['subject'];
$subject = preg_replace("/[^0-9]/", "", $subject);
$activityLogArray = array();
if (strlen($subject) < 10) {
    $phone_value = isset($person_data['data']['phone'][0]['value']) ? $person_data['data']['phone'][0]['value'] : '-1';
} else {
    $phone_value = $subject;