<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Ajax extends Ajax_Controller
{

    function __construct()
    {
        parent::__construct();
        if (!isset($this->session->userdata('userData')->password)) die();
        if (!$this->input->is_ajax_request()) {
            //exit('No direct script access allowed');
        }
    }

    public function updateStatus()
    {
        $out = '';
        $apiMsg = '';
        $leadId = intval($_POST['leadId']);
        if ($leadId > 0) {
            $lead = $this->db->query('SELECT * FROM leads as l
                                        INNER JOIN phone_lines as pl ON l.leadId = pl.leadId
                                        WHERE l.leadId = ' . $leadId)->row();
            $newStatus = intval($_POST['newStatus']);
            $campaign = $this->general_model->getRowById('campaigns', 'campaignId', $lead->campaignId);
            if ($newStatus == 5) {
                if ($campaign->campaignDesc == 'cellcom') {
                    $r = cellcomSimStateNotActive($lead->phone);
                    $apiMsg = ' - Cellcom API: <strong>' . $r->result . '</strong>';
                    if ($r->result == 'SUCCESS') {
                    } else {
                        //echo json_encode(array( 'result' => false, 'out' => $r->result ));
                        //return;
                    }
                }

                if ($campaign->campaignDesc == 'hot') {
                    $r = hotManuiActions($lead->phone, 1); //1
                    $apiMsg = ' - HOT API: <strong>' . $r->mirreturn_message . '</strong>';
                    if (strpos($r->mirreturn_message, 'Success') > -1) {
                    } else {
                        echo json_encode(array('result' => false, 'out' => $r->mirreturn_message));
                        return;
                    }
                }

                if ($campaign->campaignDesc == 'golan') {
                    $phone = $lead->phone;
                    $r = getGolanSubId($phone);
                    if (!empty($r) && isset($r->msg)) {
                        if (isset($r->msg->id)) {
                            $subId = $r->msg->id;
                            $re = GolanFreezeSub($subId);
                            $re2    = GolanReportLostStolen($subId, $a_action = 'block_outgoing_services', $incoming = false);
                            if (isset($re->code) && $re->code == 0) {
                                $apiMsg2 = 'GOLAN API: <strong>Success</strong>';
                            } else {
                                $apiMsg2 = 'GOLAN API: <strong>Failed</strong>';
                            }
                        } else {
                            $apiMsg2 = 'GOLAN API: <strong>Failed</strong>';
                        }
                    } else {
                        $apiMsg2 = 'GOLAN API: <strong>Failed</strong>';
                    }
                    $apiMsg = $apiMsg2;
                }

                $todayDate       = date('Y-m-d H:i:s');

                $date2           = $lead->creationDate;
                $date            = strtotime($date2);
                $CreationDate    = date('Y-m-d H:i:s', $date);

                $diff            = ((strtotime($todayDate) - strtotime($CreationDate)) / 86400);

                $days_between   = ceil($diff);

                if ($campaign->campaignDesc == 'we4g') {

                    if ($days_between > 90) {

                        $we4g_ID = $_POST['we4g_ID'];

                        $r = freezeLineWE4G($we4g_ID, 0);

                        echo $r;
                    }

                    if ($days_between <= 90) {

                        $phone_number = $_POST['phone_number'];

                        $r = freezeLineWE4Gtemp($phone_number, 0);

                        echo $r;

                        $tempBlock = $this->general_model->updateRowById('phone_lines', 'leadId', $leadId, array('isTempBlock' => '1', 'lastUpdate' => date('Y-m-d H:i:s')));
                    }
                }

                $tt = (strtotime($lead->serviceEndDate) - time()) / 3600 / 24;
                if ($tt > 0) $tt = $tt - 1;
                $sp = round((floor($tt)) * ($lead->priceSupplier  / 30), 2);
                $op = round((floor($tt)) * ($lead->priceOperator  / 30), 2);
                if ($lead->status != 7) {
                    $this->refundCustomerLead($lead->adminId, $sp, $op, $leadId);
                    $result = $this->general_model->updateRowById('phone_lines', 'leadId', $leadId, array('serviceEndDate' => date('Y-m-d H:i:s'), 'lastUpdate' => date('Y-m-d H:i:s')));
                }
            }
            if ($newStatus == 4) {

                if ($campaign->campaignDesc == 'cellcom') {
                    $r = $this->cellcomSimStateChange($lead->phone, 0);
                    if ($r->result == 'SUCCESS') {
                        $apiMsg = ' - Cellcom API: <strong>' . $r->result . '</strong>';
                    } else {
                        echo json_encode(array('result' => false, 'out' => $r->result));
                        return;
                    }
                }

                if ($campaign->campaignDesc == 'hot') {
                    $r = hotManuiActions($lead->phone, 1); //1
                    if (strpos($r->mirreturn_message, 'Success') > -1) {
                        $apiMsg = ' - HOT API: <strong>' . $r->mirreturn_message . '</strong>';
                    } else {
                        echo json_encode(array('result' => false, 'out' => $r->mirreturn_message));
                        return;
                    }
                }

                if ($campaign->campaignDesc == 'golan') {
                    $r = golanRobotAction($lead->phone, 0);
                    $rd = json_decode($r);
                    if (isset($rd->task)) $apiMsg = ' - GOLAN API: <strong>OK</strong> ' . $rd->task;
                    else {
                        echo json_encode(array('result' => false, 'out' => $r));
                        return;
                    }
                }
            }
            if ($newStatus == 2) {
                $user = $this->general_model->getRowById('users', 'userId', getUserId());
                if ($user->userLevel == 2) {
                    echo json_encode(array('result' => 'אין הרשאה לבצע פעולה'));
                    return;
                }

                if ($campaign->campaignDesc == 'cellcom') {
                    $r = $this->cellcomSimStateChange($lead->phone, 1);
                    if ($r->result == 'SUCCESS') {
                        $apiMsg = ' - Cellcom API: <strong>' . $r->result . '</strong>';
                    } else {
                        echo json_encode(array('result' => false));
                        return;
                    }
                }

                if ($campaign->campaignDesc == 'hot') {
                    $r = hotManuiActions($lead->phone, 2);
                    if (strpos($r->mirreturn_message, 'Success') > -1) {
                        $apiMsg = ' - HOT API: <strong>' . $r->mirreturn_message . '</strong>';
                    } else {
                        echo json_encode(array('result' => false, 'out' => $r->mirreturn_message));
                        return;
                    }
                }

                if ($campaign->campaignDesc == 'golan') {
                    $phone = $lead->phone;
                    $r = getGolanSubId($phone);
                    if (!empty($r) && isset($r->msg->id)) {
                        $subId  = $r->msg->id;
                        $re     = GolanUnFreezeSub($subId);
                        $re2    = GolanCancelReportLostStolen($subId);
                        if (isset($re2->code) && $re2->code == 0) {
                            if (isset($re2->code) && $re2->code == 0 && isset($re->code) && $re->code == 0) {
                                $taskData['status'] = 30;
                            }
                            $apiMsg2 = 'GOLAN API: <strong>Success</strong>';
                        } else {
                            $apiMsg2 = 'GOLAN API: <strong>Failed</strong>';
                            echo json_encode(array('result' => false, 'out' => $apiMsg2));
                            return;
                        }
                        $re2 = GolanCancelReportLostStolen($subId);
                    } else {
                        $apiMsg2 = 'GOLAN API: <strong>Failed</strong>';
                    }
                    $apiMsg = $apiMsg2;
                }


                if ($campaign->campaignDesc == 'we4g') {

                    if ($lead->isTempBlock == "0") {

                        $we4g_ID = $_POST['we4g_ID'];

                        $r = freezeEndWE4G($we4g_ID, 0);

                        echo $r;
                    }

                    if ($lead->isTempBlock == "1") {

                        $phone_number = $_POST['phone_number'];

                        $r = removefreezeLineWE4Gtemp($phone_number, 0);

                        echo $r;

                        $tempBlock = $this->general_model->updateRowById('phone_lines', 'leadId', $leadId, array('isTempBlock' => '0', 'lastUpdate' => date('Y-m-d H:i:s')));
                    }
                }
            }
            if ($newStatus == 7) {
                $newPhone = '8' . substr($lead->phone, 1);
                $result1 = $this->general_model->updateRowById('phone_lines', 'leadId', $lead->leadId, array('phone' => $newPhone));
                $result2 = $this->general_model->updateRowById('leads', 'leadId', $lead->leadId, array('phone' => $newPhone));
            }
            if ($newStatus == 51) {
                if ($campaign->campaignDesc == 'pelephone') {
                    $status         = 'Temp-Suspended';
                    $change_status  = PelephoneUpdateProvisioningData($actionType = 'SIM_STATE_CHANGE', $phone = $lead->phone, $targetValue = $status);
                    if (!empty($change_status) && $change_status->result == 'SUCCESS') {
                        $apiMsg = ' PELEPHONE API: <span>Success</span>';
                    } else {
                        $apiMsg = ' PELEPHONE API: <span>Failed</span>';
                    }
                }
            }
            $result = $this->general_model->updateRowById('leads', 'leadId', $leadId, array('status' => $newStatus, 'lastUpdate' => date('Y-m-d H:i:s')));

            $newStatusText = $this->general_model->getTableWhere('lead_statuses', 'lsId', $newStatus);

            $cmtText = 'עדכון סטטוס <strong>' . $newStatusText[0]->title_he . '</strong>' . $apiMsg;
            $cmtData = array(
                'leadId'       => $leadId,
                'userId'       => getUserId(),
                'adminId'      => getAdminId(),
                'text'         => $cmtText,
                'creationDate' => date('Y-m-d H:i:s')
            );
            $result = $this->general_model->insertRow('lead_comments', $cmtData);
            $out .= '<tr class="cttr" rel="' . $result . '">
    			<td style="width: 25%;"><b>' . formatDateTime(date('Y-m-d H:i:s')) . '</b></td>
    			<td class="txt-color-blue" style="width: 20%;"><b>' . getUserName(getUserId()) . '</b></td>
    			<td>' . $cmtText . '</td>
                <td></td>
    		</tr>';
            if ($result) echo json_encode(array(
                'result' => true,
                'cmt'    => $out
            ));
            else echo json_encode(array('result' => false));
        } else {
            echo json_encode(array('result' => false));
        }
    }

    public function searchLeads()
    {
        $phrase = strip_tags(mysql_real_escape_string(trim($_POST['phrase'])));

        $ps = explode(' ', $phrase);
        $string = '';
        foreach ($ps as $p) {
            $string .= '' . $p . '';
        }
        $string = str_replace("-", "", $string);
        $result = array();
        $resultName = $this->db->query("SELECT l.firstname, l.lastname, l.phone, l.leadId, pl.customerId, UPPER(pl.lineProvider) as company FROM leads as l
                                                    INNER JOIN phone_lines as pl ON l.leadId = pl.leadId
                                                    WHERE (l.phone LIKE '%$string%'
                                                        OR l.phone2 LIKE '%$string%'
                                                        OR l.firstname LIKE '%$string%'
                                                        OR l.lastname LIKE '%$string%'
                                                        OR pl.sim LIKE '%$string%')

                                                    LIMIT 20  "); //AND adminId = '".getAdminId()."'
        //debug($this->db->last_query());
        $result = $resultName->result();

        //$result = array_merge(objectToArray($resultName), objectToArray($resultSku));
        echo json_encode($result);
    }

    function createCustomerPayment()
    {

        $data = $_POST['data'];
        $customerId = intval($data['customerId']);
        $uptoDate = date('Y-m-d H:i:s', strtotime(str_replace('/', '-', $data['uptoDate'])));
        $qty = $total = 0;
        $campaigns = $this->db->query("SELECT * FROM campaigns WHERE customerId = " . $customerId . " AND campaignId IN (" . implode(',', $data['campaigns']) . ") ORDER BY isActive DESC, creationDate DESC")->result();
        foreach ($campaigns as &$c) {
            $tc = $this->db->query("SELECT COUNT(leadId) as totalCompleted FROM leads_customers
                                    WHERE campaignId = " . $c->campaignId . " AND DATE(creationDate) <= DATE('" . $uptoDate . "') AND status = 30 AND customerId = " . $customerId . " AND isPaid = 0")->result();
            $c->totalCompleted = $tc[0]->totalCompleted;
            $qty += $tc[0]->totalCompleted;
            $total += ($tc[0]->totalCompleted * $c->campaignCustomerPrice);
        }
        //debug($campaigns);

        $paymentData = array(
            'customerId' => $customerId,
            'qty'        => $qty,
            'total'      => $total,
            'creationDate'  => date('Y-m-d H:i:s'),
            'lastUpdate'    => date('Y-m-d H:i:s')
        );
        $result = $this->general_model->insertRow('payments', $paymentData);
        if ($result) {
            $lcIds = $this->db->query("SELECT GROUP_CONCAT(lcId) as lcId FROM leads_customers
                                    WHERE campaignId IN (" . implode(',', $data['campaigns']) . ") AND DATE(creationDate) <= DATE('" . $uptoDate . "') AND status = 30 AND customerId = " . $customerId . " AND isPaid = 0")->row()->lcId;
            //debug($lcIds);
            $this->general_model->updateRowById('payments', 'paymentId', $result, array('lcIds' => $lcIds));
            $update = $this->db->query("UPDATE leads_customers SET isPaid = 1, lastUpdate = '" . date('Y-m-d H:i:s') . "'
                                    WHERE campaignId IN (" . implode(',', $data['campaigns']) . ") AND DATE(creationDate) <= DATE('" . $uptoDate . "') AND status = 30 AND customerId = " . $customerId . " AND isPaid = 0");

            echo json_encode(array('result' => true, ''));
        } else {
            echo json_encode(array('result' => false));
        }

        die();
    }

    function insertInvoicePayment()
    {

        $data = $_POST['data'];
        $ciId = intval($data['ciId']);
        $total = floatval(str_replace(',', '', $data['apTotal']));
        $cpDate = date('Y-m-d H:i:s', strtotime(str_replace('/', '-', $data['cpDate'])));

        $invoice = $this->general_model->getRowById('customers_invoices', 'ciId', $ciId);

        $paymentData = array(
            'userId'        => getUserId(),
            'customerId'    => $invoice->customerId,
            'adminId'       => getAdminId(),
            'title'         => 'credit_addon',
            'qty'           => 0,
            'total'         => $total * (-1),
            'comment'       => '',
            'ciId'          => $ciId,
            'isPaid'        => 1,
            'cpDate'        => $cpDate,
            'creationDate'  => date('Y-m-d H:i:s'),
            'lastUpdate'    => date('Y-m-d H:i:s')
        );

        $result = $this->general_model->insertRow('customers_payments', $paymentData);
        if ($result) {
            $this->general_model->updateRowById('customers_invoices', 'ciId', $ciId, array(
                'total' => $invoice->total - $total,
                'qty' => $invoice->qty + 1,
                'lastUpdate'    => date('Y-m-d H:i:s')
            ));

            echo json_encode(array('result' => true, ''));
        } else {
            echo json_encode(array('result' => false));
        }

        die();
    }

    function editCp()
    {
        //debug($_POST);
        $data = $_POST;
        $invId = intval($data['invId']);
        $paymentId = intval($data['paymentId']);

        $invest = $this->general_model->getRowById('investments', 'invId', $invId);
        $paymentData = (array)$this->general_model->getRowById('clients_payments', 'paymentId', $paymentId);

        $this->general_model->updateRowById('clients_payments', 'paymentId', $paymentId, array('type' => 'F'));
        $paymentData['type'] = 'R';
        unset($paymentData['paymentId']);

        $paymentData['cpDate'] = date('Y-m-d H:i:s');
        $paymentData['creationDate'] = date('Y-m-d H:i:s');
        $paymentData['lastUpdate'] = date('Y-m-d H:i:s');
        $paymentData['userId'] = getUserId();
        $paymentData['invId'] = $invId;
        $result = $this->general_model->insertRow('clients_payments', $paymentData);

        if ($result) {
            //Update invest lastupdate
            echo json_encode(array('result' => true));
        } else {
            echo json_encode(array('result' => false));
        }

        die();
    }

    // public function updateCampaign()
    // {
    //     //debug($_POST);
    //     $leadId = intval($_POST['leadId']);
    //     if ($leadId > 0) {
    //         $newCampaign = intval($_POST['newCampaign']);
    //         $campText = 'ללא שיוך';

    //         $lead = $this->general_model->getRowById('leads', 'leadId', $leadId);
    //         $customer = $this->general_model->getRowById('customers', 'customerId', $lead->adminId);
    //         $phone_line = $this->general_model->getRowById('phone_lines', 'leadId', $leadId);
    //         $newCampaignText = $this->general_model->getRowById('campaigns', 'campaignId', $newCampaign);
    //         $campText = $newCampaignText->campaignName;
    //         if (empty($lead)) {
    //             echo json_encode(array('result' => false));
    //             die();
    //         }

    //         $campaignPrices = reindex_by_key($this->general_model->getTableWhere('customer_campaigns_prices', 'customerId', $lead->adminId), 'campaignId');
    //         if (isset($campaignPrices[$newCampaign])) {
    //             $CPrice = $campaignPrices[$newCampaign]->customerPrice;
    //             $SPrice = $campaignPrices[$newCampaign]->price;
    //         } else {
    //             $CPrice = $newCampaignText->campaignCustomerPrice;
    //             $SPrice = $newCampaignText->campaignSupplierPrice;
    //             $OPrice = $newCampaignText->campaignOperatorPrice;
    //             if ($customer->parentId > 1) {
    //                 $SPrice = $newCampaignText->campaignSubSupplierPrice;
    //             }
    //         }
    //         if ($customer->parentId > 1) {
    //             $campaignPricesP = reindex_by_key($this->general_model->getTableWhere('customer_campaigns_prices', 'customerId', $customer->parentId), 'campaignId');
    //             if (isset($campaignPricesP[$newCampaign])) {
    //                 $OPrice = $campaignPricesP[$newCampaign]->price;
    //             } else {
    //                 $OPrice = $newCampaignText->campaignOperatorPrice;
    //             }
    //         } else {
    //             if (isset($campaignPrices[$newCampaign])) {
    //                 $OPrice = $campaignPrices[$newCampaign]->price;
    //             } else {
    //                 $OPrice = $newCampaignText->campaignOperatorPrice;
    //             }
    //         }

    //         //insert payment if price increase
    //         if ($phone_line->priceSupplier < $SPrice) {

    //             $first_date     = strtotime($phone_line->serviceEndDate);
    //             $first_dates    = date('d-m-Y', $first_date);
    //             $refundDateC    = date('d-m-Y');

    //             $dd = strtotime($first_dates);
    //             $ds = strtotime($refundDateC);

    //             $days_between = ceil(abs($dd - $ds) / 86400);

    //             $datediff = round((strtotime($phone_line->serviceEndDate) - time()) / (60 * 60 * 24));

    //             $total = round(($CPrice / 30) * $days_between, 2);

    //             $paymentDataCPrice = round((($CPrice - $phone_line->price) / 30) * $days_between, 2);
    //             $paymentData = array(
    //                 'title'       => 'package_upgrade_delta',
    //                 'total'         => ($paymentDataCPrice > 0) ? $paymentDataCPrice : 0,
    //                 //'type'          => $data['pType'],
    //                 'lpDate'        => date('Y-m-d H:i:s'),
    //                 'startDate'     => date('Y-m-d H:i:s'),
    //                 'endDate'       => date('Y-m-d H:i:s', strtotime($phone_line->serviceEndDate)),
    //                 'userId'        => getUserId(),
    //                 'customerId'    => $customer->customerId,
    //                 'leadId'        => $leadId,
    //                 'comment'       => 'עדכון חבילה <strong>' . $campText . '</strong>',
    //                 'creationDate'  => date('Y-m-d H:i:s'),
    //                 'lastUpdate'    => date('Y-m-d H:i:s')
    //             );
    //             //debug($paymentData);
    //             $this->general_model->insertRow('leads_payments', $paymentData);

    //             $paymentDataCpTotal = round((($SPrice - $phone_line->priceSupplier) / 30) * $days_between, 2);
    //             $paymentDataCp = array(
    //                 'title'       => 'package_upgrade_delta',
    //                 'total'         => ($paymentDataCpTotal > 0) ? $paymentDataCpTotal : 0,
    //                 'qty'           => 1,
    //                 'cpDate'        => date('Y-m-d H:i:s'),
    //                 'startDate'     => date('Y-m-d H:i:s'),
    //                 'endDate'       => date('Y-m-d H:i:s', strtotime($phone_line->serviceEndDate)),
    //                 'userId'        => getUserId(),
    //                 'customerId'    => $customer->customerId,
    //                 'adminId'       => $customer->parentId,
    //                 'comment'       => 'עדכון חבילה <strong>' . $campText . '</strong>',
    //                 'creationDate'  => date('Y-m-d H:i:s'),
    //                 'lastUpdate'    => date('Y-m-d H:i:s')
    //             );
    //             $resultCp = $this->general_model->insertRow('customers_payments', $paymentDataCp);
    //             $cplData = array('leadId' => $leadId, 'cpId' => $resultCp, 'price' => $SPrice - $phone_line->priceSupplier);
    //             $resultCpl = $this->general_model->insertRow('customers_payments_leads', $cplData);

    //             if (($customer->credits + $customer->creditsLimit) < ($SPrice - $phone_line->priceSupplier) && !$customer->allowDebt) {
    //             } else {
    //                 $r = $this->general_model->updateRowById('customers', 'customerId', $customer->customerId, array('credits' => ($customer->credits - round((($SPrice - $phone_line->priceSupplier) / 30) * $days_between, 2)), 'lastUpdate' => date('Y-m-d H:i:s')));
    //                 $r = $this->general_model->updateRowById('customers_payments', 'paymentId', $resultCp, array('isPaid' => 1));
    //             }

    //             if ($customer->parentId > 1) {
    //                 $cp = $this->general_model->getRowById('customers', 'customerId', $customer->parentId);

    //                 $paymentDataCoTotal = round((($OPrice - $phone_line->priceOperator) / 30) * $days_between, 2);
    //                 $paymentDataCo = array(
    //                     'title'       => 'package_upgrade_delta',
    //                     'total'         => ($paymentDataCoTotal > 0) ? $paymentDataCoTotal : 0,
    //                     'qty'           => 1,
    //                     'cpDate'        => date('Y-m-d H:i:s'),
    //                     'startDate'     => date('Y-m-d H:i:s'),
    //                     'endDate'       => date('Y-m-d H:i:s', strtotime($phone_line->serviceEndDate)),
    //                     'userId'        => getUserId(),
    //                     'customerId'    => $cp->customerId,
    //                     'adminId'       => 1,
    //                     'isPaid'        => 1,
    //                     'comment'       => 'עדכון חבילה <strong>' . $campText . '</strong>',
    //                     'creationDate'  => date('Y-m-d H:i:s'),
    //                     'lastUpdate'    => date('Y-m-d H:i:s')
    //                 );
    //                 $resultCo = $this->general_model->insertRow('customers_payments', $paymentDataCo);
    //                 $colData = array('leadId' => $leadId, 'cpId' => $resultCo, 'price' => $OPrice - $phone_line->priceOperator);
    //                 $resultCol = $this->general_model->insertRow('customers_payments_leads', $colData);

    //                 if (($cp->credits + $cp->creditsLimit) > ($OPrice - $phone_line->priceOperator)) {
    //                     $r = $this->general_model->updateRowById('customers', 'customerId', $cp->customerId, array('credits' => ($cp->credits - round((($OPrice - $phone_line->priceSupplier) / 30) * $days_between, 2)), 'lastUpdate' => date('Y-m-d H:i:s')));
    //                     //$r = $this->general_model->updateRowById('customers_payments', 'paymentId', $resultCo, array('isPaid' => 1));
    //                 }
    //             }
    //         }

    //         $r = $this->general_model->updateRowById('leads', 'leadId', $leadId, array('campaignId' => $newCampaign, 'lastUpdate' => date('Y-m-d H:i:s')));
    //         $r = $this->general_model->updateRowById('phone_lines', 'leadId', $leadId, array(
    //             'price' => $CPrice,
    //             'priceSupplier' => $SPrice,
    //             'priceOperator' => $OPrice,
    //             'lineProvider' => $newCampaignText->campaignDesc,
    //             'lastUpdate' => date('Y-m-d H:i:s')
    //         ));

    //         $cmtText = 'עדכון חבילה <strong>' . $campText . '</strong><br />חבילה קודמת: ' . getCampaignName($lead->campaignId);
    //         $cmtData = array(
    //             'leadId'        => $leadId,
    //             'adminId'       => getAdminId(),
    //             'userId'        => getUserId(),
    //             'text'          => $cmtText,
    //             'creationDate'  => date('Y-m-d H:i:s')
    //         );
    //         $result = $this->general_model->insertRow('lead_comments', $cmtData);
    //         $out = '<tr class="cttr" rel="' . $result . '">
    // 			<td style="width: 25%;"><b>' . formatDateTime(date('Y-m-d H:i:s')) . '</b></td>
    // 			<td class="txt-color-blue" style="width: 20%;"><b>' . getUserName(getUserId()) . '</b></td>
    // 			<td>' . $cmtText . '</td>
    //             <td></td>
    // 		</tr>';

    //         $emailTo = '';
    //         if ($newCampaignText->campaignDesc == 'cellcom') {
    //             $taskText = 'נא להחליף חבילת גלישה למנוי ' . $lead->phone . ' לחבילה: ' . $newCampaignText->campaignName;
    //         } elseif ($newCampaignText->campaignDesc == 'hot') {
    //             $taskText = 'נא להחליף חבילת גלישה למנוי ' . $lead->phone . ' לחבילה: ' . $newCampaignText->campaignName;
    //         } else {
    //             $taskText = 'נא להחליף חבילת גלישה למנוי ' . $lead->phone . ' לחבילה: ' . $newCampaignText->campaignName;
    //         }

    //         if ($newCampaignText->campaignDesc == 'we4g') {
    //             $change_package = We4GchangeSub($phone_number = $lead->phone, $package = $newCampaignText->apiCode);
    //             if (!empty($change_package) && $change_package != false) {
    //                 $result     = isset($change_package->desc) ? $change_package->desc : ' Unknown';
    //                 $apiResult  = 'WE4G PACKAGE API: ' . $result;
    //             } else {
    //                 $apiResult = 'WE4G PACKAGE API: FAILED';
    //             }
    //             $cmtData = array(
    //                 'leadId'       => $lead->leadId,
    //                 'adminId'      => $lead->adminId,
    //                 'userId'       => getUserId(),
    //                 'text'         => $apiResult,
    //                 'creationDate' => date('Y-m-d H:i:s')
    //             );
    //             $result = $this->general_model->insertRow('lead_comments', $cmtData);
    //         }

    //         if ($newCampaignText->campaignDesc == 'golan') {
    //             $r  = getGolanSubId($phone = $lead->phone);
    //             if (!empty($r) && isset($r->msg->id)) {
    //                 $subId      = $r->msg->id;
    //                 $offer_id   = $newCampaignText->apiCode;
    //                 $change_package = GolanChangeOffer($subId, $offer_id);
    //                 if (isset($change_package->code) && $change_package->code == 0) {
    //                     $apiResult  = 'GOLAN PACKAGE API: Success';
    //                 } else {
    //                     $apiResult = 'GOLAN PACKAGE API: FAILED';
    //                 }
    //             } else {
    //                 $apiResult = 'GOLAN PACKAGE API: FAILED - NO ID';
    //             }
    //             $cmtData = array(
    //                 'leadId'       => $lead->leadId,
    //                 'adminId'      => $lead->adminId,
    //                 'userId'       => getUserId(),
    //                 'text'         => $apiResult,
    //                 'creationDate' => date('Y-m-d H:i:s')
    //             );
    //             $result = $this->general_model->insertRow('lead_comments', $cmtData);
    //         }

    //         $mDate = date('Y-m-d');
    //         $taskData = array(
    //             'leadId' => isset($leadId) ? $leadId : 0,
    //             'userId' => getUserId(),
    //             'adminId' => getAdminId(),
    //             'attendsIds' => '',
    //             'customerId' => $lead->adminId,
    //             'campaignId' => 0,
    //             'subject' => 'שינוי חבילה',
    //             'text' => $taskText,
    //             'rating' => 3,
    //             'todoDate' => date('Y-m-d H:i:s'),
    //             'creationDate' => date('Y-m-d H:i:s'),
    //             'lastUpdate' => date('Y-m-d H:i:s'),
    //         );

    //         //debug($taskData);
    //         //$result = $this->general_model->insertRow('tasks', $taskData);
    //         /*
    //         if($emailTo != '') {
    //             $recipes = explode(',', $emailTo);
    //             foreach($recipes as $r) {
    //                 $mailData = array( 'content' => $taskText );
    //                 $message = $this->load->view('emails/taskMessage', $mailData, true);
    //                 sendEmail(trim($r), 'info@leadmecms.co.il', 'MT CMS', 'שינוי חבילה', $message, $cc = '', $bcc = '', $html = true);
    //             }
    //         }
    //     */
    //         if (isset($_POST['niyudCode']) && $_POST['niyudCode'] != '') {
    //             $r = ramilevyActivateSim($sim, $_POST['niyudCode']);
    //             $res = $r['status'] ? 'OK' : $r['result'];
    //             $apiMsg = 'Rami Levy API: <strong>' . $res . '</strong>';
    //             $dataA = array(
    //                 'leadId' => $leadId,
    //                 'userId'  => getUserId(),
    //                 'adminId'      => getAdminId(),
    //                 'text' => $apiMsg,
    //                 'creationDate'    => date('Y-m-d H:i:s'),
    //             );
    //             $this->general_model->insertRow('lead_comments', $dataA);
    //         }

    //         echo json_encode(array('result' => true, 'cmt'    => $out));
    //     } else {
    //         echo json_encode(array('result' => false));
    //     }
    //     die();
    // }

    function setLeadAlertDone()
    {
        $data = $_POST;
        $r = $this->general_model->updateRowById('leads_alerts', 'laId', $data['laId'], array('isDone' => 1, 'lastUpdate' => date('Y-m-d H:i:s')));
        if ($r) echo json_encode(array('result' => true, ''));
        else echo json_encode(array('result' => false));
    }

    function setCustomerToCampaign()
    {
        $data = $_POST['data'];
        $r = $this->general_model->updateRowById('campaigns', 'campaignId', $data['campaignId'], array('customerId' => $data['customerId']));
        if ($r) echo json_encode(array('result' => true, ''));
        else echo json_encode(array('result' => false));
    }

    function setPaymentPaid()
    {
        $data = $_POST['data'];
        $r = $this->general_model->updateRowById('payments', 'paymentId', $data['paymentId'], array('isPaid' => 1));
        if ($r) echo json_encode(array('result' => true, ''));
        else echo json_encode(array('result' => false));
    }

    function setCustomerPaymentPaid()
    {
        $data = $_POST;

        $cp = $this->general_model->getRowById('customers_payments', 'paymentId', $data['id']);
        $customer = $this->general_model->getRowById('customers', 'customerId', $cp->customerId);

        if (($customer->credits + $customer->creditsLimit) < $cp->total && !$customer->allowDebt) {
            echo json_encode(array('result' => false));
        } else {
            $result = $this->general_model->updateRowById($data['table'], $data['idColumn'], $data['id'], array($data['dataColumn'] => $data['value']));
            $r = $this->general_model->updateRowById('customers', 'customerId', $customer->customerId, array('credits' => ($customer->credits - $cp->total), 'lastUpdate' => date('Y-m-d H:i:s')));
            echo json_encode(array('result' => true, ''));
        }

        return;
    }

    function setLeadCustomerApproved()
    {
        $lcId = intval($_POST['lcId']);
        $r = $this->general_model->updateRowById('leads_customers', 'lcId', $lcId, array('status' => 30, 'lastUpdate' => date('Y-m-d H:i:s')));
        if ($r) {
            $lc = $this->general_model->getRowById('leads_customers', 'lcId', $lcId);
            $this->general_model->updateRowById('leads', 'leadId', $lc->leadId, array('status' => 30, 'lastUpdate' => date('Y-m-d H:i:s')));
            $cmtText = 'עדכון סטטוס <strong>הושלם</strong>';
            $cmtData = array(
                'leadId'       => $lc->leadId,
                'userId'       => getUserId(),
                'text'         => $cmtText,
                'creationDate' => date('Y-m-d H:i:s')
            );
            $result = $this->general_model->insertRow('lead_comments', $cmtData);
            $this->general_model->updateRowById('leads_suppliers', 'leadId', $lc->leadId, array('status' => 30, 'lastUpdate' => date('Y-m-d H:i:s')));
            echo json_encode(array('result' => true));
        } else {
            echo json_encode(array('result' => false));
        }
    }

    function cancelLeadCustomer()
    {
        $lcId = intval($_POST['lcId']);
        $lc = $this->general_model->getRowById('leads_customers', 'lcId', $lcId);
        $this->general_model->updateRowById('leads_suppliers', 'leadId', $lc->leadId, array('status' => 2, 'lastUpdate' => date('Y-m-d H:i:s')));
        $r = $this->general_model->updateRowById('leads', 'leadId', $lc->leadId, array('status' => 2, 'lastUpdate' => date('Y-m-d H:i:s')));
        $r = $this->general_model->deleteRowById('leads_customers', 'lcId', $lcId);
        if ($r) echo json_encode(array('result' => true));
        else echo json_encode(array('result' => false));
        die();
    }

    public function getCallerReportData()
    {
        return false;
        /*
        $data = $_POST['data'];
        $userId = intval($data['userId']);
        $data['start'] = str_replace('/', '-', $data['start']);
        $data['end'] = str_replace('/', '-', $data['end']);
        $start = date('Y-m-d 00:00:00', strtotime($data['start']));
        $end = date('Y-m-d 23:59:59', strtotime($data['end']));
        $leads = $this->db->query("
        SELECT COUNT(*) AS leads, creationDate FROM lead_comments
                                                WHERE (creationDate BETWEEN '$start' AND '$end') AND userId = ".$userId."
                                                AND text LIKE '%ליד בהמתנה%'
                                                GROUP BY DATE(creationDate)
                                                ORDER BY creationDate ASC")->result();//GROUP BY EXTRACT(DAY FROM creationDate)
        foreach($leads as $o) {
            $os[] = array(strtotime($o->creationDate) * 1000, intval($o->leads));
        }
        //debug($os);
        echo json_encode( array( 'leads' => $os ) );
        */
    }

    public function getLeadComments()
    {
        //debug($_POST);
        $lc = $this->general_model->getRowById('leads', 'leadId', intval($_POST['leadId']));
        if ($lc->adminId == getAdminId()) {
            $result = $this->db->query("SELECT * FROM lead_comments WHERE leadId = '" . $_POST['leadId'] . "' ORDER BY creationDate DESC LIMIT 3")->result();
            $out = '';
            if (count($result) > 0) {
                $out .= '';
                foreach ($result as $lcc) {
                    $out .= '<p>' . $lcc->text . ' / ' . getUserName($lcc->userId) . '<br /><small>' . formatDateTime($lcc->creationDate) . '</small></p>';
                }
                $out .= '<hr />';
            }
            echo json_encode(array('result' => true, 'out' => $out));
        } else {
            echo json_encode(array('result' => false));
        }
    }

    public function getDataForLeadsTable()
    {

        /*
    	 * Script:    DataTables server-side script for PHP and MySQL
    	 * Copyright: 2010 - Allan Jardine
    	 * License:   GPL v2 or BSD (3-point)
    	 */

        /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    	 * Easy set variables
    	 */

        /* Array of database columns which should be read and sent back to DataTables. Use a space where
    	 * you want to insert a non-database field (for example a counter or static image)
    	 */
        //$aColumns = array( 'lcId', 'firstname', 'lastname', 'phone', 'email', 'status', 'lastUpdate' );
        $aColumns = array('leadId', 'firstname', 'phone', 'adminId', 'status', 'lastUpdate');
        $qColumns = array('leadId', 'firstname', 'phone', 'adminId', 'status', 'lastUpdate');
        /* Indexed column (used for fast and accurate table cardinality) */
        $sIndexColumn = "leadId";
        $bindings = array();
        /* DB table to use */
        $sTable = "leads";

        /*
    	 * Paging
    	 */
        $limit = "";
        if (isset($_GET['start']) && $_GET['length'] != -1) {
            $limit = "LIMIT " . intval($_GET['start']) . ", " . intval($_GET['length']);
        }


        /*
    	 * Ordering
    	 */
        $order = "";
        if (isset($_GET['order']) && count($_GET['order'])) {
            $orderBy = array();

            for ($i = 0, $ien = count($_GET['order']); $i < $ien; $i++) {
                // Convert the column index into the column data property
                $columnIdx = intval($_GET['order'][$i]['column']);
                $requestColumn = $_GET['columns'][$columnIdx];

                $columnIdx = $qColumns[$requestColumn['data']];
                $column = $columnIdx;

                if ($requestColumn['orderable'] == 'true') {
                    $dir = $_GET['order'][$i]['dir'] === 'asc' ?
                        'ASC' :
                        'DESC';

                    $orderBy[] = '`' . $column . '` ' . $dir;
                }
            }

            $order = 'ORDER BY ' . implode(', ', $orderBy);
        }


        /*
    	 * Filtering
    	 * NOTE this does not match the built-in DataTables filtering which does it
    	 * word by word on any field. It's possible to do here, but concerned about efficiency
    	 * on very large tables, and MySQL's regex functionality is very limited
    	 */
        $where = "";
        $globalSearch = array();
        $columnSearch = array();

        if (isset($_GET['search']) && $_GET['search']['value'] != '') {
            $str = $_GET['search']['value'];

            for ($i = 0, $ien = count($_GET['columns']); $i < $ien; $i++) {
                $requestColumn = $_GET['columns'][$i];
                $columnIdx = $qColumns[$requestColumn['data']];
                $column = $columnIdx;

                if ($requestColumn['searchable'] == 'true') {
                    //$binding = self::bind( $bindings, '%'.$str.'%', PDO::PARAM_STR );
                    //$globalSearch[] = "`".$column."` LIKE ".$binding;
                    $globalSearch[] = "" . $column . " LIKE '%" . $str . "%'";
                }
            }
        }

        // Individual column filtering
        for ($i = 0, $ien = count($_GET['columns']); $i < $ien; $i++) {
            $requestColumn = $_GET['columns'][$i];
            $columnIdx = $qColumns[$requestColumn['data']];
            $column = $columnIdx;

            $str = $requestColumn['search']['value'];

            if ($requestColumn['searchable'] == 'true' && $str != '') {
                $binding = self::bind($bindings, '%' . $str . '%', PDO::PARAM_STR);
                $columnSearch[] = "`" . $column . "` LIKE " . $binding;
            }
        }

        // Combine the filters into a single string
        $where = '';

        if (count($globalSearch)) {
            $where = '(' . implode(' OR ', $globalSearch) . ')';
        }

        if (count($columnSearch)) {
            $where = $where === '' ?
                implode(' AND ', $columnSearch) :
                $where . ' AND ' . implode(' AND ', $columnSearch);
        }

        if ($where !== '') {
            $where = 'WHERE ' . $where;
        }

        /*
    	 * SQL queries
    	 * Get data to display
    	 */
        $sQuery = "
    		SELECT SQL_CALC_FOUND_ROWS leadId, CONCAT(firstname, ' ', lastname) as firstname, phone, adminId, status, lastUpdate
            FROM $sTable
            $where
    		$order
    		$limit
    	";
        //debug($sQuery);
        //$rResult = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
        $rResult = $this->db->query($sQuery);

        /* Data set length after filtering */
        $sQuery = "
    		SELECT FOUND_ROWS()
    	";
        //$rResultFilterTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
        $rResultFilterTotal = $this->db->query($sQuery);
        //$aResultFilterTotal = mysql_fetch_array($rResultFilterTotal);
        $aResultFilterTotal = $rResultFilterTotal->result();
        $iFilteredTotal = objectToArray($aResultFilterTotal[0]);

        /* Total data set length */
        $sQuery = "
    		SELECT COUNT(" . $sIndexColumn . ")
    		FROM   $sTable
    	";
        //$rResultTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
        $rResultTotal = $this->db->query($sQuery);
        //$aResultTotal = mysql_fetch_array($rResultTotal);
        $aResultTotal = $rResultTotal->result();
        $iTotal = objectToArray($aResultTotal[0]);

        /*
    	 * Output
    	 *//*
    	$output = array(
    		"sEcho" => intval($_GET['draw']),
    		"iTotalRecords" => $iTotal['COUNT('.$sIndexColumn.')'],
    		"iTotalDisplayRecords" => $iFilteredTotal['FOUND_ROWS()'],
    		"aaData" => array()
    	);*/
        $output = array(
            "draw"            => intval($_GET['draw']),
            "recordsTotal"    => intval($iTotal['COUNT(' . $sIndexColumn . ')']),
            "recordsFiltered" => intval($iFilteredTotal['FOUND_ROWS()']),
            "data"            => array()
        );

        //while ( $aRow = mysql_fetch_array( $rResult ) )
        $r = $rResult->result();

        $statuses = $this->general_model->getLeadStatuses();
        $customers = reindex_by_key($this->db->query("SELECT customerId, customerName FROM customers")->result(), 'customerId');
        //debug($r);
        foreach ($r as $aRow) {
            $aRow = objectToArray($aRow);
            $row = array();

            for ($i = 0; $i < count($aColumns); $i++) {
                $aRow['relatedCustomers'] = $this->leads_model->getLeadRelatedCustomers($aRow['leadId']);
                if ($aColumns[$i] == "leadId") {
                    $row[] = '<label class="checkbox" style="margin-left: 0;">
                              <input class="leadCB" type="checkbox" name="selectedLeads[]" value="' . $aRow['leadId'] . '" />
							  <i></i> </label>';
                } else if ($aColumns[$i] == "status") {
                    //status label
                    $row[] = '<span class="label status" style="text-align: center; color: #fff; background-color: ' . $statuses[$aRow['status'] - 1]->lsColor . '">' . $statuses[$aRow['status'] - 1]->title_he . '</span>';
                } else if ($aColumns[$i] == 'lastUpdate') {
                    if ($aRow[$aColumns[$i]] == '0000-00-00 00:00:00') $row[] = formatDateTime($aRow['creationDate']);
                    else $row[] = formatDateTime($aRow[$aColumns[$i]]);
                } else if ($aColumns[$i] == "adminId") {
                    if (isset($customers[$aRow[$aColumns[$i]]]))
                        $row[] = '<span class="label label-primary" style="text-align: center!important; color: #fff;">' . $customers[$aRow[$aColumns[$i]]]->customerName . '</span>';
                    else $row[] = '';
                } else {
                    /* General output */
                    $row[] = $aRow[$aColumns[$i]];
                }
            }
            //$row[] = '<a class="btn btn-primary btn-xs" href="javascript: leadToCustomer('.$aRow['leadId'].');"><i class="fa fa-user"></i> שיוך ללקוח</a><a class="btn btn-default btn-xs" href="javascript: editLead('.$aRow['leadId'].');"><i class="fa fa-cog"></i> עריכה</a>';
            $output['data'][] = $row;
        }
        //debug($output);
        echo json_encode($output);
    }

    public function getDataForLinesTable()
    {

        /*
    	 * Script:    DataTables server-side script for PHP and MySQL
    	 * Copyright: 2010 - Allan Jardine
    	 * License:   GPL v2 or BSD (3-point)
    	 */

        /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    	 * Easy set variables
    	 */

        /* Array of database columns which should be read and sent back to DataTables. Use a space where
    	 * you want to insert a non-database field (for example a counter or static image)
    	 */
        $sTable = "phone_lines";
        //$aColumns = array( 'lcId', 'firstname', 'lastname', 'phone', 'email', 'status', 'lastUpdate' );
        $aColumns = array('lineId', 'phone', 'sim', 'customerId', 'lineProvider', 'lineGb', 'firstname', 'isActive', 'lastUpdate');
        $qColumns = array('lineId', $sTable . '.phone', 'sim', 'customerId', 'lineProvider', 'lineGb', 'firstname', 'isActive', $sTable . '.lastUpdate');
        /* Indexed column (used for fast and accurate table cardinality) */
        $sIndexColumn = "lineId";
        $bindings = array();
        /* DB table to use */


        /*
    	 * Paging
    	 */
        $limit = "";
        if (isset($_GET['start']) && $_GET['length'] != -1) {
            $limit = "LIMIT " . intval($_GET['start']) . ", " . intval($_GET['length']);
        }


        /*
    	 * Ordering
    	 */
        $order = "";
        if (isset($_GET['order']) && count($_GET['order'])) {
            $orderBy = array();

            for ($i = 0, $ien = count($_GET['order']); $i < $ien; $i++) {
                // Convert the column index into the column data property
                $columnIdx = intval($_GET['order'][$i]['column']);
                $requestColumn = $_GET['columns'][$columnIdx];

                $columnIdx = $qColumns[$requestColumn['data']];
                $column = $columnIdx;

                if ($requestColumn['orderable'] == 'true') {
                    $dir = $_GET['order'][$i]['dir'] === 'asc' ?
                        'ASC' :
                        'DESC';

                    $orderBy[] = '`' . str_replace('phone_lines.', '', $column) . '` ' . $dir;
                }
            }

            $order = 'ORDER BY ' . implode(', ', $orderBy);
        }


        /*
    	 * Filtering
    	 * NOTE this does not match the built-in DataTables filtering which does it
    	 * word by word on any field. It's possible to do here, but concerned about efficiency
    	 * on very large tables, and MySQL's regex functionality is very limited
    	 */
        $where = "";
        $globalSearch = array();
        $columnSearch = array();

        if (isset($_GET['search']) && $_GET['search']['value'] != '') {
            $str = $_GET['search']['value'];

            for ($i = 0, $ien = count($_GET['columns']); $i < $ien; $i++) {
                $requestColumn = $_GET['columns'][$i];
                $columnIdx = $qColumns[$requestColumn['data']];
                $column = $columnIdx;

                if ($requestColumn['searchable'] == 'true') {
                    //$binding = self::bind( $bindings, '%'.$str.'%', PDO::PARAM_STR );
                    //$globalSearch[] = "`".$column."` LIKE ".$binding;
                    $globalSearch[] = "" . $column . " LIKE '%" . $str . "%'";
                }
            }
        }

        // Individual column filtering
        for ($i = 0, $ien = count($_GET['columns']); $i < $ien; $i++) {
            $requestColumn = $_GET['columns'][$i];
            $columnIdx = $qColumns[$requestColumn['data']];
            $column = $columnIdx;

            $str = $requestColumn['search']['value'];

            if ($requestColumn['searchable'] == 'true' && $str != '') {
                $binding = self::bind($bindings, '%' . $str . '%', PDO::PARAM_STR);
                $str = str_replace("^", "", $str);
                $str = str_replace("$", "", $str);
                $columnSearch[] = "`" . $column . "` LIKE " . "'" . $str . "'";
            }
        }

        // Combine the filters into a single string
        $where = '';

        if (count($globalSearch)) {
            $where = '(' . implode(' OR ', $globalSearch) . ')';
        }

        if (count($columnSearch)) {
            $where = $where === '' ?
                implode(' AND ', $columnSearch) :
                $where . ' AND ' . implode(' AND ', $columnSearch);
        }

        if ($where !== '') {
            $where = 'WHERE ' . $where;
        }

        /*
    	 * SQL queries
    	 * Get data to display
    	 */

        $sQuery = "
    		SELECT SQL_CALC_FOUND_ROWS $sTable.lineId, CONCAT(leads.firstname, ' ', leads.lastname) as firstname, $sTable.phone, $sTable.sim, $sTable.customerId, $sTable.lineProvider, $sTable.lineGb, $sTable.isActive, $sTable.lastUpdate
            FROM $sTable
            LEFT JOIN leads ON $sTable.leadId = leads.leadId
            $where
    		$order
    		$limit
    	";
        //debug($sQuery);
        //$rResult = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
        $rResult = $this->db->query($sQuery);

        /* Data set length after filtering */
        $sQuery = "
    		SELECT FOUND_ROWS()
    	";
        //$rResultFilterTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
        $rResultFilterTotal = $this->db->query($sQuery);
        //$aResultFilterTotal = mysql_fetch_array($rResultFilterTotal);
        $aResultFilterTotal = $rResultFilterTotal->result();
        $iFilteredTotal = objectToArray($aResultFilterTotal[0]);

        /* Total data set length */
        $sQuery = "
    		SELECT COUNT(" . $sIndexColumn . ")
    		FROM   $sTable
    	";
        //$rResultTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
        $rResultTotal = $this->db->query($sQuery);
        //$aResultTotal = mysql_fetch_array($rResultTotal);
        $aResultTotal = $rResultTotal->result();
        $iTotal = objectToArray($aResultTotal[0]);

        /*
    	 * Output
    	 *//*
    	$output = array(
    		"sEcho" => intval($_GET['draw']),
    		"iTotalRecords" => $iTotal['COUNT('.$sIndexColumn.')'],
    		"iTotalDisplayRecords" => $iFilteredTotal['FOUND_ROWS()'],
    		"aaData" => array()
    	);*/
        $output = array(
            "draw"            => intval($_GET['draw']),
            "recordsTotal"    => intval($iTotal['COUNT(' . $sIndexColumn . ')']),
            "recordsFiltered" => intval($iFilteredTotal['FOUND_ROWS()']),
            "data"            => array()
        );

        //while ( $aRow = mysql_fetch_array( $rResult ) )
        $r = $rResult->result();

        $statuses = $this->general_model->getLeadStatuses();
        $customers = reindex_by_key($this->db->query("SELECT customerId, customerName FROM customers")->result(), 'customerId');
        //debug($r);
        foreach ($r as $aRow) {
            $aRow = objectToArray($aRow);
            $row = array();

            for ($i = 0; $i < count($aColumns); $i++) {
                if ($aColumns[$i] == "lineId") {
                    $row[] = '<label class="checkbox" style="margin-left: 0;">
                              <input class="lineCB" type="checkbox" name="selectedLines[]" value="' . $aRow['lineId'] . '" />
							  <i></i> </label>';
                } else if ($aColumns[$i] == "isActive") {
                    //status label
                    if ($aRow['isActive']) {
                        $row[] = '<span class="label status" style="width: auto; text-align: center; font-weight: bold; color: #fff; background-color: #5cb85c; padding: 1px 6px; float: right; margin: 0 2px;">פעיל</span>';
                    } else {
                        $row[] = '<span class="label status" style="width: auto; text-align: center; font-weight: bold; color: #fff; background-color: #d9534f; padding: 1px 6px; float: right; margin: 0 2px;">לא פעיל</span>';
                    }
                } else if ($aColumns[$i] == 'lastUpdate') {
                    if ($aRow[$aColumns[$i]] == '0000-00-00 00:00:00') $row[] = formatDateTime($aRow['creationDate']);
                    else $row[] = formatDateTime($aRow[$aColumns[$i]]);
                } else if ($aColumns[$i] == "customerId") {
                    if ($aRow[$aColumns[$i]] && isset($customers[$aRow[$aColumns[$i]]]))
                        $row[] = '<span class="label label-primary" style="text-align: center!important; color: #fff;">' . $customers[$aRow[$aColumns[$i]]]->customerName . '</span>';
                    else $row[] = '';
                } else {
                    /* General output */
                    $row[] = $aRow[$aColumns[$i]];
                }
            }
            //$row[] = '<a class="btn btn-primary btn-xs" href="javascript: leadToCustomer('.$aRow['leadId'].');"><i class="fa fa-user"></i> שיוך ללקוח</a><a class="btn btn-default btn-xs" href="javascript: editLead('.$aRow['leadId'].');"><i class="fa fa-cog"></i> עריכה</a>';
            $output['data'][] = $row;
        }
        //debug($output);
        echo json_encode($output);
    }

    public function getDataForTasksTable()
    {

        /*
    	 * Script:    DataTables server-side script for PHP and MySQL
    	 * Copyright: 2010 - Allan Jardine
    	 * License:   GPL v2 or BSD (3-point)
    	 */

        /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    	 * Easy set variables
    	 */

        /* Array of database columns which should be read and sent back to DataTables. Use a space where
    	 * you want to insert a non-database field (for example a counter or static image)
    	 */
        $sTable = "tasks";
        //$aColumns = array( 'lcId', 'firstname', 'lastname', 'phone', 'email', 'status', 'lastUpdate' );
        $aColumns = array('taskId', 'creationDate', 'phone', 'campaignDesc', 'campaignName', 'customerId', 'subject', 'text', 'status1', 'status', 'lastUpdate');
        $qColumns = array('taskId', $sTable . '.creationDate', 'phone', 'campaignDesc', 'campaignName', $sTable . '.customerId', 'subject', 'text', 'isDone', $sTable . '.status', $sTable . '.lastUpdate');
        /* Indexed column (used for fast and accurate table cardinality) */
        $sIndexColumn = "taskId";
        $bindings = array();
        /* DB table to use */


        /*
    	 * Paging
    	 */
        $limit = "";
        if (isset($_GET['start']) && $_GET['length'] != -1) {
            $limit = "LIMIT " . intval($_GET['start']) . ", " . intval($_GET['length']);
        }


        /*
    	 * Ordering
    	 */
        $order = "";
        if (isset($_GET['order']) && count($_GET['order'])) {
            $orderBy = array();

            for ($i = 0, $ien = count($_GET['order']); $i < $ien; $i++) {
                // Convert the column index into the column data property
                $columnIdx = intval($_GET['order'][$i]['column']);
                $requestColumn = $_GET['columns'][$columnIdx];

                $columnIdx = $qColumns[$requestColumn['data']];
                $column = $columnIdx;

                if ($requestColumn['orderable'] == 'true') {
                    $dir = $_GET['order'][$i]['dir'] === 'asc' ?
                        'ASC' :
                        'DESC';

                    $orderBy[] = '`' . str_replace('tasks.', '', $column) . '` ' . $dir;
                }
            }

            $order = 'ORDER BY ' . implode(', ', $orderBy);
        }


        /*
    	 * Filtering
    	 * NOTE this does not match the built-in DataTables filtering which does it
    	 * word by word on any field. It's possible to do here, but concerned about efficiency
    	 * on very large tables, and MySQL's regex functionality is very limited
    	 */
        $where = "";
        $globalSearch = array();
        $columnSearch = array();

        if (isset($_GET['search']) && $_GET['search']['value'] != '') {
            $str = $_GET['search']['value'];

            for ($i = 0, $ien = count($_GET['columns']); $i < $ien; $i++) {
                $requestColumn = $_GET['columns'][$i];
                $columnIdx = $qColumns[$requestColumn['data']];
                $column = $columnIdx;

                if ($requestColumn['searchable'] == 'true') {
                    //$binding = self::bind( $bindings, '%'.$str.'%', PDO::PARAM_STR );
                    //$globalSearch[] = "`".$column."` LIKE ".$binding;

                    if ($column == 'tasks.creationDate' or $column == 'tasks.lastUpdate') {
                        $column = 'CAST(' . $column . ' AS CHAR)';
                    }


                    $globalSearch[] = "" . str_replace('tasks.', '', $column) . " LIKE '%" . $str . "%'";
                }
            }
        }

        // Individual column filtering
        for ($i = 0, $ien = count($_GET['columns']); $i < $ien; $i++) {
            $requestColumn = $_GET['columns'][$i];
            $columnIdx = $qColumns[$requestColumn['data']];
            $column = $columnIdx;

            $str = $requestColumn['search']['value'];

            if ($requestColumn['searchable'] == 'true' && $str != '') {
                //$binding = self::bind( $bindings, '%'.$str.'%', PDO::PARAM_STR );
                if ($column == 'tasks.creationDate' or $column == 'tasks.lastUpdate') {
                    $column = 'CAST(' . $column . ' AS CHAR)';
                }
                $cond = str_replace('tasks.', '', $column) == 'status' ? '= ' . $str : 'LIKE \'%' . $str . '%\'';
                $columnSearch[] = "`" . str_replace('tasks.', '', $column) . "` $cond ";
            }
        }

        // Combine the filters into a single string
        $where = '';

        if (count($globalSearch)) {
            $where = '(' . implode(' OR ', $globalSearch) . ')';
        }

        if (count($columnSearch)) {
            $where = $where === '' ?
                implode(' AND ', $columnSearch) :
                $where . ' AND ' . implode(' AND ', $columnSearch);
        }

        if ($where !== '') {
            $where = 'WHERE' . $where;
        }

        /*
    	 * SQL queries
    	 * Get data to display
    	 */

        if (empty($where)) {

            $sQuery = "
                SELECT SQL_CALC_FOUND_ROWS $sTable.*, c.campaignDesc, c.campaignName, l.phone, $sTable.status as status
                FROM $sTable
                LEFT JOIN (SELECT leadId, campaignId, phone FROM leads) as l ON $sTable.leadId = l.leadId
                LEFT JOIN (SELECT campaignId, campaignDesc, campaignName FROM campaigns) as c ON c.campaignId = l.campaignId
                WHERE status IN (1,6,31,32)
                $order
                $limit
            ";
        } else {

            $sQuery = "
                SELECT SQL_CALC_FOUND_ROWS $sTable.*, c.campaignDesc, c.campaignName, l.phone, $sTable.status as status
                FROM $sTable
                LEFT JOIN (SELECT leadId, campaignId, phone FROM leads) as l ON $sTable.leadId = l.leadId
                LEFT JOIN (SELECT campaignId, campaignDesc, campaignName FROM campaigns) as c ON c.campaignId = l.campaignId
                $where
                $order
                $limit
            ";
        }


        //debug($sQuery);
        //$rResult = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
        $rResult = $this->db->query($sQuery);

        /* Data set length after filtering */
        $sQuery = "
    		SELECT FOUND_ROWS()
    	";
        //$rResultFilterTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
        $rResultFilterTotal = $this->db->query($sQuery);
        //$aResultFilterTotal = mysql_fetch_array($rResultFilterTotal);
        $aResultFilterTotal = $rResultFilterTotal->result();
        $iFilteredTotal = objectToArray($aResultFilterTotal[0]);

        /* Total data set length */
        $sQuery = "
    		SELECT COUNT(" . $sIndexColumn . ")
    		FROM   $sTable
    	";
        //$rResultTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
        $rResultTotal = $this->db->query($sQuery);
        //$aResultTotal = mysql_fetch_array($rResultTotal);
        $aResultTotal = $rResultTotal->result();
        $iTotal = objectToArray($aResultTotal[0]);

        /*
    	 * Output
    	 *//*
    	$output = array(
    		"sEcho" => intval($_GET['draw']),
    		"iTotalRecords" => $iTotal['COUNT('.$sIndexColumn.')'],
    		"iTotalDisplayRecords" => $iFilteredTotal['FOUND_ROWS()'],
    		"aaData" => array()
    	);*/
        $output = array(
            "draw"            => intval($_GET['draw']),
            "recordsTotal"    => intval($iTotal['COUNT(' . $sIndexColumn . ')']),
            "recordsFiltered" => intval($iFilteredTotal['FOUND_ROWS()']),
            "data"            => array()
        );

        //while ( $aRow = mysql_fetch_array( $rResult ) )
        $r = $rResult->result();

        $statuses = reindex_by_key($this->general_model->getLeadStatuses(), 'lsId');
        $customers = reindex_by_key($this->db->query("SELECT customerId, customerName FROM customers")->result(), 'customerId');
        //debug($statuses);
        foreach ($r as $aRow) {

            $aRow = objectToArray($aRow);
            $row = array();

            for ($i = 0; $i < count($aColumns); $i++) {
                $lead           = $this->general_model->getRowById('leads', 'leadId', $aRow['leadId']);
                $phone          = $this->general_model->getRowById('phone_lines', 'leadId', $aRow['leadId']);
                //debug($aColumns);
                if ($aColumns[$i] == "taskId") {
                    if ($this->session->userdata('userData')->userLevel == 1) {
                        $row[] = '<label class="checkbox" style="margin-left: 0;">
                                  <input class="taskCB" type="checkbox" name="selectedTasks[]" value="' . $aRow['taskId'] . '" />
    							  <i></i> </label>';
                    } else {
                        $row[] = '<label class="checkbox" style="margin-left: 0;opacity:0;">
                                  <input class="taskCB" type="checkbox" name="selectedTasks[]" value="' . $aRow['taskId'] . '" />
    							  <i></i> </label>';
                    }
                } else if ($aColumns[$i] == "status1") {
                    //status label
                    $row[] = '<span class="label status" style="text-align: center; color: #fff; background-color: ' . $statuses[$aRow['status']]->lsColor . '">' . $statuses[$aRow['status']]->title_he . '</span>';
                } else if ($aColumns[$i] == "status") {
                    //status label
                    $row[] = '<span class="label status" style="text-align: center; color: #fff; background-color: ' . $statuses[$aRow['status']]->lsColor . '">' . $statuses[$aRow['status']]->title_he . '</span>';
                    //$row[] = $aRow['status'];
                } else if ($aColumns[$i] == 'creationDate') {
                    if ($aRow[$aColumns[$i]] == '0000-00-00 00:00:00') $row[] = formatDateTime($aRow['creationDate']);
                    else $row[] = formatDateTime($aRow[$aColumns[$i]]) . '<br />' . time_ago(strtotime($aRow[$aColumns[$i]]));
                } else if ($aColumns[$i] == "customerId") {
                    if (isset($customers[$aRow[$aColumns[$i]]]))
                        $row[] = '<span class="label label-primary" style="text-align: center!important; color: #fff;">' . $customers[$aRow[$aColumns[$i]]]->customerName . '</span>';
                    else $row[] = '';
                } else if ($aColumns[$i] == "lastUpdate") {
                    $button1 = '<button class="btn btn-xs btn-danger pull-right margin-top-10" onclick="deleteTask(' . $aRow['taskId'] . ');" style="margin-left: 10px;"><i class="fa fa-trash-o"></i></button>';
                    $button2 = '<button class="check_status btn btn-xs btn-info pull-right margin-top-10" rel-taskId="' . $aRow['taskId'] . '" style="margin-left: 10px;"><i class="fa fa-link"></i></button>';
                    $row[] = $button2 . $button1;
                } else if ($aColumns[$i] == "text") {
                    $subject = $aRow[$aColumns[$i - 1]];
                    if ($subject == 'בקשה לחיבור מספר' && !empty($phone)) {
                        $new_text       = 'בקשה לחיבור מספר ';
                        $sim            = ' <br/> SIM : ' . $phone->sim . ' <br/>';
                        $text_to_show   = $new_text . $phone->phone . $sim;
                    } else if ($subject == 'בקשה לניוד מספר' && !empty($phone)) {
                        $new_text       = 'בקשה לניוד מספר ';
                        $sim            = ' SIM : ' . $phone->sim . ' <br/>';
                        $text_to_show   = $new_text . $phone->phone . $sim;
                    } else {
                        $text_to_show = $aRow[$aColumns[$i]];
                    }
                    $row[] = $text_to_show;
                } else {
                    /* General output */
                    $row[] = $aRow[$aColumns[$i]];
                }
            }

            $output['data'][] = $row;
        }
        //debug($output);
        echo json_encode($output);
    }

    public function getDataForTable1()
    {

        // DB table to use
        $table = 'leads';

        // Table's primary key
        $primaryKey = 'leadId';

        // Array of database columns which should be read and sent back to DataTables.
        // The `db` parameter represents the column name in the database, while the `dt`
        // parameter represents the DataTables column identifier. In this case simple
        // indexes
        $columns = array(
            array('db' => 'leadId',   'dt' => 0),
            array('db' => 'firstname', 'dt' => 1),
            array('db' => 'lastname',  'dt' => 1),
            array('db' => 'phone',   'dt' => 2),
            array('db' => 'email',   'dt' => 3),
            array('db' => 'address',   'dt' => 4),
            array('db' => 'status',     'dt' => 5),
            array(
                'db'        => 'lastUpdate',
                'dt'        => 6,
                /*
        		'formatter' => function( $d, $row ) {
        			return '$'.number_format($d);
        		}*/
            )
        );
        $this->load->database();
        // SQL server connection information
        $sql_details = array(
            'user' => $this->db->username,
            'pass' => $this->db->password,
            'db'   => $this->db->database,
            'host' => $this->db->hostname
        );


        /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
         * If you just want to use the basic configuration for DataTables with PHP
         * server-side, there is no need to edit below this line.
         */

        require('ssp.class.php');

        echo json_encode(
            SSP::simple($_GET, $sql_details, $table, $primaryKey, $columns)
        );
    }

    /**
     * Create a PDO binding key which can be used for escaping variables safely
     * when executing a query with sql_exec()
     *
     * @param  array &$a    Array of bindings
     * @param  *      $val  Value to bind
     * @param  int    $type PDO field type
     * @return string       Bound key to be used in the SQL where this parameter
     *   would be used.
     */
    static function bind(&$a, $val, $type)
    {
        $key = ':binding_' . count($a);

        $a[] = array(
            'key' => $key,
            'val' => $val,
            'type' => $type
        );

        return $key;
    }


    /**
     * Pull a particular property from each assoc. array in a numeric array,
     * returning and array of the property values from each item.
     *
     *  @param  array  $a    Array to get data from
     *  @param  string $prop Property to read
     *  @return array        Array of property values
     */
    static function pluck($a, $prop)
    {
        $out = array();

        for ($i = 0, $len = count($a); $i < $len; $i++) {
            $out[] = $a[$i][$prop];
        }

        return $out;
    }

    public function getCalendarEvents()
    {
        $adminData = $this->session->userdata('userData');

        $meetings = $this->general_model->getTableWhereArray('meetings', array('meetingDone' => 0, 'customerId' => 1));
        //debug($meetings);
        $meetingsData = array();
        foreach ($meetings as $row) {
            $row = objectToArray($row);
            $row['start'] = date("Y-M-d H:i:s", strtotime($row['meetingTime']));
            $row['end'] = date("Y-M-d H:i:s", strtotime($row['meetingTime']) + 5000);
            $row['title'] = '<strong>שיחה</strong><br />' . getUserName($row['userId']) . '<br />';
            $row['manage'] = $row['meetingId'];
            $row['description'] = $row['meetingNote'];
            $row['className'] = 'pointerCursor';
            if ($row['status'] == 0 || $row['status'] == 3) {
                $row['backgroundColor'] =  '#E4AF82';
                $row['borderColor'] = '#576b64';
                $row['textColor'] =  '#222';
            } elseif ($row['status'] == 4) {
                $row['backgroundColor'] =  '#00ADFF';
                $row['borderColor'] = '';
                $row['textColor'] =  '#222';
            } elseif ($row['status'] == 5) {
                $row['backgroundColor'] =  '#FF3F3F';
                $row['borderColor'] = '';
                $row['textColor'] =  '#222';
            } elseif ($row['status'] == 7) {
                $row['backgroundColor'] =  '#0BC327';
                $row['borderColor'] = '';
                $row['textColor'] =  '#222';
            }

            $meetingsData[] = $row;
            //debug($meetingsData);
        }
        //debug($meetingsData);
        echo json_encode($meetingsData);
    }

    public function userClock()
    {

        $userId = intval($_POST['userId']);
        $date = str_replace('/', '-', $_POST['userDate']);
        $date = date('Y-m-d', strtotime($date));
        $dayType = intval($_POST['dayType']);
        //CHECK TODAY DATA
        $cioIn = $this->general_model->getTableWhereArray('checkInOut', array('dayType' => 1, 'userId' => $userId, 'DATE(checkTime)' => $date));
        $cioOut = $this->general_model->getTableWhereArray('checkInOut', array('dayType' => 2, 'userId' => $userId, 'DATE(checkTime)' => $date));
        //debug($cio);
        if ($dayType == 1) {
            if (count($cioIn) > 0) {
                $this->session->set_flashdata('flashMsgType', 'Error');
                $this->session->set_flashdata('flashMsg', 'קיים רישום נוכחות ל' . getUserName($_POST['userId']));
                redirect('admin/users/clocks/', 'refresh');
            } else {
                $data = array(
                    'userId' => $userId,
                    'adminId' => getAdminId(),
                    'checkTime' => $date . ' ' . $_POST['userCheckTime'] . ':00',
                    'dayType' => $dayType,
                    'creationDate'  => date('Y-m-d H:i:s')
                );
                $result = $this->general_model->insertRow('checkInOut', $data);
            }
        } elseif ($dayType == 2) {
            if (count($cioOut) > 0) {
                $this->session->set_flashdata('flashMsgType', 'Error');
                $this->session->set_flashdata('flashMsg', 'קיים רישום נוכחות ל' . getUserName($_POST['userId']));
                redirect('admin/users/clocks/', 'refresh');
            } else {
                $data = array(
                    'userId' => $userId,
                    'adminId' => getAdminId(),
                    'checkTime' => $date . ' ' . $_POST['userCheckTime'] . ':00',
                    'dayType' => $dayType,
                    'creationDate'  => date('Y-m-d H:i:s'),
                );
                $result = $this->general_model->insertRow('checkInOut', $data);
            }
        } else {
            $data = array(
                'userId' => $userId,
                'adminId' => getAdminId(),
                'checkTime' => $date . ' ' . $_POST['userCheckTime'] . ':00',
                'dayType' => $dayType,
                'creationDate'  => date('Y-m-d H:i:s'),
            );
            $result = $this->general_model->insertRow('checkInOut', $data);
        }
        //debug($_POST);
        if ($result > 0) {
            $this->session->set_flashdata('flashMsgType', 'Success');
            $this->session->set_flashdata('flashMsg', 'נרשמה נוכחות ל<strong>' . getUserName($_POST['userId']) . '</strong>');
            redirect('admin/users/clocks/' . $date, 'refresh');
            //echo json_encode(array( 'result' => true,
            //                        'cmt' => ''      ));
        } else {
            $this->session->set_flashdata('flashMsgType', 'Error');
            $this->session->set_flashdata('flashMsg', 'אופס! אירעה שגיאה, אנא נסה שנית.');
            redirect('admin/users/clocks/', 'refresh');
            //echo json_encode(array( 'result' => false ));
        }
    }

    public function deleteCio()
    {

        $date = date('Y-m-d', strtotime($_POST['checkIn']));
        $userId = intval($_POST['userId']);
        $cio = $this->db->query("SELECT * FROM checkInOut
                                              WHERE userId = " . $userId . " AND DATE(checkTime) = DATE('" . $date . "')
                                              ORDER BY checkTime DESC")->result();

        foreach ($cio as $c) {
            $result = $this->db->query("DELETE FROM checkInOut WHERE cioId = " . $c->cioId . "");
        }
        echo json_encode(array('result' => true));
    }

    public function addLeadTag()
    {

        $result = $this->db->query("SELECT ltId FROM lead_tags WHERE tagTitle = '" . $_POST['text'] . "' AND leadId = '" . $_POST['leadId'] . "' LIMIT 1");
        $id = $result->result();
        if (count($id) == 0) {
            $data = array('tagTitle' => $_POST['text'], 'leadId' => $_POST['leadId'], 'adminId' => getAdminId());
            $result = $this->general_model->insertRow('lead_tags', $data);
        }

        echo json_encode(array('result' => true));
    }

    public function deleteLeadTag()
    {

        $result = $this->db->query("SELECT ltId FROM lead_tags WHERE tagTitle = '" . $_POST['text'] . "' AND leadId = '" . $_POST['leadId'] . "' LIMIT 1");
        $id = $result->result();
        $result = $this->general_model->deleteRowById('lead_tags', 'ltId', $id[0]->ltId);

        echo json_encode(array('result' => true));
    }

    public function deleteComment()
    {

        //$result = $this->db->query("SELECT adminId FROM lead_comments WHERE lcId = '".intval($_POST['lcId'])."' LIMIT 1")->row()->adminId;

        if (1 == 1) { //$result == getAdminId()
            $result = $this->general_model->deleteRowById('lead_comments', 'lcId', $_POST['lcId']);
            echo json_encode(array('result' => true));
        } else {
            echo json_encode(array('result' => false));
        }
    }

    public function deleteLead()
    {

        $leadId = intval($_POST['leadId']);
        $lead = $this->db->query("SELECT * FROM leads WHERE leadId = " . $leadId . " AND customerId = " . getAdminId() . "")->row();
        //debug($lead);
        if (!empty($lead)) {
            $this->db->query("DELETE FROM leads WHERE leadId = " . $lead->leadId . "");
            $this->db->query("DELETE FROM leads_customers WHERE leadId = " . $lead->leadId . "");
            $this->db->query("DELETE FROM lead_comments WHERE leadId = " . $lead->leadId . "");
            $this->db->query("DELETE FROM lead_tags WHERE leadId = " . $lead->leadId . "");

            echo json_encode(array('result' => true));
        } else {
            echo json_encode(array('result' => false));
        }
    }

    function deleteLeads()
    {

        $data = $_POST['data'];
        $i = $result = 0;
        foreach ($data['leadId'] as $l) {

            $lead = $this->db->query("SELECT leadId FROM leads WHERE leadId = " . $l . "")->row();
            //debug($lead);
            if (!empty($lead)) {

                $this->db->query("DELETE FROM leads WHERE leadId = " . $lead->leadId . "");
                $this->db->query("DELETE FROM leads_customers WHERE leadId = " . $lead->leadId . "");
                $this->db->query("DELETE FROM lead_comments WHERE leadId = " . $lead->leadId . "");
                $this->db->query("DELETE FROM lead_tags WHERE leadId = " . $lead->leadId . "");
                $this->db->query("DELETE FROM phone_lines WHERE leadId = " . $lead->leadId . "");
            }
            $i++;
        }

        if ($i > 0) {
            $this->session->set_flashdata('flashMsgType', 'Success');
            $this->session->set_flashdata('flashMsg', '' . $i . ' מנויים נמחקו!');
            echo json_encode(array('result' => true));
        } else {
            echo json_encode(array('result' => false));
        }
        //debug($where);

    }

    function deleteTasks()
    {
        if (isset($_POST['data'])) {
            $data = $_POST['data'];
            $i = $result = 0;
            foreach ($data['taskId'] as $l) {

                $task = $this->db->query("SELECT taskId FROM tasks WHERE taskId = " . $l . "")->row();
                //debug($lead);
                if (!empty($task)) {

                    $this->db->query("DELETE FROM tasks WHERE taskId = " . $task->taskId . "");
                    $this->db->query("DELETE FROM task_comments WHERE taskId = " . $task->taskId . "");
                }
                $i++;
            }

            if ($i > 0) {
                $this->session->set_flashdata('flashMsgType', 'Success');
                $this->session->set_flashdata('flashMsg', '' . $i . ' משימות נמחקו!');
                echo json_encode(array('result' => true));
                return;
            } else {
                $this->session->set_flashdata('flashMsgType', 'Error');
                $this->session->set_flashdata('flashMsg', 'אירעה שגיאה!');
                echo json_encode(array('result' => false));
                return;
            }
        }
        $this->session->set_flashdata('flashMsgType', 'Error');
        $this->session->set_flashdata('flashMsg', 'אירעה שגיאה!');
        echo json_encode(array('result' => false));
        return;
        //debug($where);

    }

    function deletePayments()
    {

        $data = $_POST;
        $i = $result = 0;
        foreach ($data['leadId'] as $l) {

            if (isset($data['isRefund'])) {
                $pay = $this->general_model->getRowById('customers_payments', 'paymentId', $l);
                $customer = $this->general_model->getRowById('customers', 'customerId', $pay->customerId);
                if ($pay->ciId == 0) {
                    $newCredit = $customer->credits + $pay->total;
                    $r = $this->general_model->updateRowById('customers', 'customerId', $pay->customerId, array('credits' => $newCredit, 'lastUpdate' => date('Y-m-d H:i:s')));
                } else {
                    $invoice = $this->general_model->getRowById('customers_invoices', 'ciId', $pay->ciId);
                    $t = $invoice->total + $pay->total;
                    $r = $this->general_model->updateRowById('customers_invoices', 'ciId', $pay->ciId, array('total' => $t, 'lastUpdate' => date('Y-m-d H:i:s')));
                }
            }
            $r = $this->general_model->deleteRowById('customers_payments', 'paymentId', $l);
            $i++;
        }

        if ($i > 0) {
            $this->session->set_flashdata('flashMsgType', 'Success');
            $this->session->set_flashdata('flashMsg', '' . $i . ' תשלומים נמחקו!');
            echo json_encode(array('result' => true));
        } else {
            echo json_encode(array('result' => false));
        }
        //debug($where);

    }

    public function deleteClientPayment()
    {

        $result = $this->general_model->deleteRowById('clients_payments', 'paymentId', intval($_POST['pId']));

        echo json_encode(array('result' => true));
    }

    function getRowFromTable()
    {
        $r = $this->general_model->getTableWhereArray($_POST['table'], $_POST['data']);
        if ($r) echo json_encode(array('result' => true, 'data' => $r[0]));
        else echo json_encode(array('result' => false));
    }

    function getRowsFromTable()
    {
        $r = $this->general_model->getTableWhereArray($_POST['table'], $_POST['data']);
        if ($r) echo json_encode(array('result' => true, 'data' => $r));
        else echo json_encode(array('result' => false));
    }

    public function insertRowAjax()
    {
        $result = $this->general_model->insertRow($_POST['table'], $_POST['data']);
        echo json_encode(array('result' => $result));
    }

    public function setCustomerToLine()
    {
        $data = $_POST['data'];
        //debug($data);
        $users = explode(',', $data['userId']);
        $customerId = intval($data['customerId']);
        foreach ($users as $u) {

            $sqlData = array(
                'customerId' => $customerId,
                'lastUpdate' => date('Y-m-d H:i:s')
            );
            $result = $this->general_model->updateRowById('phone_lines', 'lineId', intval($u), $sqlData);
        }

        echo json_encode(array('result' => true));
    }

    public function updateLeadCustomer()
    {

        $data = $_POST['data'];

        $leadId = $data['leadId'];
        $customerId = intval($data['customerId']);
        if ($leadId > 0) {

            $lead = $this->general_model->getRowById('leads', 'leadId', $leadId);

            $history_data = array(
                'leadId'        => $leadId,
                'adminId'       => getUserId(),
                'phone'         => $lead->phone,
                'old'           => $lead->adminId,
                'new'           => $customerId,
                'creationDate'  => date('Y-m-d H:i:s')
            );

            $addHistory = $this->general_model->insertRow('change_customer_history', $history_data);

            $sqlData = array(
                'adminId' => $customerId,
                'lastUpdate' => date('Y-m-d H:i:s')
            );
            $result = $this->general_model->updateRowById('leads', 'leadId', intval($leadId), $sqlData);
            $sqlData = array(
                'customerId' => $customerId,
                'lastUpdate' => date('Y-m-d H:i:s')
            );
            $result = $this->general_model->updateRowById('phone_lines', 'leadId', intval($leadId), $sqlData);
        }

        echo json_encode(array('result' => true));
    }

    public function updateCustomerPayment()
    {

        $data = $_POST['data'];
        //debug($data);
        $pId = $data['id'];
        if ($pId > 0) {

            $pay = $this->general_model->getRowById('customers_payments', 'paymentId', intval($pId));
            $customer = $this->general_model->getRowById('customers', 'customerId', $pay->customerId);

            $sqlData = array(
                'total' => floatval($data['total']),
                'comment' => htmlspecialchars($data['comment']),
                'cpDate' => date('Y-m-d', strtotime(str_replace('/', '-', $data['date']))),
                'lastUpdate' => date('Y-m-d H:i:s')
            );
            $result = $this->general_model->updateRowById('customers_payments', 'paymentId', intval($pId), $sqlData);

            if ($pay->total != $sqlData['total']) {

                $delta = $pay->total - $sqlData['total'];
                $newCredit = $customer->credits + $delta;
                if ($pay->title == 'credit_addon') $newCredit = $customer->credits - $delta;
                $result = $this->general_model->updateRowById('customers', 'customerId', $pay->customerId, array('credits' => $newCredit));
            }

            /*
            $sqlData = array(
                'customerId' => $customerId,
                'lastUpdate' => date('Y-m-d H:i:s')
            );
            $result = $this->general_model->updateRowById('phone_lines', 'leadId', intval($leadId), $sqlData);
            */
            if ($result) echo json_encode(array('result' => true));
            else echo json_encode(array('result' => false));
            return;
        }

        echo json_encode(array('result' => true));
        return;
    }

    public function insertTask()
    {

        $data               = $_POST;
        $data['taskText']   = remove_emoji($data['taskText']);
        $mDate              = date('Y-m-d', strtotime(str_replace('/', '-', $data['taskDate'])));
        $customerId         = isset($data['customerId']) ? $data['customerId'] : 0;
        $taskSubject        = $_POST['taskSubject'];

        if ($taskSubject == "שחרור חסימת ניוד") {

            $lead = $this->db->query('SELECT * FROM leads as l
                                          INNER JOIN phone_lines as pl ON l.leadId = pl.leadId
                                          WHERE l.leadId = ' . $data['leadId'])->row();
            $unblock_block            = $_POST['unblock_block'];

            $fbData = array(
                'leadId'          => isset($data['leadId']) ? $data['leadId'] : 0,
                'phoneLine'       => $_POST['phoneLineTask'],
                'orgCompany'      => $_POST['lineProviderTask'],
                'status'          => $_POST['statusTask'],
                'dateActivation'  => $_POST['serviceStartDateTask'],
                'dateCreated'     => date('Y-m-d H:i:s'),
                'customerId'      => $lead->adminId,
                'unblocked'       => '0',
                'accepted'        => '0',
                'moved'           => '0',
                'report'          => '0',
                'toCompany'       => $_POST['unblock_company'],
                'simNumber'       => $_POST['task_unblock_sim_number'],
                'comment'         => $data['taskSubject'],
                'result'          => '',
                'dateUpdated'     => date('Y-m-d H:i:s')

            );

            $fbDataId = $this->general_model->insertRow('free_unblock_niyud', $fbData);

            if ($unblock_block == 2) {
                $unblock_company          = $_POST['unblock_company'];
                $task_unblock_sim_number  = $_POST['task_unblock_sim_number'];
                $taskText                 = 'שחרור חסימת ניוד והעברה ' . $unblock_company . ' - ' . $task_unblock_sim_number;
            } else {
                $taskText                 = 'שחרור חסימת ניוד';
            }

            if (isset($_POST['unblock_campaignId']) && !empty($_POST['unblock_campaignId'])) {
                $unblock_campaignId = $_POST['unblock_campaignId'];
                $allCcampaigns      = reindex_by_key($this->db->query("SELECT * FROM campaigns WHERE isActive = 1 ")->result(), 'campaignId');

                $cmtfreetxt = "חבילה נבחרה: ";
                $cmtText    = $allCcampaigns[$unblock_campaignId]->campaignName;
                $final_text = $cmtfreetxt . $cmtText;
                $cmtData    = array(
                    'leadId'       => $data['leadId'],
                    'userId'       => getUserId(),
                    'adminId'      => getAdminId(),
                    'text'         => $final_text,
                    'creationDate' => date('Y-m-d H:i:s')
                );
                $result = $this->general_model->insertRow('lead_comments', $cmtData);
            } else {
                $final_text = '';
            }
            $taskData = array(
                'leadId'        => isset($data['leadId']) ? $data['leadId'] : 0,
                'userId'        => getUserId(),
                'adminId'       => getAdminId(),
                'attendsIds'    => isset($data['userId']) ? implode(',', $data['userId']) : '',
                'customerId'    => getAdminId(),
                'campaignId'    => isset($data['campaignId']) ? $data['campaignId'] : 0,
                'subject'       => $data['taskSubject'],
                'text'          => $taskText . "<br/>" . $final_text,
                'todoDate'      => date('Y-m-d H:i:s', strtotime('+1 DAYS')),
                'creationDate'  => date('Y-m-d H:i:s'),
                'lastUpdate'    => date('Y-m-d H:i:s'),
            );

            $result = $this->general_model->insertRow('tasks', $taskData);

            $re = $this->general_model->updateRowById('free_unblock_niyud', 'uID', $fbDataId, array('taskId' => $result));
        } else {

            $taskData = array(
                'leadId' => isset($data['leadId']) ? $data['leadId'] : 0,
                'userId' => getUserId(),
                'adminId' => getAdminId(),
                'attendsIds' => isset($data['userId']) ? implode(',', $data['userId']) : '',
                'customerId' => $customerId,
                'campaignId' => isset($data['campaignId']) ? $data['campaignId'] : 0,
                'subject' => $data['taskSubject'],
                'text' => makeLinks($data['taskText']),
                'rating' => intval($data['rating']),
                'todoDate' => $mDate . ' ' . $data['taskTime'] . ':00',
                'creationDate' => date('Y-m-d H:i:s'),
                'lastUpdate' => date('Y-m-d H:i:s'),
            );

            //debug($taskData);
            $result = $this->general_model->insertRow('tasks', $taskData);

            if ($data['emailTo'] != '') {
                $recipes = explode(',', $data['emailTo']);
                foreach ($recipes as $r) {
                    $mailData = array('content'  => makeLinks($data['taskText']));
                    $message = $this->load->view('emails/taskMessage', $mailData, true);
                    //sendEmail(trim($r), 'info@leadmecms.co.il', 'MT CMS', $data['taskSubject'].' - '.getCustomerName($customerId), $message, $cc = '', $bcc = '', $html = true);

                }
            }
        }
        redirect('admin/tasks/viewTask/' . $result, 'refresh');
    }

    public function updateTaskStatus()
    {

        $taskId = is_array($_POST['taskId']) ? $_POST['taskId'] : intval($_POST['taskId']);
        $newStatus = intval($_POST['newStatus']);
        $newStatusText = $this->general_model->getTableWhere('lead_statuses', 'lsId', $newStatus);

        if (is_array($taskId)) {
            foreach ($taskId as $t) {
                $result = $this->general_model->updateRowById('tasks', 'taskId', $t, array('status' => $newStatus, 'lastUpdate' => date('Y-m-d H:i:s')));

                $cmtText = 'עדכון סטטוס <strong>' . $newStatusText[0]->title_he . '</strong>';
                $cmtData = array(
                    'taskId'       => $t,
                    'userId'       => getUserId(),
                    'text'         => $cmtText,
                    'creationDate' => date('Y-m-d H:i:s')
                );
                $result = $this->general_model->insertRow('task_comments', $cmtData);

                if ($newStatus == 30) {
                    $task = $this->general_model->getRowById('tasks', 'taskId', $t);
                    if ($task->leadId > 0) {
                        if (strpos($task->subject, 'חיבור') > -1 || strpos($task->subject, 'ניוד') > -1) {

                            $lead = $this->general_model->getRowById('leads', 'leadId', $task->leadId);
                            if ($lead->status == 1) {
                                $result = $this->general_model->updateRowById('leads', 'leadId', $task->leadId, array('status' => 2, 'lastUpdate' => date('Y-m-d H:i:s')));
                            }
                            //$result = $this->general_model->updateRowById('leads', 'leadId', $task->leadId, array('status' => 2, 'lastUpdate' => date('Y-m-d H:i:s')));

                            $cmtText = 'עדכון סטטוס <strong>פעיל</strong>'; //.$apiMsg;
                            $cmtData = array(
                                'leadId'       => $task->leadId,
                                'userId'       => getUserId(),
                                'adminId'      => getAdminId(),
                                'text'         => $cmtText,
                                'creationDate' => date('Y-m-d H:i:s')
                            );
                            $result = $this->general_model->insertRow('lead_comments', $cmtData);
                        }
                    }
                }
            }
            $this->session->set_flashdata('flashMsgType', 'Success');
            $this->session->set_flashdata('flashMsg', 'עודכן סטטוס ל<strong>' . count($taskId) . '</strong> קריאות שירות.');
            if ($result) echo json_encode(array('result' => true));
            else echo json_encode(array('result' => false));
        } else {

            $result = $this->general_model->updateRowById('tasks', 'taskId', $taskId, array('status' => $newStatus, 'lastUpdate' => date('Y-m-d H:i:s')));

            $cmtText = 'עדכון סטטוס <strong>' . $newStatusText[0]->title_he . '</strong>';
            $cmtData = array(
                'taskId'       => $taskId,
                'userId'       => getUserId(),
                'text'         => $cmtText,
                'creationDate' => date('Y-m-d H:i:s')
            );
            $result = $this->general_model->insertRow('task_comments', $cmtData);

            if ($newStatus == 30) {
                $task = $this->general_model->getRowById('tasks', 'taskId', $taskId);
                if ($task->leadId > 0) {
                    if (strpos($task->subject, 'חיבור') > -1 || strpos($task->subject, 'ניוד') > -1) {

                        $lead = $this->general_model->getRowById('leads', 'leadId', $task->leadId);
                        $this->general_model->updateRowById('leads', 'leadId', $task->leadId, array('isWe4gActive' => 0));
                        if ($lead->status == 1) {
                            $result = $this->general_model->updateRowById('leads', 'leadId', $task->leadId, array('status' => 2, 'lastUpdate' => date('Y-m-d H:i:s')));
                        }

                        //$result = $this->general_model->updateRowById('leads', 'leadId', $task->leadId, array('status' => 2, 'lastUpdate' => date('Y-m-d H:i:s')));

                        $cmtText = 'עדכון סטטוס <strong>פעיל</strong>'; //.$apiMsg;
                        $cmtData = array(
                            'leadId'       => $task->leadId,
                            'userId'       => getUserId(),
                            'adminId'      => getAdminId(),
                            'text'         => $cmtText,
                            'creationDate' => date('Y-m-d H:i:s')
                        );
                        $result = $this->general_model->insertRow('lead_comments', $cmtData);
                    }

                    $lead           = $this->general_model->getRowById('leads', 'leadId', $task->leadId);
                    if ($lead->subtracted_store == 0) {

                        //Mark as subtracted from store
                        $subtractLead   = $this->general_model->updateRowById('leads', 'leadId', $lead->leadId, array('subtracted_store' => 1));
                        $camp           = $this->general_model->getRowById('campaigns', 'campaignId', $lead->campaignId);
                        $company        = $this->general_model->getRowById('companies', 'code', $camp->campaignDesc);
                        $customerStore  = $this->general_model->getTableWhereArray('sim_customer_store', array('customerId' => $lead->adminId, "companyId" => $company->id));
                        if (!empty($customerStore)) {
                            //Subtract from Store
                            $subtractLead   = $this->general_model->updateRowById(
                                'sim_customer_store',
                                'id',
                                $customerStore[0]->id,
                                array('quantity_rentpaid' => $customerStore[0]->quantity_rentpaid - 1)
                            );
                            //Add Subtract Data
                            $customer_data_sub = array(
                                'customerId'        => $customerStore[0]->customerId,
                                'store_id'          => $customerStore[0]->id,
                                'leadId'            => $lead->leadId,
                                'phone'             => $lead->phone,
                                'type'              => 'quantity_rentpaid',
                                'quantity'          => 1,
                                'quantity_before'   => $customerStore[0]->quantity_rentpaid,
                                'quantity_after'    => $customerStore[0]->quantity_rentpaid - 1,
                                'dateCreation'      => date('Y-m-d H:i:s')
                            );
                            $insertSub = $this->general_model->insertRow('sim_customer_store_phones', $customer_data_sub);
                        }
                    }
                }
            }

            $out = '<tr class="cttr" rel="' . $result . '">
    			<td style="width: 25%;"><b>' . formatDateTime(date('Y-m-d H:i:s')) . '</b></td>
    			<td class="txt-color-blue" style="width: 20%;"><b>' . getUserName(getUserId()) . '</b></td>
    			<td>' . $cmtText . '</td>
                <td></td>
    		</tr>';
            if ($result) echo json_encode(array(
                'result' => true,
                'cmt'    => $out
            ));
            else echo json_encode(array('result' => false));
        }
    }

    public function insertTaskComment()
    {

        $taskId     = intval($_POST['taskId']);
        $text_id    = intval($_POST['text_id']);
        $texts      = $this->general_model->getRowById('task_comments_texts', 'text_id', $text_id);
        $task       = $this->general_model->getRowById('tasks', 'taskId', $taskId);
        $lead       = $this->general_model->getRowById('leads', 'leadId', $task->leadId);

        $cmtData = array(
            'taskId'       => $taskId,
            'userId'       => getUserId(),
            'text'         => $texts->text_he,
            'text_id'      => $text_id,
            'isCall'       => '',
            'creationDate' => date('Y-m-d H:i:s')
        );

        $result = $this->general_model->insertRow('task_comments', $cmtData);

        $notification_data = array(
            'customerId'    => $lead->adminId,
            'leadId'        => $lead->leadId,
            'isSeen'        => 0,
            'text'          => $texts->text_he,
            'text_id'       => $text_id,
            'isDeleted'     => 0,
            'isDone'        => 0,
            'creationDate'  => date('Y-m-d H:i:s'),
            'lastUpdate'    => date('Y-m-d H:i:s')
        );

        $add_notification = $this->general_model->insertRow('customers_notifications', $notification_data);

        $this->general_model->updateRowById('tasks', 'taskId', $taskId, array('lastUpdate' => date('Y-m-d H:i:s')));

        $task       = $this->general_model->getRowById('tasks', 'taskId', $taskId);
        $cmtText    = $texts->text_he;
        $leadId     = $task->leadId;
        $addComment = $this->addCommentToLead($leadId, $cmtText, $text_id);

        if ($result > 0) {
            list($time, $date) = explode(' ', date('H:i d/m/Y'));
            !$cmtData['isCall'] ? $icon = '<i class="fa fa-phone"></i>' : $icon = '';
            $out = '';
            $out .= '<tr class="cttr" rel="' . $result . '">
						<td style="width: 25%;"><b>' . formatDateTime(date('Y-m-d H:i:s')) . '</b></td>
						<td class="txt-color-blue" style="width: 20%;"><b>' . getUserName(getUserId()) . '</b></td>
						<td>' . $cmtText . '</td>
                        <td></td>
					</tr>';
            echo json_encode(array(
                'result' => true,
                'cmt' => $out
            ));
        } else {
            echo json_encode(array('result' => false));
        }
    }

    public function insertTanslatedComment()
    {

        $leadId     = intval($_POST['leadId']);
        if (!empty($leadId)) {
            $text_id    = intval($_POST['text_id']);
            $texts      = $this->general_model->getRowById('task_comments_texts', 'text_id', $text_id);
            $lead       = $this->general_model->getRowById('leads', 'leadId', $leadId);
            $cmtText    = $texts->text_he;
            $addComment = $this->addCommentToLead($leadId, $cmtText, $text_id);

            if (!empty($addComment)) {
                echo json_encode(array('result' => true));
            } else {
                echo json_encode(array('result' => false));
            }
        } else {
            echo json_encode(array('result' => false));
        }
    }
    function setTaskDone()
    {
        $data = $_POST;
        $r = $this->general_model->updateRowById('tasks', 'taskId', $data['laId'], array('isDone' => getUserId(), 'lastUpdate' => date('Y-m-d H:i:s')));
        if ($r) echo json_encode(array('result' => true, ''));
        else echo json_encode(array('result' => false));
    }

    function deleteTask()
    {
        $data = $_POST;
        $r = $this->general_model->deleteRowById('tasks', 'taskId', $data['laId']);
        $r = $this->general_model->deleteRowById('task_comments', 'taskId', $data['laId']);
        if ($r) echo json_encode(array('result' => true));
        else echo json_encode(array('result' => false));
    }

    function deleteLeadPayment()
    {
        $data = $_POST;
        $r = $this->general_model->deleteRowById('leads_payments', 'lpId', $data['lpId']);
        if ($r) echo json_encode(array('result' => true));
        else echo json_encode(array('result' => false));
    }

    function deleteCustomerPayment()
    {
        //debug($_POST);
        $data = $_POST;
        if (isset($data['isRefund'])) {
            $pay = $this->general_model->getRowById('customers_payments', 'paymentId', $data['paymentId']);
            if (!empty($pay)) {
                $customer = $this->general_model->getRowById('customers', 'customerId', $pay->customerId);
                if ($pay->ciId == 0) {
                    $newCredit = $customer->credits + $pay->total;
                    $r = $this->general_model->updateRowById('customers', 'customerId', $pay->customerId, array('credits' => $newCredit, 'lastUpdate' => date('Y-m-d H:i:s')));
                } else {
                    $invoice = $this->general_model->getRowById('customers_invoices', 'ciId', $pay->ciId);
                    $t = $invoice->total - $pay->total;
                    $r = $this->general_model->updateRowById('customers_invoices', 'ciId', $pay->ciId, array('total' => $t, 'lastUpdate' => date('Y-m-d H:i:s')));
                }
            } else {
            }
        }
        $r = $this->general_model->deleteRowById('customers_payments', 'paymentId', $data['paymentId']);
        if ($r) echo json_encode(array('result' => true));
        else echo json_encode(array('result' => false));
    }

    function deleteCustomerPaymentPP()
    {
        //debug($_POST);
        $data = $_POST;
        if (isset($data['isRefund'])) {
            $pay = $this->general_model->getRowById('customers_payments', 'paymentId', $data['paymentId']);
            $customer = $this->general_model->getRowById('customers', 'customerId', $pay->customerId);
            if ($pay->ciId == 0) {
                $newCredit = $customer->creditsPP + $pay->total;
                $r = $this->general_model->updateRowById('customers', 'customerId', $pay->customerId, array('creditsPP' => $newCredit, 'lastUpdate' => date('Y-m-d H:i:s')));
            } else {
                $invoice = $this->general_model->getRowById('customers_invoices', 'ciId', $pay->ciId);
                $t = $invoice->total - $pay->total;
                $r = $this->general_model->updateRowById('customers_invoices', 'ciId', $pay->ciId, array('total' => $t, 'lastUpdate' => date('Y-m-d H:i:s')));
            }
        }
        $r = $this->general_model->deleteRowById('customers_payments', 'paymentId', $data['paymentId']);
        if ($r) echo json_encode(array('result' => true));
        else echo json_encode(array('result' => false));
    }

    function deleteAgentCollect()
    {
        $data = $_POST;
        $r = $this->general_model->deleteRowById('agents_payments_collections', 'apcId', $data['apcId']);
        if ($r) echo json_encode(array('result' => true));
        else echo json_encode(array('result' => false));
    }

    function insertLeadPayment()
    {
        //debug($_POST);
        $data = $_POST;
        $paymentData = array(
            'comment'       => $data['comment'],
            'total'         => $data['total'],
            //'type'          => $data['pType'],
            'lpDate'        => date('Y-m-d H:i:s'),
            'startDate'     => date('Y-m-d H:i:s', strtotime(str_replace('/', '-', $data['startDate']))),
            'endDate'       => date('Y-m-d H:i:s', strtotime(str_replace('/', '-', $data['endDate']))),
            'userId'        => getUserId(),
            'customerId'    => getAdminId(),
            'leadId'        => $data['leadId'],
            'creationDate'  => date('Y-m-d H:i:s'),
            'lastUpdate'    => date('Y-m-d H:i:s')
        );

        $findPhone = $this->general_model->getRowById('phone_lines', 'leadId', $data['leadId']);
        //update credits if needed
        if ($findPhone->creditType == 3) {

            $credit = $findPhone->credits - $data['total'];
            if ($credit > 0) {
                $r = $this->general_model->updateRowById('phone_lines', 'leadId', $data['leadId'], array('credits' => $credit, 'lastUpdate' => date('Y-m-d H:i:s')));
                $paymentData['isPaid'] = 1;
            } else {
                $this->session->set_flashdata('flashMsgType', 'Error');
                $this->session->set_flashdata('flashMsg', 'יתרת הלקוח אינה מאפשרת תשלום');
                redirect('admin/leads/viewLead/' . $data['leadId'], 'refresh');
            }
        }

        $result = $this->general_model->insertRow('leads_payments', $paymentData);
        //debug($_POST);
        redirect('admin/leads/viewLead/' . $data['leadId'], 'refresh');

        if ($result) {
            //Update invest lastupdate
            echo json_encode(array('result' => true, 'out' => $out));
        } else {
            echo json_encode(array('result' => false));
        }
    }

    function insertCustomerPayment($customerId)
    {

        $data = $_POST;

        $total_date     = $data['total_date'];
        $dateStr        = str_replace("/", "-", $total_date);
        $first_date     = strtotime($dateStr);
        $cpDate         = date('Y-m-d H:i:s', $first_date);

        $customer = $this->general_model->getRowById('customers', 'customerId', intval($customerId));
        $paymentData = array(
            'comment'       => htmlspecialchars($data['comment']),
            'total'         => floatval($data['total']),
            'title'          => 'general_payment',
            'cpDate'        => $cpDate,
            //'startDate'     => date('Y-m-d H:i:s', strtotime(str_replace('/', '-', $data['startDate']))),
            //'endDate'       => date('Y-m-d H:i:s', strtotime(str_replace('/', '-', $data['endDate']))),
            'userId'        => getUserId(),
            'adminId'       => $customer->parentId,
            'customerId'    => intval($customerId),
            'isPaid'        => 1,
            'qty' => 1,
            'creationDate'  => date('Y-m-d H:i:s'),
            'lastUpdate'    => date('Y-m-d H:i:s')
        );

        $result = $this->general_model->insertRow('customers_payments', $paymentData);


        $newCredit = $customer->credits - floatval($data['total']);
        $r = $this->general_model->updateRowById('customers', 'customerId', intval($customerId), array('credits' => $newCredit, 'lastUpdate' => date('Y-m-d H:i:s')));

        if (isset($data['leadId'])) {

            $cplData = array('leadId' => intval($data['leadId']), 'cpId' => $result, 'price' => floatval($data['total']));
            $resultCp = $this->general_model->insertRow('customers_payments_leads', $cplData);

            if ($customer->parentId != 1) {
                $customerP = $this->general_model->getRowById('customers', 'customerId', $customer->parentId);
                $cpDataP = array(
                    'customerId' => $customer->parentId,
                    'comment'       => htmlspecialchars($data['comment']),
                    'total' => floatval($data['totalOperator']),
                    'title' => 'general_payment',
                    'qty' => 1,
                    'adminId' => 1,
                    'userId'        => getUserId(),
                    'cpDate'  => date('Y-m-d H:i:s'),
                    'creationDate'  => date('Y-m-d H:i:s'),
                    'lastUpdate'    => date('Y-m-d H:i:s')
                );

                $creditP = $customerP->credits - floatval($data['totalOperator']);
                $r = $this->general_model->updateRowById('customers', 'customerId', $customerP->customerId, array('credits' => $creditP, 'lastUpdate' => date('Y-m-d H:i:s')));
                $cpDataP['isPaid'] = 1;

                $resultCpP = $this->general_model->insertRow('customers_payments', $cpDataP);

                $cplDataP = array('leadId' => intval($data['leadId']), 'cpId' => $resultCpP, 'price' => floatval($data['totalOperator']));
                $resultCp = $this->general_model->insertRow('customers_payments_leads', $cplDataP);
            }

            redirect('admin/leads/viewLead/' . intval($data['leadId']), 'refresh');
        }

        //debug($_POST);
        redirect('admin/customers/customerPaymentsSum/' . intval($customerId), 'refresh');

        if ($result) {
            //Update invest lastupdate
            echo json_encode(array('result' => true, 'out' => $out));
        } else {
            echo json_encode(array('result' => false));
        }
    }

    function insertAgentDeposit()
    {

        $data = $_POST['data'];
        //$data['apcId'] = intval($data['apcId']);
        //$apc = $this->general_model->getRowById('agents_payments_collections', 'apcId', $data['apcId']);
        $paymentData = array(
            'comment'       => htmlspecialchars($data['comment']),
            'total'         => -1 * floatval($data['total']),
            'is_prepaid'    => intval($data['is_prepaid']),
            'userId'        => intval($data['userId']),
            'agentId'       => intval($data['agent']),
            'creationDate'  => date('Y-m-d H:i:s')
        );

        if ($data['date'] != '') {
            $paymentData['creationDate'] = date('Y-m-d H:i:s', strtotime($data['date']));
        }

        $result = $this->general_model->insertRow('agents_payments_collections', $paymentData);

        //$r = $this->general_model->updateRowById('agents_payments_collections', 'apcId', $data['apcId'], array('deposit' => $apc->deposit + $paymentData['total']));


        if ($result) {
            //Update invest lastupdate
            echo json_encode(array('result' => true));
        } else {
            echo json_encode(array('result' => false));
        }
    }

    function editAgentDeposit()
    {

        $data = $_POST['data'];
        $data['apcId'] = intval($data['apcId']);
        //$apc = $this->general_model->getRowById('agents_payments_collections', 'apcId', $data['apcId']);
        $paymentData = array(
            'comment'       => htmlspecialchars($data['comment']),
            'is_prepaid'    => intval($data['is_prepaid']),
            'agentId'       => intval($data['agent']),
            'total'         => floatval($data['total'])
        );
        if ($data['date'] != '') {
            $paymentData['creationDate'] = date('Y-m-d H:i:s', strtotime($data['date']));
        }
        $result = $this->general_model->updateRowById('agents_payments_collections', 'apcId', $data['apcId'], $paymentData);

        //$r = $this->general_model->updateRowById('agents_payments_collections', 'apcId', $data['apcId'], array('deposit' => $apc->deposit + $paymentData['total']));


        if ($result) {
            //Update invest lastupdate
            echo json_encode(array('result' => true));
        } else {
            echo json_encode(array('result' => false));
        }
    }

    function insertInvoice()
    {

        $data = $_POST;
        $i = $result = 0;
        if (count($data['leadId']) > 0) {
            $idS = implode(',', $data['leadId']);
            $total = $this->db->query('SELECT SUM(total) as t FROM customers_payments WHERE paymentId IN (' . $idS . ')')->row()->t;


            $invData = array(
                'comment'       => 'סגירת חשבון',
                'total'         => $total,
                'qty'          => count($data['leadId']),
                'userId'        => getUserId(),
                'customerId'    => $data['customerId'],
                'adminId'       => getAdminId(),
                'creationDate'  => date('Y-m-d H:i:s'),
                'lastUpdate'    => date('Y-m-d H:i:s')
            );

            $result = $this->general_model->insertRow('customers_invoices', $invData);

            foreach ($data['leadId'] as $l) {
                $r = $this->general_model->updateRowById('customers_payments', 'paymentId', $l, array('ciId' => $result, 'lastUpdate' => date('Y-m-d H:i:s')));

                $i++;
            }
            $customer = $this->general_model->getRowById('customers', 'customerId', $data['customerId']);
            $credit = $customer->credits + $total;
            $r = $this->general_model->updateRowById('customers', 'customerId', $data['customerId'], array('credits' => $credit, 'lastUpdate' => date('Y-m-d H:i:s')));

            $this->session->set_flashdata('flashMsgType', 'Success');
            $this->session->set_flashdata('flashMsg', '' . $i . ' תשלומים נסגרו!');
            echo json_encode(array('result' => true));
        } else {
            echo json_encode(array('result' => false));
        }
        //debug($where);

    }

    function insertPhoneLine()
    {
        $phone = htmlspecialchars($_POST['phone']);
        if (substr($phone, 0, 1) !== '0') $phone = '0' . $phone;

        $findPhone = $this->general_model->getRowById('phone_lines', 'phone', $phone);
        $dataSql = array(
            'phone'         => $phone,
            'customerId'    => getAdminId(),
            'leadId'        => 0,
            'isActive'      => 0,
            'creationDate'  => date('Y-m-d H:i:s'),
            'lastUpdate'    => date('Y-m-d H:i:s')
        );
        if (!empty($findPhone)) {
            echo json_encode(array('result' => false, 'msg' => $phone . ' - מספר קיים במערכת'));
        } else {
            $resultP = $this->general_model->insertRow('phone_lines', $dataSql);
            echo json_encode(array('result' => true, 'msg' => 'המספר נקלט בהצלחה'));
        }
    }

    function cellcomActivateLine($phone)
    {
        //$phone = '0528146156';
        $token = $this->cellcomProviderToken();
        //debug($token);
        $url = 'https://api.cellcom.co.il:4433/api/services/provider/OrgServicesRestore';
        $CR = curl_init();
        $strRequest = array(
            'operatorID' => 'MENDI',
            'processId' => '4837389c-407e-49ed-9b5a-d029c48d136a',
            'messageId' => '4837389c-407e-49ed-9b5a-d029c48d136a',
            'subscriberNumber' => $phone,
            'organization' => '6700973',
            'dealerCode' => '00300',
            'actionDate' => date('Ymd'),
            'actionReason' => 'CR',
            'actionText' => 'RESTORE By MendiTelecom CMS'
        );
        curl_setopt($CR, CURLOPT_URL, $url);
        curl_setopt($CR, CURLOPT_POST, true);
        curl_setopt($CR, CURLOPT_FAILONERROR, true);
        curl_setopt($CR, CURLOPT_POSTFIELDS, http_build_query($strRequest));
        curl_setopt($CR, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($CR, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($CR, CURLOPT_HTTPHEADER, array(
            'Authorization: ' . $token->access_token,
            'Content-Type: application/x-www-form-urlencoded',
        ));

        //actual curl execution perfom
        $result = curl_exec($CR);
        $error = curl_error($CR);

        curl_close($CR);
        $result = json_decode($result);
        //var_dump($error);
        //debug($result);
        return $result;
    }

    function cellcomSuspendLine($phone)
    {
        //$phone = '0528146156';
        $token = $this->cellcomProviderToken();
        //debug($token);
        $url = 'https://api.cellcom.co.il:4433/api/services/provider/OrgServicesSuspend';
        $CR = curl_init();
        $strRequest = array(
            'operatorID'       => 'MENDI',
            'processId'        => '4837389c-407e-49ed-9b5a-d029c48d136a',
            'messageId'        => '4837389c-407e-49ed-9b5a-d029c48d136a',
            'subscriberNumber' => $phone,
            'organization' => '6700973',
            'dealerCode'   => '00300',
            'actionDate'   => date('Ymd'),
            'actionReason' => 'RENT',
            'actionText'   => 'RESTORE By MendiTelecom CMS'
        );
        curl_setopt($CR, CURLOPT_URL, $url);
        curl_setopt($CR, CURLOPT_POST, true);
        curl_setopt($CR, CURLOPT_FAILONERROR, true);
        curl_setopt($CR, CURLOPT_POSTFIELDS, http_build_query($strRequest));
        curl_setopt($CR, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($CR, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($CR, CURLOPT_HTTPHEADER, array(
            'Authorization: ' . $token->access_token,
            'Content-Type: application/x-www-form-urlencoded',
        ));

        //actual curl execution perfom
        $result = curl_exec($CR);
        $error = curl_error($CR);

        curl_close($CR);
        $result = json_decode($result);
        //var_dump($error);
        //debug($result);
        return $result;
    }

    public function cellcomProviderToken()
    {


        //$url = 'https://apigwqa.cellcom.co.il:4433/api/services/getProviderToken';
        $url = 'https://api.cellcom.co.il:4433/api/services/getProviderToken';
        $CR = curl_init();
        curl_setopt($CR, CURLOPT_URL, $url);
        curl_setopt($CR, CURLOPT_POST, true);
        curl_setopt($CR, CURLOPT_FAILONERROR, true);
        //curl_setopt($CR, CURLOPT_POSTFIELDS, $strRequest);
        curl_setopt($CR, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($CR, CURLOPT_SSL_VERIFYPEER, true);
        //curl_setopt($CR, CURLOPT_USERPWD, "$username:$password");
        //curl_setopt($CR, CURLOPT_SSL_VERIFYHOST, true);

        curl_setopt($CR, CURLOPT_HTTPHEADER, array(
            'Content-Type: text/json',
            //'Content-Length: ' . strlen($strRequest),
            'grant_type: client_credentials',
            'scope: resource.READ',
            'format: Json',
            //test
            //'client_secret: 4234b1d5-17ae-46e8-83d1-88691f791ff1',
            //'client_id: 6492f874-27f5-47ea-9dc7-ea67b3ab9ca4',
            //live
            'client_secret: d1f852d0-13e7-4a94-b4b4-aca0af76c77e',
            'client_id: 0f63aba5-18ee-4021-829a-c36f50455e5f',
        ));
        //actual curl execution perfom
        $result = curl_exec($CR);
        $error = curl_error($CR);

        curl_close($CR);
        $result = json_decode($result);
        return $result;
    }

    public function cellcomProviderToken2()
    {


        //$url = 'https://apigwqa.cellcom.co.il:4433/api/services/getProviderToken';
        //$url = 'https://connect.cellcom.co.il:8080/ipa/apis/json/general/login';
        $url = 'https://connect.cellcom.co.il:8080/ipa/apis/json/provisioning/getProvisioningData';
        $CR = curl_init();
        $strRequest = array(
            'username' => 'mohammad', //avishag.tzur@gmail.com
            'password' => 'Mm112233!',
            'limit' => '5',
            'search' => array(array(
                "fieldName" => "MSISDN", //0528146156
                "fieldValue" => "0524651895"
            ))
        );
        curl_setopt($CR, CURLOPT_URL, $url);
        curl_setopt($CR, CURLOPT_POST, true);
        curl_setopt($CR, CURLOPT_FAILONERROR, true);
        curl_setopt($CR, CURLOPT_POSTFIELDS, json_encode($strRequest));
        curl_setopt($CR, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($CR, CURLOPT_SSL_VERIFYPEER, true);
        //curl_setopt($CR, CURLOPT_USERPWD, "avishag.tzur@gmail.com:8898mendi");
        //curl_setopt($CR, CURLOPT_SSL_VERIFYHOST, true);

        curl_setopt($CR, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
        ));

        //actual curl execution perfom
        $result = curl_exec($CR);
        $error = curl_error($CR);

        curl_close($CR);
        $result = json_decode($result);
        echo $error;
        debug($result);
        return $result;
    }

    public function cellcomSimStateChange($phone, $newState)
    {
        $newState = $newState ? 'A' : 'RNTN';

        $url = 'https://connect.cellcom.co.il:8080/ipa/apis/json/provisioning/updateProvisioningData';
        $CR = curl_init();
        $strRequest = array(
            'username' => 'mohammad',
            'password' => 'Mm112233!',
            'actions' => array(array(
                "actionType" => "SIM_STATE_CHANGE",
                "targetValue" => $newState,
                "targetId" => "",
                "subscribers" => array(array(
                    "neId" => $phone
                )),
            ))
        );
        curl_setopt($CR, CURLOPT_URL, $url);
        curl_setopt($CR, CURLOPT_POST, true);
        curl_setopt($CR, CURLOPT_FAILONERROR, true);
        curl_setopt($CR, CURLOPT_POSTFIELDS, json_encode($strRequest));
        curl_setopt($CR, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($CR, CURLOPT_SSL_VERIFYPEER, true);

        curl_setopt($CR, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
        ));

        //actual curl execution perfom
        $result = curl_exec($CR);
        $error = curl_error($CR);

        curl_close($CR);
        $result = json_decode($result);
        return $result;
    }

    public function cellcomProviderToken1()
    {


        //$url = 'https://apigwqa.cellcom.co.il:4433/api/services/getProviderToken';
        //$url = 'https://connect.cellcom.co.il:8080/ipa/apis/json/general/login';
        $url = 'https://connect.cellcom.co.il:8080/ipa/apis/json/provisioning/getProvisioningParameterList';
        $CR = curl_init();
        $strRequest = array(
            'username' => 'mohammad',
            'password' => 'Mm112233!',
        );
        curl_setopt($CR, CURLOPT_URL, $url);
        curl_setopt($CR, CURLOPT_POST, true);
        curl_setopt($CR, CURLOPT_FAILONERROR, true);
        curl_setopt($CR, CURLOPT_POSTFIELDS, json_encode($strRequest));
        curl_setopt($CR, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($CR, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($CR, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
        ));

        //actual curl execution perfom
        $result = curl_exec($CR);
        $error = curl_error($CR);

        curl_close($CR);
        $result = json_decode($result);
        echo $error;
        debug($result);
        return $result;
    }

    function getPaymentLeads()
    {
        //$date = date('Y-m-d', strtotime($_POST['checkIn']));
        $paymentId = intval($_POST['paymentId']);
        $paymentLeads = $this->db->query("SELECT pl.phone, cpl.* FROM customers_payments_leads as cpl
                                                INNER JOIN phone_lines as pl ON pl.leadId = cpl.leadId
                                                WHERE cpl.cpId = " . $paymentId . "
                                                             ")->result();
        //debug($this->db->last_query());
        $out = '';
        foreach ($paymentLeads as $p) {

            $out .= '<tr onclick="window.open(root + \'admin/leads/viewLead/\' + ' . $p->leadId . ');">';
            $out .= '<td></td>';
            $out .= '<td>' . $p->phone . '</td>';
            $out .= '<td>' . $p->price . ' ₪</td>';
            $out .= '</tr>';
            $p = null;
        }
        //debug($out);
        echo json_encode(array('result' => true, 'data' => $out, 'cnt' => count($paymentLeads)));
    }

    function renewLines()
    {
        $data = $_POST['data'];
        //$data['autoRenew'] = date('Y-m-d', strtotime(str_replace('/','-',$data['endDate'])));
        $i = 0;
        foreach ($data['leadId'] as $l) {
            if (!isset($data['eDate'])) $data['eDate'] = 'month';
            $this->renewPhoneLine($l, $data['eDate'], true);
            $i++;
        }
        $this->session->set_flashdata('flashMsgType', 'Success');
        $this->session->set_flashdata('flashMsg', 'בוצעה הארכה ל -  ' . $i . ' מנויים');
        echo json_encode(array('result' => true, ''));
    }

    function renewPhoneLine($leadId = '', $timeStr = '', $isBulk = false)
    {
        if ($leadId == '') {
            $timeStr = htmlspecialchars($_POST['timeStr']);
            $leadId = intval($_POST['leadId']);
        }

        $lead = $this->general_model->getRowById('leads', 'leadId', $leadId);
        $findPhone = $this->general_model->getRowById('phone_lines', 'leadId', $leadId);
        $customer = $this->general_model->getRowById('customers', 'customerId', $findPhone->customerId);
        $campaign = $this->general_model->getRowById('campaigns', 'campaignId', $lead->campaignId);
        if (!empty($findPhone)) {
            if ($lead->status == 2) {
                $endDate = addCalendaricMonths($findPhone->serviceEndDate, 1); //
                if ($timeStr != 'month') {

                    $endDate = date('Y-m-d', strtotime(str_replace('/', '-', $timeStr)));
                    if ($endDate != addCalendaricMonths($findPhone->serviceEndDate, 1)) {
                        $tt = (strtotime($endDate) - strtotime($findPhone->serviceEndDate)) / 3600 / 24;
                        $findPhone->priceSupplier = round((floor($tt)) * ($findPhone->priceSupplier  / 30), 2);
                        $findPhone->priceOperator = round((floor($tt)) * ($findPhone->priceOperator  / 30), 2);
                    }
                }
            } else {
                $endDate = addCalendaricMonths(date('Y-m-d'), 1); //, strtotime($findPhone->serviceEndDate)
                if ($timeStr != 'month') {

                    $endDate = date('Y-m-d', strtotime(str_replace('/', '-', $timeStr)));
                    if ($endDate != addCalendaricMonths(date('Y-m-d'), 1)) {
                        $tt = (strtotime($endDate) - time()) / 3600 / 24;
                        $findPhone->priceSupplier = round((floor($tt)) * ($findPhone->priceSupplier  / 30), 2);
                        $findPhone->priceOperator = round((floor($tt)) * ($findPhone->priceOperator  / 30), 2);
                    }
                }
            }

            if ($findPhone->rashutPackagePrice > 0) {
                $findPhone->priceSupplier += $findPhone->rashutPackagePrice;
                $findPhone->priceOperator += $findPhone->rashutPackagePrice;
            }

            //debug($findPhone->priceSupplier);
            if (($customer->credits + $customer->creditsLimit) < $findPhone->priceSupplier && !$customer->allowDebt) {
                if (!$isBulk) {
                    echo json_encode(array('result' => false, 'msg' => 'שגיאה 200'));
                    return;
                }
            }

            $this->general_model->updateRowById('phone_lines', 'leadId', $leadId, array('serviceStartDate' => date('Y-m-d'), 'serviceEndDate' => $endDate));

            $cpData = array(
                'customerId' => $customer->customerId,
                'total' => $findPhone->priceSupplier,
                'title' => 'lead_payment',
                'qty' => 1,
                'adminId' => $customer->parentId,
                'cpDate'  => date('Y-m-d H:i:s'),
                'creationDate'  => date('Y-m-d H:i:s'),
                'lastUpdate'    => date('Y-m-d H:i:s')
            );

            if (($customer->credits + $customer->creditsLimit) < $findPhone->priceSupplier && !$customer->allowDebt) {
                //$this->session->set_flashdata('flashMsgType', 'Error');
                //$this->session->set_flashdata('flashMsg','יתרת הלקוח אינה מאפשרת תשלום');
                $cpData['isPaid'] = 0;
            } else {
                $credit = $customer->credits - $findPhone->priceSupplier;
                $r = $this->general_model->updateRowById('customers', 'customerId', $customer->customerId, array('credits' => $credit, 'lastUpdate' => date('Y-m-d H:i:s')));
                $cpData['isPaid'] = 1;
            }
            $resultCp = $this->general_model->insertRow('customers_payments', $cpData);

            $cplData = array('leadId' => $leadId, 'cpId' => $resultCp, 'price' => $findPhone->priceSupplier);
            $resultCp = $this->general_model->insertRow('customers_payments_leads', $cplData);

            if ($customer->parentId != 1) {
                $customerP = $this->general_model->getRowById('customers', 'customerId', $customer->parentId);
                $cpDataP = array(
                    'customerId' => $customer->parentId,
                    'total' => $findPhone->priceOperator,
                    'title' => 'supplier_payment',
                    'qty' => 1,
                    'adminId' => 1,
                    'cpDate'  => date('Y-m-d H:i:s'),
                    'creationDate'  => date('Y-m-d H:i:s'),
                    'lastUpdate'    => date('Y-m-d H:i:s')
                );

                $creditP = $customerP->credits - $findPhone->priceOperator;
                $r = $this->general_model->updateRowById('customers', 'customerId', $customerP->customerId, array('credits' => $creditP, 'lastUpdate' => date('Y-m-d H:i:s')));
                $cpDataP['isPaid'] = 1;

                $resultCpP = $this->general_model->insertRow('customers_payments', $cpDataP);

                $cplDataP = array('leadId' => $leadId, 'cpId' => $resultCpP, 'price' => $findPhone->priceOperator);
                $resultCp = $this->general_model->insertRow('customers_payments_leads', $cplDataP);
            }

            if ($lead->status != 2) {
                $data = array(
                    'leadId'        => $leadId,
                    'userId'       => getUserId(),
                    'text'         => 'עדכון סטטוס <strong>פעיל</strong>',
                    'creationDate' => date('Y-m-d H:i:s'),
                );
                $this->general_model->insertRow('lead_comments', $data);
                $this->general_model->updateRowById('leads', 'leadId', $leadId, array('status' => 2, 'lastUpdate' => date('Y-m-d H:i:s')));
                if ($campaign->campaignDesc == 'cellcom') {
                    $r = cellcomSimStateChange($lead->phone, 1);
                    $apiMsg = 'Cellcom API: <strong>' . $r->result . '</strong>';
                    $dataA = array(
                        'leadId' => $leadId,
                        'userId'  => getUserId(),
                        'adminId'      => getAdminId(),
                        'text' => $apiMsg,
                        'creationDate'    => date('Y-m-d H:i:s'),
                    );
                    $this->general_model->insertRow('lead_comments', $dataA);
                }

                if ($campaign->campaignDesc == 'hot') {
                    $r = hotManuiActions($lead->phone, 2);
                    $apiMsg = 'HOT API: <strong>' . $r->mirreturn_message . '</strong>';
                    $dataA = array(
                        'leadId' => $leadId,
                        'userId'  => getUserId(),
                        'adminId'      => getAdminId(),
                        'text' => $apiMsg,
                        'creationDate'    => date('Y-m-d H:i:s'),
                    );
                    $this->general_model->insertRow('lead_comments', $dataA);
                }
                if ($campaign->campaignDesc == 'golan') {
                    $r = golanRobotAction($lead->phone, 5);
                    sleep(1);
                    $r = golanRobotAction($lead->phone, 2);
                    $rd = json_decode($r);
                    $apiMsg = 'GOLAN API: <strong>OK</strong> ' . $rd->task;
                    $dataA = array(
                        'leadId' => $leadId,
                        'userId'  => getUserId(),
                        'adminId'      => getAdminId(),
                        'text' => $apiMsg,
                        'creationDate'    => date('Y-m-d H:i:s'),
                    );
                    $this->general_model->insertRow('lead_comments', $dataA);
                }

                if ($campaign->campaignDesc == 'we4g') {

                    if ($findPhone->isTempBlock == "0") {

                        $we4g_ID = $_POST['we4g_ID'];

                        $r = freezeEndWE4G($we4g_ID, 0);

                        echo $r;
                    }

                    if ($findPhone->isTempBlock == "1") {

                        $phone_number = $_POST['phone_number'];

                        $r = removefreezeLineWE4Gtemp($phone_number, 0);

                        echo $r;

                        $tempBlock = $this->general_model->updateRowById('phone_lines', 'leadId', $leadId, array('isTempBlock' => '0', 'lastUpdate' => date('Y-m-d H:i:s')));
                    }
                }
            }

            if ($campaign->campaignDesc == 'ramilevy') {
                $r = ramilevyChargeApi($lead->phone, $campaign->campaignId);
                $res = $r['status'] ? 'OK' : $r['result'];
                $apiMsg = 'Rami Levy API: <strong>' . $res . '</strong> - טעינה';
                $dataA = array(
                    'leadId' => $leadId,
                    'userId'  => getUserId(),
                    'adminId'      => getAdminId(),
                    'text' => $apiMsg,
                    'creationDate'    => date('Y-m-d H:i:s'),
                );
                $this->general_model->insertRow('lead_comments', $dataA);
                /*
                if(strpos($r->mirreturn_message, 'Success') > -1) {

                } else {
                    $createTask = true;
                }
                */
                $createTask = true;
            }

            $data = array(
                'leadId'        => $leadId,
                'userId'       => getUserId(),
                'text'         => 'הארכה למנוי עד לתאריך: ' . date('d/m/Y', strtotime($endDate)),
                'creationDate' => date('Y-m-d H:i:s'),
            );
            $this->general_model->insertRow('lead_comments', $data);
            //debug($endDate);
            if (!$isBulk) echo json_encode(array('result' => true, 'msg' => ''));
        } else {
            //$resultP = $this->general_model->insertRow('phone_lines', $dataSql);
            if (!$isBulk) echo json_encode(array('result' => false, 'msg' => ''));
        }
        return;
    }

    function changeLinePrice()
    {


        $data = $_POST['data'];
        $data['creationDate'] = date('Y-m-d H:i:s');
        $newPrice = floatval($data['price']);
        $priceType = htmlspecialchars($data['priceType']);
        $i = 0;
        if ($priceType != '' && $newPrice > 0) {
            foreach ($data['leadId'] as $l) {

                $result = $this->general_model->updateRowById('phone_lines', 'leadId', $l, array($priceType => $newPrice, 'lastUpdate' => date('Y-m-d H:i:s')));
                $i++;
            }
            $this->session->set_flashdata('flashMsgType', 'Success');
            $this->session->set_flashdata('flashMsg', 'עודכן מחיר ל ' . $i . ' מנויים.');
            echo json_encode(array('result' => true, ''));
        } else {
            echo json_encode(array('result' => false, 'msg' => ''));
        }
        //debug($where);


    }

    function refundCustomerLead($customerId, $SPrice, $OPrice, $leadId)
    {
        $customerData = $this->general_model->getRowById('customers', 'customerId', $customerId);
        $cpData = array(
            'customerId' => $customerId,
            'total' => (-1) * $SPrice,
            'title' => 'lead_payment',
            'qty' => 1,
            'adminId' => $customerData->parentId,
            'cpDate'  => date('Y-m-d H:i:s'),
            'creationDate'  => date('Y-m-d H:i:s'),
            'lastUpdate'    => date('Y-m-d H:i:s')
        );

        $credit = $customerData->credits + $SPrice;
        $r = $this->general_model->updateRowById('customers', 'customerId', $customerId, array('credits' => $credit, 'lastUpdate' => date('Y-m-d H:i:s')));
        $cpData['isPaid'] = 1;

        $resultCp = $this->general_model->insertRow('customers_payments', $cpData);
        $cplData = array('leadId' => $leadId, 'cpId' => $resultCp, 'price' => $SPrice);
        $resultCp = $this->general_model->insertRow('customers_payments_leads', $cplData);

        if ($customerData->parentId > 1) {
            $customerP = $this->general_model->getRowById('customers', 'customerId', $customerData->parentId);
            $cpDataP = array(
                'customerId' => $customerData->parentId,
                'total' => (-1) * $OPrice,
                'title' => 'supplier_payment',
                'qty' => 1,
                'adminId' => 1,
                'cpDate'  => date('Y-m-d H:i:s'),
                'creationDate'  => date('Y-m-d H:i:s'),
                'lastUpdate'    => date('Y-m-d H:i:s')
            );

            $creditP = $customerP->credits + $OPrice;
            $r = $this->general_model->updateRowById('customers', 'customerId', $customerP->customerId, array('credits' => $creditP, 'lastUpdate' => date('Y-m-d H:i:s')));
            $cpDataP['isPaid'] = 1;

            $resultCpP = $this->general_model->insertRow('customers_payments', $cpDataP);

            $cplDataP = array('leadId' => $leadId, 'cpId' => $resultCpP, 'price' => $OPrice);
            $resultCp = $this->general_model->insertRow('customers_payments_leads', $cplDataP);
        }
        return;
    }

    function sendNiyudCodeRamiLevy()
    {

        $phone = htmlspecialchars($_POST['phone']);
        //$a = ramilevySmsCode($phone);
        $a['status'] = 1;
        if ($a['status']) echo json_encode(array('result' => true, 'msg' => ''));
        else echo json_encode(array('result' => false, 'msg' => ''));
    }

    function niyudRamiLevy()
    {

        $leadId = intval($_POST['leadId']);
        $lead = $this->general_model->getRowById('leads', 'leadId', $leadId);
        $findPhone = $this->general_model->getRowById('phone_lines', 'leadId', $leadId);

        if (isset($_POST['niyudCode']) && $_POST['niyudCode'] != '') {
            $r = ramilevyActivateSim($findPhone->sim, $_POST['niyudCode']);
            $res = $r['status'] ? 'OK' : $r['result'];
            $apiMsg = 'Rami Levy API: <strong>' . $res . '</strong>';
            $dataA = array(
                'leadId' => $leadId,
                'userId'  => getUserId(),
                'adminId'      => getAdminId(),
                'text' => $apiMsg,
                'creationDate'    => date('Y-m-d H:i:s'),
            );
            $this->general_model->insertRow('lead_comments', $dataA);
            sleep(2);
        }

        $r = ramilevyChargeApi($lead->phone, $lead->campaignId);
        $res = $r['status'] ? 'OK' : $r['result'];
        $apiMsg = 'Rami Levy API: <strong>' . $res . '</strong> - טעינה';
        $dataA = array(
            'leadId' => $leadId,
            'userId'  => getUserId(),
            'adminId'      => getAdminId(),
            'text' => $apiMsg,
            'creationDate'    => date('Y-m-d H:i:s'),
        );
        $this->general_model->insertRow('lead_comments', $dataA);
        echo json_encode(array('result' => true, 'msg' => ''));

        //else echo json_encode(array( 'result' => false, 'msg' => '' ));
        return;
    }

    function checkGolanQueueStatus()
    {

        $phone = $_POST['phone'];
        //$phone = $_POST['data']['phone'];
        $re = getGolanSubId($phone);

        if (isset($re->msg)) {
            if ($re->msg->freeze === 0 || $re->msg->freeze === false) {
                $freeze_status = 'לא מוקפא - Not Freezed';
            } else {
                $freeze_status = 'מוקפא - Freezed';
            }

            if ($re->msg->status == 'line_status_active') {
                $active = 'מחובר';
            } else {
                $active = 'לא מחובר';
            }
            $msg = array(
                'freeze'    => $freeze_status,
                'iccid'     => $re->msg->iccid,
                'id'        => $re->msg->id,
                'status'    => $active
            );
            echo json_encode(array('result' => true, 'msg' => $msg));
        } else {
            echo json_encode(array('result' => false, 'msg' => ''));
        }
    }


    public function sendSmsBulkToCustomers()
    {

        $data = $_POST['data'];
        //$data['creationDate'] = date('Y-m-d H:i:s');
        $i = $j = $k = $result = 0;
        $lcS = $this->db->query('SELECT * FROM customers as c
                                        INNER JOIN users as u ON c.adminId = u.userId
                                        WHERE c.customerId IN (' . $data['leadId'] . ') ')->result();


        if (1 == 1) {

            $from = htmlspecialchars($data['fromName']) != '' ? htmlspecialchars($data['fromName']) : 'SMS';
            $url = "https://019sms.co.il/api";
            $xml = '
            <?xml version="1.0" encoding="UTF-8"?>
            <bulk>
            <user>
            <username>callup</username>
            <password>callup2010</password>
            </user>
            <messages>';

            foreach ($lcS as $lc) {
                if ($lc->phoneNumber == '') continue;

                $con = str_replace('{{fullname}}', $lc->customerName, $data['content']);
                $con = str_replace('{{email}}', $lc->email, $con);
                $con = str_replace('{{id}}', $lc->customerId, $con);
                $xml .= '
                <sms>
                <source>' . $from . '</source>
                <destinations>
                <phone id="' . $lc->phoneNumber . '">' . substr($lc->phoneNumber, 1) . '</phone>
                </destinations>
                <message>' . substr($con, 0, 310) . '</message>
                </sms>';
                $i++;
            }
            $xml .= '
            </messages>
            <response>0</response>
            </bulk>';
            $CR = curl_init();
            curl_setopt($CR, CURLOPT_URL, $url);
            curl_setopt($CR, CURLOPT_POST, 1);
            curl_setopt($CR, CURLOPT_FAILONERROR, true);
            curl_setopt($CR, CURLOPT_POSTFIELDS, $xml);
            curl_setopt($CR, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($CR, CURLOPT_HTTPHEADER, array("charset=utf-8"));
            $result = curl_exec($CR);
            $error = curl_error($CR);

            if ($error) {
                ob_end_clean();
                echo json_encode(array('result' => false, 'msg' => 'אירעה שגיאה!', 'error' => $error));
            } else {
                $response = new SimpleXMLElement($result);
                $response = xml2array($response);

                if ($response['status'] == '0' || $response['status'] == '4' && $i > 0) {
                    /*
                    foreach($lcS as $lc) {
                        $con = str_replace('{{fullname}}', $lc->customerName, $data['content']);
                        $con = str_replace('{{email}}', $lc->email, $con);
                        $con = str_replace('{{id}}', $lc->customerId, $con);

                        $cmtText = 'נשלח SMS: <strong>'.$con.'</strong>';
                        $cmtData = array( 'lcId'         => $lc->lcId,
                                          'userId'       => getUserId(),
                                          'adminId'      => getAdminId(),
                                          'text'         => $cmtText,
                                          'creationDate' => date('Y-m-d H:i:s')                    );
                        //$resultC = $this->general_model->insertRow('lc_comments', $cmtData);
                    }
                    //$this->general_model->updateRowById('leads_customers', 'lcId', $lc->lcId, array('lastUpdate' => date('Y-m-d H:i:s')));
                    //$this->general_model->updateRowById('customers', 'customerId', getAdminId(), array('smsQty' => $customerData->smsQty-count($lcS)));
                    */
                    echo json_encode(array('result' => true, 'msg' => $i . ' הודעות SMS נשלחו בהצלחה!'));
                } else {
                    //echo $CI->email->print_debugger();
                    ob_end_clean();
                    echo json_encode(array('result' => false, 'msg' => 'אירעה שגיאה!', 'error' => $response));
                }
            }
        } else {
            echo json_encode(array('result' => false, 'msg' => 'אין יתרת הודעות לשליחה.'));
        }
    }

    public function getSmsTemplate($bulk = 0)
    {
        $data = $_POST['data'];
        $stId = intval($data['stId']);

        if ($stId) {

            $smsTemplate = $this->general_model->getRowById('sms_templates', 'stId', $stId);
            if (!$bulk) {
                $lcId = intval($data['leadId']);
                $lc = $this->db->query('SELECT * FROM leads_customers WHERE lcId = ' . $lcId . ' AND customerId = ' . getAdminId())->row();

                $smsTemplate->content = str_replace('{{fullname}}', getLeadName($lc->leadId), $smsTemplate->content);
                $smsTemplate->content = str_replace('{{email}}', getLeadEmail($lc->leadId), $smsTemplate->content);
                $smsTemplate->content = str_replace('{{id}}', $lc->lcId, $smsTemplate->content);
                $smsTemplate->content = str_replace('{{username}}', $this->session->userdata('userData')->firstname, $smsTemplate->content);
                $smsTemplate->content = str_replace('{{useremail}}', $this->session->userdata('userData')->email, $smsTemplate->content);
                $smsTemplate->content = str_replace('{{userphone}}', formatPhone($this->session->userdata('userData')->phone), $smsTemplate->content);
            }
            echo json_encode(array('result' => true, 'data' => array(
                'body' => strip_tags($smsTemplate->content),
                'smsFrom' => $smsTemplate->subject
            )));
        } else {
            echo json_encode(array('result' => false));
        }
    }

    function resetArl()
    {
        $arId = intval($_POST['arId']);
        $r = $this->general_model->updateRowById('api_requests_log', 'arId', $arId, array('result' => '', 'creationDate' => date('Y-m-d H:i:s')));
        if ($r) echo json_encode(array('result' => true, ''));
        else echo json_encode(array('result' => false));
    }

    function deleteArl()
    {
        $data = $_POST;
        $r = $this->general_model->deleteRowById('api_requests_log', 'arId', intval($_POST['arId']));
        if ($r) echo json_encode(array('result' => true));
        else echo json_encode(array('result' => false));
    }

    function getOpenTasks()
    {

        $openTasks = $this->db->query("SELECT t.*, l.campaignId FROM tasks as t
                                                LEFT JOIN leads as l ON t.leadId = l.leadId
                                                WHERE t.status IN(1,6) ORDER BY t.status ASC, t.rating DESC, t.lastUpdate DESC")->result();
        if ($this->session->userdata('userLevel') == 2 && $this->session->userdata('userData')->allowedCampaigns != '') {
            $campsAllowed = explode(',', $this->session->userdata('userData')->allowedCampaigns);

            $where = '';
            foreach ($campsAllowed as $c) {
                $where .= " campaignDesc LIKE '" . $c . "' OR ";
            }
            $campaigns = reindex_by_key($this->db->query("SELECT * FROM campaigns as c
                                       WHERE $where isActive = 100

                                                  ")->result(), 'campaignId');
            $iDs = implode(',', array_keys($campaigns));
            $openTasks = $this->db->query("SELECT t.*, l.campaignId FROM tasks as t
                                                LEFT JOIN leads as l ON t.leadId = l.leadId
                                                WHERE t.status IN(1,6)
                                                AND l.campaignId IN ($iDs)
                                                ORDER BY t.status ASC, t.rating DESC, t.lastUpdate DESC")->result();
        }
        $cnts['openTasksCnt'] = count($openTasks);

        //debug($this->db->last_query());
        $statuses = reindex_by_key($this->general_model->getLeadStatuses(), 'lsId');
        $customers = reindex_by_key($this->db->query("SELECT customerId, customerName FROM customers")->result(), 'customerId');

        $out = '';
        foreach ($openTasks as $p) {

            $out .= '<tr onclick="window.open(root + \'admin/tasks/viewTask/\' + ' . $p->taskId . ');">';
            $out .= '<td>' . formatDateTime($p->creationDate) . '</td>';

            $out .= '<td>' . $p->subject . '</td>';
            $out .= '<td>' . $p->text . '</td>';
            if (isset($customers[$p->adminId])) $out .= '<td><span class="label label-primary" style="text-align: center!important; color: #fff;">' . $customers[$p->adminId]->customerName . '</span></td>';
            else $out .= '<td></td>';
            $out .= '<td class="text-center">
                        <span class="label" style="text-align: center; color: #fff; background-color: ' . $statuses[$p->status]->lsColor . ';">' . $statuses[$p->status]->title_he . '</span>
                    </td>';
            $out .= '</tr>';
        }

        //debug($out);
        echo json_encode(array('result' => true, 'data' => $out, 'cnt' => count($openTasks)));

        return;
    }

    function insertBoardMessage()
    {
        $allowedUsers       = is_array($_POST['usersId']) ? implode(',', $_POST['usersId']) : '';
        $notallowedUsers    = is_array($_POST['notusersId']) ? implode(',', $_POST['notusersId']) : '';
        $mType    = $_POST['mType'];
        $data = array(
            'content' => $_POST['content'],
            'contentArabic' => $_POST['contentArabic'],
            'allowedCustomers'  => $allowedUsers,
            'notAllowedCustomers'  => $notallowedUsers,
            'customerId'    => getAdminId(),
            'userId'        => getUserId(),
            'providerImage' => $_POST['providerImage'],
            'mType'         => $mType,
            'creationDate'  => date('Y-m-d H:i:s')
        );
        //debug($data);
        $result = $this->general_model->insertRow('customer_messages', $data);

        if ($result) {
            echo json_encode(array('result' => true));
        } else {
            echo json_encode(array('result' => false));
        }
    }

    public function removeBoardMessage($cmId)
    {

        $result = $this->db->query("SELECT customerId FROM customer_messages WHERE cmId = '" . intval($cmId) . "' AND customerId = '" . getAdminId() . "' LIMIT 1")->row()->customerId;

        if ($result == getAdminId()) {
            $result = $this->general_model->deleteRowById('customer_messages', 'cmId', intval($cmId));
            echo json_encode(array('result' => true));
        } else {
            echo json_encode(array('result' => false));
        }
    }

    public function getText2VoiceStatus()
    {
        $out = '';
        $leadId = intval($_POST['leadId']);
        $line = $this->general_model->getRowById('phone_lines', 'leadId', intval($leadId));
        $result = text2voiceStatus($line->phone);
        if ($result) {
            if ($result->status == 'Active') {
                $out .= '<div class="text-right"><p>Status: ' . $result->status . '</p>';
                $out .= '<p>Expire: ' . date('d/m/Y', strtotime($result->valid_to)) . '</p></div>';
            } else {
                $out .= '<div class="text-right"><p>Status: ' . $result->status . '</p>';
                $out .= '</div><br />';
                $out .= '<label class="select"><select class="input-lg" id="tvBundleSelect">';
                $out .= '<option value="1">חודש</option>';
                $out .= '<option value="3">6 חודשים</option>';
                $out .= '<option value="4">12 חודשים</option>';
                $out .= '</select></label>';
                $out .= '<a id="tvPurchaseBtn" class="btn btn-warning btn-lg" style="margin-right: 10px;"><i class="fa fa-plus"></i> רכישה</a>';
            }

            echo json_encode(array('result' => true, 'msg' => $out));
        } else {
            echo json_encode(array('result' => false));
        }
    }

    public function purchaseText2VoiceBundle()
    {
        $customerPrice = 30;
        $supplierPrice = 25;
        $operatorPrice = 20;

        $leadId = intval($_POST['leadId']);
        $bundle = intval($_POST['bundle']);
        $findPhone = $this->general_model->getRowById('phone_lines', 'leadId', intval($leadId));
        if (!in_array($bundle, array(1, 3, 4))) return;
        $result = objectToArray(text2voiceAction($findPhone->phone, $bundle));
        if ($result['status'] == 1 && $result['Approve Number'] != '') {

            if ($bundle == 3) $bundle = 6;
            if ($bundle == 4) $bundle = 12;

            $plData = array('text2voice' => 1, 'text2voiceEndDate' => addCalendaricMonths(date('Y-m-d'), $bundle), 'lastUpdate' => date('Y-m-d H:i:s'));
            $this->general_model->updateRowById('phone_lines', 'leadId', $leadId, $plData);
            $customer = $this->general_model->getRowById('customers', 'customerId', $findPhone->customerId);
            $cpData = array(
                'customerId' => $customer->customerId,
                'total' => $supplierPrice,
                'title' => 'textvoice_payment',
                'comment' => 'TextVoice',
                'qty' => 1,
                'adminId' => $customer->parentId,
                'cpDate'  => date('Y-m-d H:i:s'),
                'creationDate'  => date('Y-m-d H:i:s'),
                'lastUpdate'    => date('Y-m-d H:i:s')
            );

            if ($customer->credits < $supplierPrice && !$customer->allowDebt) {
                //$this->session->set_flashdata('flashMsgType', 'Error');
                //$this->session->set_flashdata('flashMsg','יתרת הלקוח אינה מאפשרת תשלום');
                $cpData['isPaid'] = 0;
            } else {
                $credit = $customer->credits - $supplierPrice;
                $r = $this->general_model->updateRowById('customers', 'customerId', $customer->customerId, array('credits' => $credit, 'lastUpdate' => date('Y-m-d H:i:s')));
                $cpData['isPaid'] = 1;
            }
            $resultCp = $this->general_model->insertRow('customers_payments', $cpData);

            $cplData = array('leadId' => $leadId, 'cpId' => $resultCp, 'price' => $supplierPrice);
            $resultCp = $this->general_model->insertRow('customers_payments_leads', $cplData);

            if ($customer->parentId != 1) {
                $customerP = $this->general_model->getRowById('customers', 'customerId', $customer->parentId);
                $cpDataP = array(
                    'customerId' => $customer->parentId,
                    'total' => $operatorPrice,
                    'title' => 'textvoice_payment',
                    'comment' => 'TextVoice',
                    'qty' => 1,
                    'adminId' => 1,
                    'cpDate'  => date('Y-m-d H:i:s'),
                    'creationDate'  => date('Y-m-d H:i:s'),
                    'lastUpdate'    => date('Y-m-d H:i:s')
                );

                $creditP = $customerP->credits - $operatorPrice;
                $r = $this->general_model->updateRowById('customers', 'customerId', $customerP->customerId, array('credits' => $creditP, 'lastUpdate' => date('Y-m-d H:i:s')));
                $cpDataP['isPaid'] = 1;

                $resultCpP = $this->general_model->insertRow('customers_payments', $cpDataP);

                $cplDataP = array('leadId' => $leadId, 'cpId' => $resultCpP, 'price' => $operatorPrice);
                $resultCp = $this->general_model->insertRow('customers_payments_leads', $cplDataP);
            }


            $cmtText = 'TextVoice רכישת חבילה: <strong>' . $bundle . ' חודשים</strong>';
            $dataA = array(
                'leadId'       => $leadId,
                'userId'       => getUserId(),
                'adminId'      => getAdminId(),
                'text'         => $cmtText,
                'creationDate' => date('Y-m-d H:i:s'),
            );
            $this->general_model->insertRow('lead_comments', $dataA);
            echo json_encode(array('result' => true));
        } else {
            echo json_encode(array('result' => false));
        }
    }

    public function cellcomGetPhoneData()
    {
        $phone  = htmlspecialchars($_POST['phone']);
        $phone2 = htmlspecialchars($_POST['phone2']);
        $out = '';
        $out2 = '';
        $result = cellcomGetData($phone);
        $result2 = cellcomGetData($phone2);
        //debug($result);

        $out .= 'Result: <strong>' . $result->result . '</strong><br />';
        if ($result->count) {
            $arr = $result->data;
            foreach ($arr[0] as $r => $v) {
                $out .= '' . $r . ': <strong>' . $v . '</strong><br />';
            }
        } else {
            $out .= '<div class="text-center"><strong>לא נמצא בסלקום</strong></div>';
        }

        $out2 .= 'Result: <strong>' . $result2->result . '</strong><br />';
        if ($result2->count) {
            $arr2 = $result2->data;
            foreach ($arr2[0] as $r => $v) {
                $out2 .= '' . $r . ': <strong>' . $v . '</strong><br />';
            }
        } else {
            $out2 .= '<div class="text-center"><strong>לא נמצא בסלקום</strong></div>';
        }

        if ($result) {
            echo json_encode(array('result' => true, 'out' => $out, 'out2' => $out2));
        } else {
            echo json_encode(array('result' => false));
        }
    }

    public function partnerGetPhoneData()
    {

        $phone = htmlspecialchars($_POST['phone']);
        $phone2 = htmlspecialchars($_POST['phone2']);

        $result = partnerGetData($phone2);
        $result2 = partnerGetData($phone);

        if (!empty($result)) {
            $data_result = $result;
        } else {
            $data_result = json_encode(json_encode(array(
                'ModelBO'   => [array(
                    'ProductName'       => 0,
                    'EndDate'           => "0",
                    'CreditAmmountGB'   => 0,
                    'CreditAmmountMB'   => 0,
                    'AppliedAmountGB'   => 0,
                    'CreditAmount'      => 0,
                    'CreditAmmountMB'   => 0
                )],
            )));
        }

        if (!empty($result2)) {
            $data_result2 = $result2;
        } else {
            $data_result2 = json_encode(json_encode(array(
                'ModelBO'   => [array(
                    'ProductName'       => 0,
                    'EndDate'           => "0",
                    'CreditAmmountGB'   => 0,
                    'CreditAmmountMB'   => 0,
                    'AppliedAmountGB'   => 0,
                    'CreditAmount'      => 0,
                    'CreditAmmountMB'   => 0
                )],
            )));
        }

        echo json_encode(array("result" => true, "phone" => $phone, "details" => array(json_decode($data_result2)), "phone2" => $phone2, "details2" => array(json_decode($data_result))));
    }

    public function getTranzillaToken()
    {
        $this->load->model('creditcard_model');

        $data = array();
        foreach ($_POST['data'] as $d) {
            $data[$d['name']] = htmlspecialchars($d['value']);
        }
        $ccName         = $data['ccName'];
        $ccPersonalId   = $data['ccPersonalId'];
        $ccNumber       = $data['ccNumber'];
        $ccExpiration   = $data['ccMonth'] . $data['ccYear'];

        if ($data['ccMonth'] <= 9) {
            $ccExpiration = '0' . $data['ccMonth'] . $data['ccYear'];
        } else {
            $ccExpiration   = $data['ccMonth'] . $data['ccYear'];
        }

        $ccCvv          = $data['ccCvv'];
        $CardLastFour   = substr($ccNumber, -4);
        $token = $this->creditcard_model->tranzillaCreateToken($ccNumber);

        if ($token != '') {
            $custData = array(
                'creditCardExpiration'    => $ccExpiration,
                'creditCartLastFour'      => $CardLastFour,
                'creditCardToken'         => $token
            );

            $r = $this->general_model->updateRowById('customers', 'customerId', $data['customerId'], $custData);
            echo json_encode(array('result' => true));
        } else {
            echo json_encode(array('result' => false));
        }
        return;
    }

    public function getTranzillaTokenPP()
    {
        $this->load->model('creditcard_model');

        $data = array();
        foreach ($_POST['data'] as $d) {
            $data[$d['name']] = htmlspecialchars($d['value']);
        }
        $ccName         = $data['ccName'];
        $ccPersonalId   = $data['ccPersonalId'];
        $ccNumber       = $data['ccNumber'];
        $ccExpiration   = $data['ccMonth'] . $data['ccYear'];

        if ($data['ccMonth'] <= 9) {
            $ccExpiration = '0' . $data['ccMonth'] . $data['ccYear'];
        } else {
            $ccExpiration   = $data['ccMonth'] . $data['ccYear'];
        }

        $ccCvv          = $data['ccCvv'];
        $CardLastFour   = substr($ccNumber, -4);
        $token = $this->creditcard_model->tranzillaCreateToken($ccNumber);

        if ($token != '') {
            $custData = array(
                'creditCardExpirationPP'  => $result['expdate'],
                'creditCartLastFourPP'    => $result['ccno'],
                'creditCardTokenPP'       => $token
            );

            $r = $this->general_model->updateRowById('customers', 'customerId', $data['customerId'], $custData);
            echo json_encode(array('result' => true));
        } else {
            echo json_encode(array('result' => false));
        }
        return;
    }

    public function addParentLead()
    {
        $phone = htmlspecialchars($_POST['parentLeadPhone']);
        $leadId = htmlspecialchars($_POST['leadId']);

        $lead = $this->general_model->getRowById('leads', 'phone', $phone);

        if ($lead) {
            $dataA = array(
                'leadId'       => $leadId,
                'parentLeadId' => $lead->leadId,
                'creationDate' => date('Y-m-d H:i:s'),
            );
            $this->general_model->insertRow('leads_siblings', $dataA);
            echo json_encode(array('result' => true));
        } else {
            echo json_encode(array('result' => false));
        }
    }

    public function getWe4gPhoneNumberID()
    {

        $phone_number = $_POST['phone_number'];

        $r = getWe4gPhoneNumberID($phone_number);

        echo $r;
    }

    public function We4GgetNumberDetails()
    {

        $phone_number = $_POST['phone_number'];

        $r = We4GgetNumberDetails($phone_number);

        echo $r;
    }

    public function updateRefund()
    {

        $leadId         = $_POST['leadId'];
        $edit_amount    = $_POST['edit_amount'];
        $edit_amountP   = $_POST['edit_amountP'];

        if (isset($edit_amount)) {
            $ccc        = $this->general_model->getRowById('refunds', 'lead_id', $leadId);
            $pay        = $this->general_model->getRowById('customers_payments', 'customerId', $ccc->customerId);
            $customer   = $this->general_model->getRowById('customers', 'customerId', $pay->customerId);
            $lead       = $this->general_model->getRowById('leads', 'leadId', $leadId);
            $camp       = $this->general_model->getRowById('campaigns', 'campaignId', $lead->campaignId);

            $newCredit = $customer->credits + $edit_amount;
            $r = $this->general_model->updateRowById('customers', 'customerId', $pay->customerId, array('credits' => $newCredit, 'lastUpdate' => date('Y-m-d H:i:s')));

            $paymentData = array(
                'comment'       => 'refund_payment',
                'total'           => floatval(0 - $edit_amount),
                'title'           => 'refund_payment',
                'cpDate'          => date('Y-m-d H:i:s'),
                'adminId'         => $customer->parentId,
                'userId'          => getUserId(),
                'customerId'      => intval($pay->customerId),
                'isPaid'          => 1,
                'qty'             => 1,
                'creationDate'    => date('Y-m-d H:i:s'),
                'lastUpdate'      => date('Y-m-d H:i:s')
            );

            $resultCp = $this->general_model->insertRow('customers_payments', $paymentData);

            $cplData = array('leadId' => $leadId, 'cpId' => $resultCp, 'price' => 0 - $edit_amount);

            $resultCp = $this->general_model->insertRow('customers_payments_leads', $cplData);

            $result = $this->general_model->updateRowById('refunds', 'lead_id', $leadId, array('cpId' => $resultCp, 'amount' => $edit_amount, 'status' => '1', 'doneBy' => getUserId(), 'lastUpdate' => date('Y-m-d H:i:s')));
            $sold = $edit_amount;
            $profit_data = array(
                'userId'        => getUserId(),
                'customerId'    => intval($pay->customerId),
                'leadId'        => $leadId,
                'cost'          => !empty($ccc->days) && $ccc->days > 0 ? $camp->campaignCostPrice / $ccc->days : 0,
                'sold'          => $sold,
                'profit'        => !empty($ccc->days) && $ccc->days > 0 ? $sold - ($camp->campaignCostPrice / $ccc->days) : 0,
                'renew'         => 1,
                'days_count'    => $ccc->days,
                'dateCreation'  => date('Y-m-d H:i:s'),
                'lastUpdate'    => date('Y-m-d H:i:s')
            );
            $addProfit = $this->general_model->insertRow('leads_profits', $profit_data);

            if ($customer->parentId != 1) {

                $Pcustomer = $this->general_model->getRowById('customers', 'customerId', $customer->parentId);

                $ParentNewCredit = $Pcustomer->credits + $edit_amountP;
                $r = $this->general_model->updateRowById('customers', 'customerId', $Pcustomer->customerId, array('credits' => $ParentNewCredit, 'lastUpdate' => date('Y-m-d H:i:s')));

                $paymentData1 = array(
                    'comment'        => 'refund_payment',
                    'total'          => floatval(0 - $edit_amountP),
                    'title'          => 'refund_payment',
                    'cpDate'         => date('Y-m-d H:i:s'),
                    'adminId'        => 1,
                    'userId'         => getUserId(),
                    'customerId'     => intval($Pcustomer->customerId),
                    'isPaid'         => 1,
                    'qty'            => 1,
                    'creationDate'   => date('Y-m-d H:i:s'),
                    'lastUpdate'     => date('Y-m-d H:i:s')
                );

                $resultCp2 = $this->general_model->insertRow('customers_payments', $paymentData1);

                $cplData2 = array('leadId' => $leadId, 'cpId' => $resultCp2, 'price' => 0 - $edit_amountP);

                $resultCp3 = $this->general_model->insertRow('customers_payments_leads', $cplData2);

                $result = $this->general_model->updateRowById('refunds', 'lead_id', $leadId, array('cpId' => $resultCp2, 'amount' => $edit_amountP, 'status' => '1', 'doneBy' => getUserId(), 'lastUpdate' => date('Y-m-d H:i:s')));

                $soldP = $edit_amountP;
                $profit_data = array(
                    'userId'        => getUserId(),
                    'customerId'    => $Pcustomer->customerId,
                    'leadId'        => $leadId,
                    'cost'          => !empty($ccc->days) && $ccc->days > 0 ? $camp->campaignCostPrice / $ccc->days : 0,
                    'sold'          => $soldP,
                    'profit'        => !empty($ccc->days) && $ccc->days > 0 ? $soldP - ($camp->campaignCostPrice / $ccc->days) : 0,
                    'renew'         => 1,
                    'days_count'    => $ccc->days,
                    'dateCreation'  => date('Y-m-d H:i:s'),
                    'lastUpdate'    => date('Y-m-d H:i:s')
                );
                $addProfit = $this->general_model->insertRow('leads_profits', $profit_data);
            }
        }

        if (isset($result) && !empty($result)) {
            echo json_encode(array("result" => "true", "msg" => "Great!"));
        } else {
            echo json_encode(array("result" => "false", "msg" => "Failed!"));
        }
    }

    public function updateRefundDelete()
    {

        $leadId         = $_POST['leadId'];

        $result = $this->general_model->updateRowById('refunds', 'lead_id', $leadId, array('status' => '2', 'doneBy' => getUserId(), 'lastUpdate' => date('Y-m-d H:i:s')));

        if ($result) {
            echo json_encode(array("result" => "true", "msg" => "Great!"));
        } else {
            echo json_encode(array("result" => "false", "msg" => "Failed!"));
        }
    }

    public function DeleteRefundFinal()
    {

        $leadId         = $_POST['leadId'];

        $result = $this->general_model->deleteRowById('refunds', 'lead_id', $leadId);

        if ($result) {
            echo json_encode(array("result" => "true", "msg" => "Great!"));
        } else {
            echo json_encode(array("result" => "false", "msg" => "Failed!"));
        }
    }

    public function getHotSubscriberStatus()
    {

        $phone_number = $_POST['phone_number'];
        $phone_number2 = $_POST['phone_number2'];

        $r = hotGetSubscriberStatus($phone_number);
        $r2 = hotGetSubscriberStatus($phone_number2);

        $r_final = array(
            'first'     => json_decode($r),
            'second'    => json_decode($r2)
        );

        echo json_encode($r_final);
    }

    public function We4GgetUsageData()
    {

        $phone_number = $_POST['phone_number'];

        $r = We4GgetUsageData($phone_number);

        if (!empty($r)) {

            $result   = array(

                "result"    => true,
                "usage"     => $r->data->usages,
                "groups"    => $r->data->groups

            );

            echo json_encode($result);
        } else {
            echo json_encode(array("result" => false));
        }
    }

    public function freeUnblockWe4g()
    {

        $phone_number = $_POST['phone_number'];

        $r = freeUnblockWe4g($phone_number);

        echo json_encode($r);
    }

    public function freeblockWe4g()
    {

        $phone_number = $_POST['phone_number'];

        $r = freeblockWe4g($phone_number);

        echo json_encode($r);
    }

    public function updateFreeUnblock()
    {

        $uid = $_POST['action'];
        $rel = $_POST['rel'];
        $val = $_POST['code'];

        $result = $this->general_model->updateRowById('free_unblock_niyud', 'uID', $uid, array($rel => $val, 'dateUpdated' => date('Y-m-d H:i:s')));

        $re = $this->general_model->getRowById('free_unblock_niyud', 'uID', $uid);
        $taskId = $re->taskId;

        if ($rel == "accepted") {
            $r = $this->general_model->updateRowById('tasks', 'taskId', $taskId, array('status' => '6'));
        }
        if ($rel == "moved" && empty($re->toCompany)) {
            $lead = $this->general_model->getRowById('leads', 'leadId', $re->leadId);
            if (!empty($lead)) {
                $newPhone = '8' . substr($lead->phone, 1);
                $result1 = $this->general_model->updateRowById('phone_lines', 'leadId', $lead->leadId, array('phone' => $newPhone));
                $result2 = $this->general_model->updateRowById('leads', 'leadId', $lead->leadId, array('phone' => $newPhone, 'status' => 7));
                $cmtText = 'עדכון סטטוס ניתוק בפועל';
                $cmtData = array(
                    'leadId'        => $lead->leadId,
                    'adminId'       => 0,
                    'userId'        => getUserId(),
                    'text'          => $cmtText,
                    'creationDate'  => date('Y-m-d H:i:s')
                );
                $result     = $this->general_model->insertRow('lead_comments', $cmtData);
                $cmtText2   = 'החלפת מספר: ' . $lead->phone . ' במספר: <strong>' . $newPhone . '</strong>';;
                $cmtData2   = array(
                    'leadId'        => $lead->leadId,
                    'adminId'       => 0,
                    'userId'        => getUserId(),
                    'text'          => $cmtText2,
                    'creationDate'  => date('Y-m-d H:i:s')
                );
                $result = $this->general_model->insertRow('lead_comments', $cmtData2);
            }
        }
        if ($rel == "unblocked") {
            if (empty($re->toCompany)) {
                $r = $this->general_model->updateRowById('tasks', 'taskId', $taskId, array('status' => '30'));

                $text_id    = '18';
                $texts      = $this->general_model->getRowById('task_comments_texts', 'text_id', $text_id);
                $task       = $this->general_model->getRowById('tasks', 'taskId', $taskId);
                $lead       = $this->general_model->getRowById('leads', 'leadId', $task->leadId);

                $cmtData = array(
                    'taskId'       => $taskId,
                    'userId'       => getUserId(),
                    'text'         => $texts->text_he,
                    'text_id'      => $text_id,
                    'isCall'       => '',
                    'creationDate' => date('Y-m-d H:i:s')
                );

                $result = $this->general_model->insertRow('task_comments', $cmtData);

                $notification_data = array(
                    'customerId'    => $lead->adminId,
                    'leadId'        => $lead->leadId,
                    'isSeen'        => 0,
                    'text'          => $texts->text_he,
                    'text_id'       => $text_id,
                    'isDeleted'     => 0,
                    'isDone'        => 0,
                    'creationDate'  => date('Y-m-d H:i:s'),
                    'lastUpdate'    => date('Y-m-d H:i:s')
                );

                $add_notification = $this->general_model->insertRow('customers_notifications', $notification_data);

                $task       = $this->general_model->getRowById('tasks', 'taskId', $taskId);
                $cmtText    = $texts->text_he;
                $leadId     = $task->leadId;
                $addComment = $this->addCommentToLead($leadId, $cmtText, $text_id);
                $result     = $this->general_model->updateRowById('free_unblock_niyud', 'uID', $uid, array($rel => $val, 'date_unblock' => date('Y-m-d H:i:s')));
            } else {
                $r = $this->general_model->updateRowById('tasks', 'taskId', $taskId, array('status' => '6'));
            }
        }

        if ($result) {
            echo json_encode(array("result" => "true", "msg" => 'Success', "val" => $val));
        } else {
            echo json_encode(array("result" => "false", "msg" => "Failed!"));
        }
    }

    public function DeleteFbFinal()
    {

        $uID         = $_POST['uiD'];

        $result = $this->general_model->deleteRowById('free_unblock_niyud', 'uID', $uID);

        if ($result) {
            echo json_encode(array("result" => "true", "msg" => "Great!"));
        } else {
            echo json_encode(array("result" => "false", "msg" => "Failed!"));
        }
    }

    public function updateFbComment()
    {

        $uiD      = $_POST['uiD'];
        $comment  = $_POST['comment'];

        $r = $this->general_model->updateRowById('free_unblock_niyud', 'uiD', $uiD, array('comment' => $comment));
        $re = $this->general_model->getRowById('free_unblock_niyud', 'uID', $uiD);

        $taskId = $re->taskId;

        if ($taskId != 0) {

            $cmtData = array(
                'taskId'       => $taskId,
                'userId'       => getUserId(),
                'text'         => $comment,
                'creationDate' => date('Y-m-d H:i:s')
            );

            $result = $this->general_model->insertRow('task_comments', $cmtData);
        }

        if ($r) {
            echo json_encode(array("result" => "true", "msg" => "Success!"));
        } else {
            echo json_encode(array("result" => "false", "msg" => "Failed!"));
        }
    }

    public function deleteRefundsGroup()
    {
        $data = $_POST['leadCB'];

        foreach ($_POST['leadCB'] as $l) {
            //echo json_encode($l['value']);
            $result = $this->general_model->deleteRowById('refunds', 'refund_id', $l['value']);
        }

        if ($result) {
            echo json_encode(array("result" => true, "msg" => "Great!"));
        } else {
            echo json_encode(array("result" => false, "msg" => "Failed!"));
        }
    }

    public function markReundsAsNotActive()
    {

        $data = $_POST['leadCB'];

        foreach ($_POST['leadCB'] as $l) {
            $result = $this->general_model->updateRowById('refunds', 'refund_id', $l['value'], array('status' => '2', 'doneBy' => getUserId(), 'lastUpdate' => date('Y-m-d H:i:s')));
        }

        if ($result) {
            echo json_encode(array("result" => true, "msg" => "Great!"));
        } else {
            echo json_encode(array("result" => false, "msg" => "Failed!"));
        }
    }

    public function changeUserCompanyStatus()
    {

        $data_status     = $_POST['data_status'];
        $company_userid  = $_POST['company_userid'];

        if ($data_status == 0) {
            $r = $this->general_model->updateRowById('companies_to_user', 'id', $company_userid, array('is_active' => 1));

            if ($r) {
                echo json_encode(array("result" => true));
            } else {
                echo json_encode(array("result" => false));
            }
        }

        if ($data_status == 1) {
            $r = $this->general_model->updateRowById('companies_to_user', 'id', $company_userid, array('is_active' => 0));

            if ($r) {
                echo json_encode(array("result" => true));
            } else {
                echo json_encode(array("result" => false));
            }
        }
    }

    public function changeUserCompanyPPStatus()
    {

        $data_status     = $_POST['data_status'];
        $company_userid  = $_POST['company_userid'];

        if ($data_status == 0) {
            $r = $this->general_model->updateRowById('companies_to_user', 'id', $company_userid, array('is_active_pp' => 1));

            if ($r) {
                echo json_encode(array("result" => true));
            } else {
                echo json_encode(array("result" => false));
            }
        }

        if ($data_status == 1) {
            $r = $this->general_model->updateRowById('companies_to_user', 'id', $company_userid, array('is_active_pp' => 0));

            if ($r) {
                echo json_encode(array("result" => true));
            } else {
                echo json_encode(array("result" => false));
            }
        }
    }

    public function changeUserCompanyPOSTStatus()
    {

        $data_status     = $_POST['data_status'];
        $company_userid  = $_POST['company_userid'];

        if ($data_status == 0) {
            $r = $this->general_model->updateRowById('companies_to_user', 'id', $company_userid, array('is_active_post' => 1));

            if ($r) {
                echo json_encode(array("result" => true));
            } else {
                echo json_encode(array("result" => false));
            }
        }

        if ($data_status == 1) {
            $r = $this->general_model->updateRowById('companies_to_user', 'id', $company_userid, array('is_active_post' => 0));

            if ($r) {
                echo json_encode(array("result" => true));
            } else {
                echo json_encode(array("result" => false));
            }
        }
    }

    public function setCampaignPercentCustomer()
    {

        $percent    = $_POST['percent'];
        $campaignId = $_POST['campaignId'];

        $r = $this->general_model->updateRowById('prepaid_packages_discounts', 'dpid', $campaignId, array('discount' => $percent));

        if ($r) {
            echo json_encode(array("result" => true));
        } else {
            echo json_encode(array("result" => false));
        }
    }

    public function fetchTempNumbers()
    {

        $gb         = $_POST['gb'];
        $company    = $_POST['company'];
        if ($company == 'hot') $gb = 15;
        if ($company == 'partner') $gb = 15;

        $phones = $this->db->query("SELECT `lineId`, `phone` FROM `phone_lines` WHERE `isActive` = 0 AND `leadId` = 0 AND `lineProvider` LIKE '$company' AND `lineGb` = $gb ")->result();

        if (!empty($phones)) {

            echo json_encode(array("result" => true, "data" => $phones, "company" => $company));
        } else {
            echo json_encode(array("result" => false));
        }
    }

    public function activateNiyudCellcomTempNumber()
    {

        $lineId     = isset($_POST['lineId']) ? $_POST['lineId'] : '';
        $phone      = isset($_POST['phone']) ? $_POST['phone'] : '';
        $leadId     = isset($_POST['leadId']) ? $_POST['leadId'] : '';
        $company    = isset($_POST['company']) ? $_POST['company'] : '';

        if (!empty($lineId) && !empty($phone) && !empty($leadId) && !empty($company)) {
            $re         = $this->general_model->getRowById('phone_lines', 'lineId', $lineId);
            if (!empty($re)) {
                $sim        = $re->sim;
                $lead       = $this->general_model->getRowById('leads', 'leadId', $leadId);
                $camp       = $this->general_model->getRowById('campaigns', 'campaignId', $lead->campaignId);
                if (!empty($camp) && $camp->need_change_gb == 1) {
                    $changePackageData = array(
                        'leadId'        => $lead->leadId,
                        'phone'         => $lead->phone,
                        'packageId'     => $camp->campaignId,
                        'isDone'        => 0,
                        'doneBy'        => 0,
                        'dateCreation'  => date('Y-m-d H:i:s'),
                        'lastUpdate'    => date('Y-m-d H:i:s')
                    );
                    $create_change    = $this->general_model->insertRow('tasks_change_package', $changePackageData);
                }
                if ($company == 'cellcom') {
                    //$r          = cellcomSimStateChange($phone, 1, $sim);
                    $r  = cellcomSimStateChange($phone, 1);
                    if ($r->result == 'SUCCESS') {

                        $this->general_model->updateRowById('leads', 'leadId', $leadId, array('phone2' => $phone));

                        $apiMsg = 'Cellcom API: <strong>' . $r->result . '</strong>';
                        $dataA = array(
                            'leadId'        => $leadId,
                            'userId'        => getUserId(),
                            'adminId'       => getAdminId(),
                            'text'          => $apiMsg,
                            'creationDate'  => date('Y-m-d H:i:s'),
                        );

                        $this->general_model->insertRow('lead_comments', $dataA);

                        $cmtText = 'Cellcom API: <strong>SIM CHANGE ' . $r->result . '</strong>';
                        $cmtData = array(
                            'leadId'       => $leadId,
                            'userId'       => getUserId(),
                            'adminId'      => getAdminId(),
                            'text'         => $cmtText,
                            'creationDate' => date('Y-m-d H:i:s')
                        );

                        //$result = $this->general_model->insertRow('lead_comments', $cmtData);

                        $cmtText = 'נבחר מספר זמני:  <strong> ' . $phone . '</strong>';
                        $cmtData = array(
                            'leadId'       => $leadId,
                            'userId'       => getUserId(),
                            'adminId'      => getAdminId(),
                            'text'         => $cmtText,
                            'creationDate' => date('Y-m-d H:i:s')
                        );

                        $result = $this->general_model->insertRow('lead_comments', $cmtData);

                        $result = $this->general_model->deleteRowById('phone_lines', 'lineId', $lineId);
                        echo json_encode(array("result" => true));
                    } else {
                        echo json_encode(array("result" => false));
                    }
                }
                if ($company == 'partner') {

                    $r = partnerManuiAction($phone, '1');
                    if (!empty($r)) {
                        $this->general_model->updateRowById('leads', 'leadId', $leadId, array('phone2' => $phone));
                        $arr    = $r->ModelBO;

                        $apiMsg = 'PARTNER API Activation: <span>' . $arr->StatusReason . '</span>';
                        $dataA  = array(
                            'leadId'        => $leadId,
                            'userId'        => getUserId(),
                            'adminId'       => getAdminId(),
                            'text'          => $apiMsg,
                            'creationDate'  => date('Y-m-d H:i:s'),
                        );
                        $this->general_model->insertRow('lead_comments', $dataA);

                        $cmtText = 'נבחר מספר זמני:  <strong> ' . $phone . '</strong>';
                        $cmtData = array(
                            'leadId'       => $leadId,
                            'userId'       => getUserId(),
                            'adminId'      => getAdminId(),
                            'text'         => $cmtText,
                            'creationDate' => date('Y-m-d H:i:s')
                        );

                        $result = $this->general_model->insertRow('lead_comments', $cmtData);
                        /*
                        sleep(20);
                        $r2 = partnerSimChange($phone, $sim);
                        
                        if(isset($r2->ModelBO)) {
                            
                            $arr2   = $r2->ModelBO;
                            $status = $arr2->StatusReason;
                            $oldsim = $arr2->OldSimNumber;
                            $newsim = $arr2->NewSimNumber;
                            
                            $msg    = $status . ' - ' . $oldsim . ' > ' . $newsim;
                            
                            $apiMsg = 'PARTNER API - SIM Change: <span>'.$msg.'</span>';
                            $dataA = array( 'leadId'        => $leadId,
                                            'userId'        => getUserId(),
                                            'adminId'       => getAdminId(),
                                            'text'          => $apiMsg,
                                            'creationDate'  => date('Y-m-d H:i:s'),
                                            );
                            $this->general_model->insertRow('lead_comments', $dataA);
                            
                        }else{
                            $msg    = isset($r2->ErrorMsg) ? $r2->ErrorMsg : 'Unknown';
                            $apiMsg = ' - PARTNER API - SIM Change: <span>ERROR: '.$msg.'</span>';
                            $dataA  = array('leadId'        => $leadId,
                                            'userId'        => getUserId(),
                                            'adminId'       => getAdminId(),
                                            'text'          => $apiMsg,
                                            'creationDate'  => date('Y-m-d H:i:s'),
                                            );
                            $this->general_model->insertRow('lead_comments', $dataA);
                        }
                        */
                        $result = $this->general_model->deleteRowById('phone_lines', 'lineId', $lineId);
                        echo json_encode(array("result" => true));
                    } else {
                        echo json_encode(array("result" => false));
                    }
                }
                if ($company == 'hot') {

                    $r = hotManuiActions($phone, 2);

                    $apiMsg = 'HOT API: <strong>' . $r->mirreturn_message . '</strong>';
                    $dataA = array(
                        'leadId'        => $leadId,
                        'userId'        => getUserId(),
                        'adminId'       => getAdminId(),
                        'text'          => $apiMsg,
                        'creationDate'  => date('Y-m-d H:i:s'),
                    );
                    $this->general_model->insertRow('lead_comments', $dataA);
                    $this->general_model->updateRowById('leads', 'leadId', $leadId, array('phone2' => $phone));
                    $findPhone      = $this->general_model->getRowById('phone_lines', 'phone', $lead->phone);

                    $cmtText = 'נבחר מספר זמני:  <strong> ' . $phone . '</strong>';
                    $cmtData = array(
                        'leadId'       => $leadId,
                        'userId'       => getUserId(),
                        'adminId'      => getAdminId(),
                        'text'         => $cmtText,
                        'creationDate' => date('Y-m-d H:i:s')
                    );

                    $result = $this->general_model->insertRow('lead_comments', $cmtData);
                    /*
                    sleep(25);
                    
                    $r = hotManuiActions($phone, 3, $findPhone->sim, $sim);
                    
                    if(strpos($r->mirreturn_message, 'Success') > -1) {
                        $apiMsg = 'HOT API SIM CHANGE*: <strong>'.$r->mirreturn_message.'</strong>';
                    } else {
                        $apiMsg = 'HOT API SIM CHANGE*: <strong>'.$r->mirreturn_message.'</strong>';
                    }
                    
                    $cmtData = array( 'leadId'       => $leadId,
                                      'userId'       => getUserId(),
                                      'adminId'      => getAdminId(),
                                      'text'         => $apiMsg,
                                      'creationDate' => date('Y-m-d H:i:s')
                                      );
                                      
                    $result = $this->general_model->insertRow('lead_comments', $cmtData);
                    
                    if($findPhone->sim != '') {
                        $cmtData = array( 'leadId'       => $leadId,
                                          'userId'       => getUserId(),
                                          'adminId'      => getAdminId(),
                                          'text'         => 'סים ישן: '.$findPhone->sim .' - סים חדש: '. $sim,
                                          'creationDate' => date('Y-m-d H:i:s')
                                          );
                        $result = $this->general_model->insertRow('lead_comments', $cmtData);
                    }
                    */
                    $result = $this->general_model->deleteRowById('phone_lines', 'lineId', $lineId);

                    echo json_encode(array("result" => true));
                }
            } else {
                echo json_encode(array("result" => false));
            }
        } else {
            echo json_encode(array("result" => false));
        }
    }


    public function deactivateNiyudCellcomTempPhone()
    {

        $gb         = $_POST['gb'];
        $phone      = $_POST['phonetemp'];
        $leadId     = $_POST['leadId'];
        $company    = $_POST['company'];
        $lead      = $this->general_model->getRowById('leads', 'leadId', $leadId);
        if ($lead->temp_freezed == 0) {
            if ($company == 'cellcom') {
                $r          = cellcomSimStateNotActive($phone);
                if ($r->result == 'SUCCESS') {

                    $this->general_model->updateRowById('leads', 'leadId', $leadId, array('phone2' => ''));

                    $apiMsg = 'Cellcom API: <strong>' . $r->result . '</strong>';
                    $dataA = array(
                        'leadId'        => $leadId,
                        'userId'        => getUserId(),
                        'adminId'       => getAdminId(),
                        'text'          => $apiMsg,
                        'creationDate'  => date('Y-m-d H:i:s'),
                    );

                    $this->general_model->insertRow('lead_comments', $dataA);

                    $cmtText = 'Cellcom API: <strong>SIM CHANGE ' . $r->result . '</strong>';
                    $cmtData = array(
                        'leadId'       => $leadId,
                        'userId'       => getUserId(),
                        'adminId'      => getAdminId(),
                        'text'         => $cmtText,
                        'creationDate' => date('Y-m-d H:i:s')
                    );

                    $result = $this->general_model->insertRow('lead_comments', $cmtData);

                    $phone_line = array(
                        'phone'             => $phone,
                        'lineProvider'      => $company,
                        'lineGb'            => $gb,
                        'serviceStartDate'  => date('Y-m-d H:i:s'),
                        'serviceEndDate'    => date('Y-m-d H:i:s'),
                        'creationDate'      => date('Y-m-d H:i:s'),
                        'text2voice'        => 1,
                        'text2voiceEndDate' => date('Y-m-d H:i:s'),
                        'lastUpdate'        => date('Y-m-d H:i:s')
                    );

                    $result = $this->general_model->insertRow('phone_lines', $phone_line);

                    echo json_encode(array("result" => true));
                } else {
                    echo json_encode(array("result" => false));
                }
            }
            if ($company == 'partner') {
                $result = partnerManuiAction($phone, '2');

                if (!empty($result) && isset($result->ModelBO)) {
                    $arr = $result->ModelBO;

                    $this->general_model->updateRowById('leads', 'leadId', $leadId, array('phone2' => ''));

                    $apiMsg = ' - PARTNER API: <span>' . $arr->StatusReason . '</span>';
                    $dataA = array(
                        'leadId'        => $leadId,
                        'userId'        => getUserId(),
                        'adminId'       => getAdminId(),
                        'text'          => $apiMsg,
                        'creationDate'  => date('Y-m-d H:i:s'),
                    );

                    $this->general_model->insertRow('lead_comments', $dataA);

                    $phone_line = array(
                        'phone'             => $phone,
                        'lineProvider'      => $company,
                        //'lineGb'            => $gb,
                        'lineGb'            => 15,
                        'serviceStartDate'  => date('Y-m-d H:i:s'),
                        'serviceEndDate'    => date('Y-m-d H:i:s'),
                        'creationDate'      => date('Y-m-d H:i:s'),
                        'text2voice'        => 1,
                        'text2voiceEndDate' => date('Y-m-d H:i:s'),
                        'lastUpdate'        => date('Y-m-d H:i:s')
                    );

                    $result = $this->general_model->insertRow('phone_lines', $phone_line);

                    echo json_encode(array("result" => true));
                } else {
                    echo json_encode(array("result" => false));
                }
            }
            if ($company == 'hot') {
                $r = hotManuiActions($phone, 1); //1
                $this->general_model->updateRowById('leads', 'leadId', $leadId, array('phone2' => ''));
                $findPhone      = $this->general_model->getRowById('phone_lines', 'leadId', $leadId);

                $apiMsg = 'HOT API: <strong>' . $r->mirreturn_message . '</strong>';
                $dataA = array(
                    'leadId'        => $leadId,
                    'userId'        => getUserId(),
                    'adminId'       => getAdminId(),
                    'text'          => $apiMsg,
                    'creationDate'  => date('Y-m-d H:i:s'),
                );

                $this->general_model->insertRow('lead_comments', $dataA);

                $phone_line = array(
                    'phone'             => $phone,
                    'lineProvider'      => $company,
                    //'lineGb'            => $gb,
                    'lineGb'            => 15,
                    'sim'               => $findPhone->sim,
                    'serviceStartDate'  => date('Y-m-d H:i:s'),
                    'serviceEndDate'    => date('Y-m-d H:i:s'),
                    'creationDate'      => date('Y-m-d H:i:s'),
                    'text2voice'        => 1,
                    'text2voiceEndDate' => date('Y-m-d H:i:s'),
                    'lastUpdate'        => date('Y-m-d H:i:s')
                );

                $result = $this->general_model->insertRow('phone_lines', $phone_line);

                echo json_encode(array("result" => true));
            }
        } else {
            $this->general_model->updateRowById('leads', 'leadId', $leadId, array('phone2' => ''));
            $findPhone      = $this->general_model->getRowById('phone_lines', 'leadId', $leadId);

            $apiMsg = 'בוטל מספר זמני';
            $dataA = array(
                'leadId'        => $leadId,
                'userId'        => getUserId(),
                'adminId'       => getAdminId(),
                'text'          => $apiMsg,
                'creationDate'  => date('Y-m-d H:i:s'),
            );

            $this->general_model->insertRow('lead_comments', $dataA);

            $phone_line = array(
                'phone'             => $phone,
                'lineProvider'      => $company,
                'lineGb'            => $gb,
                'sim'               => $findPhone->sim,
                'serviceStartDate'  => date('Y-m-d H:i:s'),
                'serviceEndDate'    => date('Y-m-d H:i:s'),
                'creationDate'      => date('Y-m-d H:i:s'),
                'text2voice'        => 1,
                'text2voiceEndDate' => date('Y-m-d H:i:s'),
                'lastUpdate'        => date('Y-m-d H:i:s')
            );

            $result = $this->general_model->insertRow('phone_lines', $phone_line);

            echo json_encode(array("result" => true));
        }
    }

    public function RefundPrePaid()
    {

        $order_id   = $_POST['order_id'];
        $re         = $this->general_model->getRowById('prepaid_orders', 'order_id', $order_id);
        $re2        = $this->general_model->getRowById('customers', 'customerId', $re->customerId);

        $balance    = $re2->creditsPP;

        $order_data = array(
            'customerId'      => $re->customerId,
            'company'         => $re->company,
            'packageId'       => $re->packageId,
            'is_niyud'        => $re->is_niyud,
            'phone'           => $re->phone,
            'sim'             => $re->sim,
            'price_before'    => $re->price_before * -1,
            'price_after'     => $re->price_after * -1,
            'discount_amount' => $re->discount_amount,
            'credit_before'   => $balance,
            'credit_after'    => $balance + $re->price_after,
            'parentDiscount'  => $re->parentDiscount * -1,
            'api_result'      => $re->api_result,
            'status'          => 3,
            'date_created'    => $re->date_created,
            'lastupdate'      => $re->lastupdate
        );

        $result = $this->general_model->insertRow('prepaid_orders', $order_data);

        if (!empty($result)) {

            $this->general_model->updateRowById('prepaid_orders', 'order_id', $order_id, array('status' => 2));

            $this->general_model->updateRowById('customers', 'customerId', $re->customerId, array('creditsPP' => $balance + $re->price_after));

            if ($re2->parentId > 1) {
                $parentDetails  = $this->general_model->getRowById('customers', 'customerId', $re2->parentId);
                if ($parentDetails->can_retail_pp == 1) {
                    $resultDiscount = $this->general_model->updateRowById('customers', 'customerId', $parentDetails->customerId, array('retail_credit' => $parentDetails->retail_credit - $re->parentDiscount));
                }
            }

            echo json_encode(array("result" => true));
        } else {
            echo json_encode(array("result" => false));
        }
    }

    public function RefundPrePaidAPI()
    {
        $order_id   = $_POST['order_id'];
        $re         = $this->general_model->getRowById('prepaid_orders', 'order_id', $order_id);
        $re2        = $this->general_model->getRowById('customers', 'customerId', $re->customerId);

        $balance    = $re2->creditsPP;
        $newApi     = '';

        if ($re->company == 'ramilevy') {
            $refundAPI = ramilevyCancelTopUp($re->phone);
            if (isset($refundAPI['status']) && !empty($refundAPI['status']) && $refundAPI['status'] == 1) {
                $result = true;
                $newApi = $refundAPI['result'];
            } else {
                $result = false;
                $newApi = 'API FAILED';
            }
        }

        if ($re->company == 'ramilevy-new') {
            $refundAPI = RamilevyMobileQCancel($jobId = $re->authNumber);
            if (isset($refundAPI->status) && !empty($refundAPI->status) && $refundAPI->status == true) {
                $result = true;
                $newApi = $refundAPI->status;
            } else {
                $result = false;
                $newApi = 'API FAILED';
            }
            if (isset($refundAPI->message) && !empty($refundAPI->message)) {
                $api_result = $refundAPI->message;
            } else {
                $api_result = 'Unknown Error!';
            }
        }

        if ($re->company == '019') {
            $reff       = $re->api_result;
            $refference = str_replace("1 - ", "", $reff);
            $refundAPI = PP019CancelCharge($re->phone, $refference);
            if (isset($refundAPI->status) && !empty($refundAPI->status) && $refundAPI->status == 1) {
                $result = true;
                $newApi = $refundAPI->refference;
            } else {
                $result = false;
                $newApi = 'API FAILED';
            }
            if (isset($refundAPI->message) && !empty($refundAPI->message)) {
                $api_result = $refundAPI->message;
            } else {
                $api_result = 'Unknown Error!';
            }
        }

        if ($re->company == 'hot') {
            $oldResult = $re->api_result;
            $UniqueTransId = str_replace('Ok - ', "", $oldResult);
            $r = CancelHotMobileTopUp($UniqueTransId);
            if (isset($r['Result']) && $r['Result'] == 0) {
                $result = true;
                $newApi = $api_result = $r['Result'] . ' - ' . $r['Message'] . ' - ' . $r['TransId'] . ' - ' . $r['Amount'];
            } else {
                $result = false;
                $newApi = $api_result = $r['Result'] . ' - ' . $r['Message'] . ' - ' . $r['TransId'] . ' - ' . $r['Amount'];
            }
        }

        $this->general_model->updateRowById('prepaid_packages_cancel', 'order_id', $order_id, array('api_result' => $api_result));
        if (!empty($newApi) && !strpos($newApi, 'FAILED') && $result == true) {
            $this->general_model->updateRowById('prepaid_orders', 'order_id', $order_id, array('status' => 2, 'api_result' => $re->api_result . ' | ' . $newApi));
            echo json_encode(array("result" => true));
        } else {
            echo json_encode(array("result" => false));
        }
    }

    public function RefundPrePaidNew()
    {

        $order_id   = $_POST['order_id'];
        $re         = $this->general_model->getRowById('prepaid_orders', 'order_id', $order_id);
        $re2        = $this->general_model->getRowById('customers', 'customerId', $re->customerId);

        $balance    = $re2->creditsPP;


        $order_data = array(
            'customerId'      => $re->customerId,
            'company'         => $re->company,
            'packageId'       => $re->packageId,
            'is_niyud'        => $re->is_niyud,
            'phone'           => $re->phone,
            'sim'             => $re->sim,
            'price_before'    => $re->price_before * -1,
            'price_after'     => $re->price_after * -1,
            'discount_amount' => $re->discount_amount,
            'credit_before'   => $balance,
            'credit_after'    => $balance + $re->price_after,
            'parentDiscount'  => $re->parentDiscount * -1,
            'api_result'      => $re->api_result,
            'status'          => 3,
            'date_created'    => date('Y-m-d H:i:s'),
            'lastupdate'      => date('Y-m-d H:i:s'),
        );

        $result = $this->general_model->insertRow('prepaid_orders', $order_data);

        if (!empty($result)) {

            $this->general_model->updateRowById('prepaid_orders', 'order_id', $order_id, array('status' => 2));

            $this->general_model->updateRowById('customers', 'customerId', $re->customerId, array('creditsPP' => $balance + $re->price_after));

            if ($re2->parentId > 1) {
                $parentDetails  = $this->general_model->getRowById('customers', 'customerId', $re2->parentId);
                if ($parentDetails->can_retail_pp == 1) {
                    $resultDiscount = $this->general_model->updateRowById('customers', 'customerId', $parentDetails->customerId, array('retail_credit' => $parentDetails->retail_credit - $re->parentDiscount));
                }
            }

            $this->general_model->updateRowById('prepaid_packages_cancel', 'order_id', $order_id, array('cStatus' => 1));

            echo json_encode(array("result" => true));
        } else {
            echo json_encode(array("result" => false));
        }
    }

    public function DoNotRefundPrePaidCharge()
    {
        $order_id   = $_POST['order_id'];
        $re         = $this->general_model->getRowById('prepaid_orders', 'order_id', $order_id);
        if (!empty($re)) {
            $this->general_model->updateRowById('prepaid_packages_cancel', 'order_id', $order_id, array('cStatus' => 2));
            echo json_encode(array("result" => true));
        } else {
            echo json_encode(array("result" => false));
        }
    }

    public function createApiHash()
    {

        $customerId     = $_POST['id'];

        if (!empty($customerId)) {

            $customer       = $this->general_model->getRowById('customers', 'customerId', $customerId);

            if (!empty($customer)) {

                $userId         = $customer->adminId;

                $name           = $customer->customerName;
                $phoneNumber    = $customer->phoneNumber;
                $email          = $customer->email;
                $today          = date("Y/m/d");

                $ApiHash    = md5($name . $phoneNumber . $email . $today);

                $r          = $this->general_model->updateRowById('customers', 'customerId', $customerId, array('ApiHash' => $ApiHash));

                if (!empty($r)) {

                    $rU         = $this->general_model->updateRowById('users', 'userId', $userId, array('ApiHash' => $ApiHash));
                    echo json_encode(array("result" => true));
                } else {
                    echo json_encode(array("result" => false));
                }
            } else {
                echo json_encode(array("result" => false));
            }
        } else {
            echo json_encode(array("result" => false));
        }
    }

    public function reCalcPrePaid()
    {

        $order_id   = $_POST['order_id'];
        $re         = $this->general_model->getRowById('prepaid_orders', 'order_id', $order_id);
        $re2        = $this->general_model->getRowById('customers', 'customerId', $re->customerId);

        $balance    = $re2->creditsPP;
        $newBalance = $balance - $re->price_after;

        $result = $this->general_model->updateRowById('prepaid_orders', 'order_id', $order_id, array('status' => 1, 'credit_before' => $balance, 'credit_after' => $newBalance, 'status' => 1, 'lastupdate' => date('Y-m-d H:i:s')));

        if (!empty($result)) {

            $this->general_model->updateRowById('customers', 'customerId', $re->customerId, array('creditsPP' => $newBalance));

            echo json_encode(array("result" => true));
        } else {
            echo json_encode(array("result" => false));
        }
    }

    function insertCustomerPrePaidPayment($customerId)
    {

        $data = $_POST;

        $total_date     = $data['total_date'];
        $dateStr        = str_replace("/", "-", $total_date);
        $first_date     = strtotime($dateStr);
        $cpDate         = date('Y-m-d H:i:s', $first_date);

        $customer = $this->general_model->getRowById('customers', 'customerId', intval($customerId));

        $paymentData = array(
            'comment'       => htmlspecialchars($data['comment']),
            'total'         => floatval($data['total']),
            'title'          => 'general_prepaid_payment',
            'cpDate'        => $cpDate,
            //'startDate'     => date('Y-m-d H:i:s', strtotime(str_replace('/', '-', $data['startDate']))),
            //'endDate'       => date('Y-m-d H:i:s', strtotime(str_replace('/', '-', $data['endDate']))),
            'userId'        => getUserId(),
            'adminId'       => $customer->parentId,
            'customerId'    => intval($customerId),
            'isPaid'        => 1,
            'qty' => 1,
            'creationDate'  => date('Y-m-d H:i:s'),
            'lastUpdate'    => date('Y-m-d H:i:s')
        );

        $result = $this->general_model->insertRow('customers_payments', $paymentData);


        $newCredit = $customer->creditsPP - floatval($data['total']);
        $r = $this->general_model->updateRowById('customers', 'customerId', intval($customerId), array('creditsPP' => $newCredit, 'lastUpdate' => date('Y-m-d H:i:s')));

        //debug($_POST);
        redirect('admin/customers/customerPaymentsSumPP/' . intval($customerId), 'refresh');

        if ($result) {
            //Update invest lastupdate
            echo json_encode(array('result' => true, 'out' => $out));
        } else {
            echo json_encode(array('result' => false));
        }
    }

    function insertCustomerPrePaidPaymentComm($customerId)
    {

        $data = $_POST;
        $total_date     = $data['total_date'];
        $dateStr        = str_replace("/", "-", $total_date);
        $first_date     = strtotime($dateStr);
        $cpDate         = date('Y-m-d H:i:s', $first_date);
        $customer       = $this->general_model->getRowById('customers', 'customerId', intval($customerId));
        $comm_text      = 'עמלת פריפייד: ';
        $comment        = $comm_text . $data['company'] . $data['month'] . '/' . $data['year'] . ' ' . $data['comment'];
        $paymentData = array(
            'comment'           => $comment,
            'total'             => floatval($data['total']) * -1,
            'title'             => 'general_prepaid_payment',
            'cpDate'            => $cpDate,
            'userId'            => getUserId(),
            'adminId'           => $customer->parentId,
            'customerId'        => intval($customerId),
            'isPaid'            => 1,
            'qty'               => 1,
            'is_comm'           => 1,
            'creationDate'      => date('Y-m-d H:i:s'),
            'lastUpdate'        => date('Y-m-d H:i:s')
        );

        $result         = $this->general_model->insertRow('customers_payments', $paymentData);
        $newCredit      = $customer->creditsPP + floatval($data['total']);
        $updateCredit   = $this->general_model->updateRowById('customers', 'customerId', intval($customerId), array('creditsPP' => $newCredit, 'lastUpdate' => date('Y-m-d H:i:s')));

        redirect('admin/customers/customerPaymentsSumPP/' . intval($customerId), 'refresh');

        if ($result) {
            echo json_encode(array('result' => true, 'out' => $out));
        } else {
            echo json_encode(array('result' => false));
        }
    }

    function addBankCredit()
    {

        $id   = $_POST['id'];

        $request = $this->general_model->getRowById('bank_requests', 'id', intval($id));
        $customer = $this->general_model->getRowById('customers', 'customerId', intval($request->customerId));

        if ($request->main_type == 1) {
            $comment = 'הוראת קבע';
        }
        if ($request->main_type == 2) {
            $comment = 'העברה';
        }
        if ($request->main_type == 3) {
            $comment = 'הפקדה';
        }
        if ($request->type == 1) {
            $title = 'credit_addon_prepaid';
        } else {
            $title = 'credit_addon';
        }
        if ($customer->parentId == 1) {
            $paymentData = array(
                'comment'       => $comment,
                'total'         => ($request->total) * -1,
                'title'          => $title,
                'cpDate'        => date('Y-m-d H:i:s'),
                'userId'        => getUserId(),
                'adminId'       => $customer->parentId,
                'customerId'    => $request->customerId,
                'isPaid'        => 1,
                'qty'           => 1,
                'creationDate'  => date('Y-m-d H:i:s'),
                'lastUpdate'    => date('Y-m-d H:i:s')
            );

            $result = $this->general_model->insertRow('customers_payments', $paymentData);
        }

        if ($customer->parentId != 1) {

            $customerP = $this->general_model->getRowById('customers', 'customerId', $customer->parentId);

            $paymentData = array(
                'userId'          => $customerP->adminId,
                'customerId'      => $customerP->customerId,
                'adminId'         => $customerP->parentId,
                'title'           => $title,
                'qty'             => 0,
                'total'           => ($request->total) * -1,
                'comment'         => $comment,
                'isPaid'          => 1,
                'parent_sub_user' => $customer->customerId,
                'cpDate'          => date('Y-m-d H:i:s'),
                'creationDate'    => date('Y-m-d H:i:s'),
                'lastUpdate'      => date('Y-m-d H:i:s')
            );

            $result = $this->general_model->insertRow('customers_payments', $paymentData);

            if ($request->type == 1) {
                $creditP = $customerP->creditsPP + $request->total;
                $r = $this->general_model->updateRowById('customers', 'customerId', $customerP->customerId, array('creditsPP' => $creditP, 'lastUpdate' => date('Y-m-d H:i:s')));
            } else {
                $creditP = $customerP->credits + $request->total;
                $r = $this->general_model->updateRowById('customers', 'customerId', $customerP->customerId, array('credits' => $creditP, 'lastUpdate' => date('Y-m-d H:i:s')));
            }
        }

        if ($result) {

            if ($request->type == 0) {
                $newCredit = $customer->credits + $request->total;
                $r = $this->general_model->updateRowById('customers', 'customerId', $customer->customerId, array('credits' => $newCredit, 'lastUpdate' => date('Y-m-d H:i:s')));
            } else {
                if ($customer->parentId == 1) {
                    $newCredit = $customer->creditsPP + $request->total;
                    $r = $this->general_model->updateRowById('customers', 'customerId', $customer->customerId, array('creditsPP' => $newCredit, 'lastUpdate' => date('Y-m-d H:i:s')));
                }
            }

            $this->general_model->updateRowById('bank_requests', 'id', $id, array('status' => 1, 'lastUpdate' => date('Y-m-d H:i:s')));

            echo json_encode(array('result' => true));
        } else {
            echo json_encode(array('result' => false));
        }
    }

    function finalApproveBankRequest()
    {

        $id         = $_POST['id'];
        $request    = $this->general_model->getRowById('bank_requests', 'id', intval($id));
        $customer   = $this->general_model->getRowById('customers', 'customerId', intval($request->customerId));

        $this->general_model->updateRowById('bank_requests', 'id', $id, array('final_approve' => 1, 'lastUpdate' => date('Y-m-d H:i:s')));

        if ($request->main_type == 1) {
            $payment_type = 1;
        }
        if ($request->main_type == 2) {
            $payment_type = 2;
        }
        if ($request->main_type == 3) {
            $payment_type = 3;
        }

        if ($request->bank == 12) {
            if ($request->bank_account == '649278') {
                $payment_box = 19;
            } else {
                $payment_box = 1;
            }
        } else if ($request->bank == 400) {
            $payment_box = 2;
        } else if ($request->bank == 500) {
            $payment_box = 3;
        } else {
            $payment_box = 1;
        }

        if ($request->main_type != 1 && $request->bank != 12) {
            //debug($payment_box);
            $invoicePaymentData = array(
                'invoice_id'        => 0,
                'customer_id'       => $request->customerId,
                'payment_type'      => $payment_type,
                'payment_box'       => $payment_box,
                'payment_date'      => date('Y-m-d', strtotime($request->date_created)),
                'bank_visa'         => $request->bank,
                'branch_digits'     => $request->bank_branch,
                'account_card'      => $request->bank_account,
                'reference_id'      => $request->reference_id,
                'total'             => $request->total,
                'is_converted'      => 1,
                'dateCreation'      => date('Y-m-d H:i:s'),
                'lastUpdate'        => date('Y-m-d H:i:s')
            );

            $payment_id = $this->general_model->insertRow('customer_invoices_payments', $invoicePaymentData);
        }
        if ($request->type == 1) {
            if ($request->bank_account == '649278') {
                $box = 19;
            } else {
                $box = 1;
            }
            //$box = 19;
            $main_type = 2;
        } else {
            if ($request->bank_account == '649278') {
                $box = 19;
            } else {
                $box = 1;
            }
            //$box = 1;
            $main_type = 1;
        }
        if ($request->main_type == 1 || $request->main_type == 2 && $request->bank == 12 || $request->main_type == 3 && $request->bank == 12) {
            if ($request->type == 1) {
                $box = 19;
                $main_type = 1;
            } else {
                $box = 1;
                $main_type = 2;
            }
            if ($request->main_type == 1) {
                $total          = $request->total;
                $customerId     = $request->customerId;
                $box            = $box;
                $digits         = 0;
                $date           = 0;
                $reference_id   = $request->reference_id;
                $payment_type   = 2;
                $bank_visa      = $request->bank;
                $branch_digits  = $request->bank_branch;
                $account_card   = $request->bank_account;
            } else {
                $total          = $request->total;
                $customerId     = $request->customerId;
                $box            = $box;
                $digits         = 0;
                $date           = 0;
                $reference_id   = $request->reference_id;
                $payment_type   = 3;
                $bank_visa      = 0;
                $branch_digits  = 0;
                $account_card   = 0;
            }

            $invoice        = $this->createInvoice(2, $total, $customerId, $box, $digits, $date, $reference_id, $main_type, $payment_type, $bank_visa, $branch_digits, $account_card);
        }

        echo json_encode(array("result" => true));
    }

    function createInvoice($type, $total, $customerId, $box, $digits, $date, $reference_id, $main_type, $payment_type, $bank_visa, $branch_digits, $account_card)
    {

        if ($type == 1) {
            $total_vat           = $total * 1.17;
            $vat                 = $total * 0.17;
            $total_before_vat    = $total;
        } else {
            $total_vat           = $total;
            $vat                 = round($total - ($total / 1.17), 2);
            $total_before_vat    = round($total / 1.17, 2);
        }

        $MainInvoiceData = array(
            'invoice_type'    => 1,
            'main_type'       => $main_type,
            'total'           => $total_vat,
            'invoice_date'    => date('Y-m-d H:i:s'),
            'customerId'      => $customerId,
            'dateCreation'    => date('Y-m-d H:i:s'),
            'lastUpdate'      => date('Y-m-d H:i:s')
        );

        $invoice_id = $this->general_model->insertRow('customer_invoices', $MainInvoiceData);

        if (!empty($invoice_id)) {

            $invoiceItemsData = array(
                'invoice_id'      => $invoice_id,
                'item_title'      => 'עבור שירותי תקשורת',
                'item_price'      => $total_before_vat,
                'customer_id'     => $customerId,
                'dateCreation'    => date('Y-m-d H:i:s'),
                'lastUpdate'      => date('Y-m-d H:i:s')
            );

            $item_id = $this->general_model->insertRow('customer_invoice_items', $invoiceItemsData);

            $invoicePaymentData = array(
                'invoice_id'        => $invoice_id,
                'main_type'         => $main_type,
                'customer_id'       => $customerId,
                'payment_type'      => $payment_type,
                'payment_box'       => $box,
                'payment_date'      => date('Y-m-d H:i:s'),
                'bank_visa'         => $bank_visa,
                'branch_digits'     => $branch_digits,
                'account_card'      => $account_card,
                'reference_id'      => $reference_id,
                'total'             => $total_vat,
                'dateCreation'      => date('Y-m-d H:i:s'),
                'lastUpdate'        => date('Y-m-d H:i:s')
            );

            $payment_id = $this->general_model->insertRow('customer_invoices_payments', $invoicePaymentData);
        }
    }

    public function newPasswordforUser()
    {

        $adminId    = $_POST['adminId'];
        $password   = $_POST['password'];
        $password2  = $_POST['password2'];

        if ($password == $password2) {
            $re         = $this->general_model->getRowById('users', 'userId', $adminId);
            $salt       = $re->salt;
            if (!empty($salt)) {
                $saltedPW   =  $password . $salt;
                $hashedPW   = hash('sha256', $saltedPW);

                $result = $this->general_model->updateRowById('users', 'userId', $adminId, array('password' => $hashedPW, 'lastUpdate' => date('Y-m-d H:i:s')));

                if (!empty($result)) {
                    echo json_encode(array("result" => true));
                } else {
                    echo json_encode(array("result" => false));
                }
            } else {
                echo json_encode(array("result" => false));
            }
        } else {
            echo json_encode(array("result" => false));
        }
    }

    public function uploadPrePaidOrders()
    {
        $data = $_POST;

        if ($_FILES['fileP']['tmp_name'] == '') {
            $this->session->set_flashdata('flashMsgType', 'Error');
            $this->session->set_flashdata('flashMsg', 'לא נבחר קובץ!');
            redirect('admin/PrepaidPackages/', 'refresh');
        } else {
            //uploadFile('data', 'fileP', 'xlsx');
            $result = $this->importPrePaidOrders($_FILES['fileP']['tmp_name'], $data);
        }

        if (!empty($result)) {
            redirect('admin/PrepaidPackages');
        }
    }

    public function importPrePaidOrders($file, $data)
    {
        ini_set('memory_limit', '4048M');
        $this->load->library('PHPExcel');
        $this->load->library('PHPExcel/IOFactory');

        $result = '<strong>תוצאות העלאה: </strong><br/>';

        $inputFileName = $file;
        $objReader = IOFactory::createReader('Excel2007');
        //$objReader->setReadDataOnly(true);
        $objPHPExcel = $objReader->load($inputFileName);
        $objWorksheet = $objPHPExcel->getActiveSheet();

        $highestRow = $objWorksheet->getHighestRow();
        $highestColumn = $objWorksheet->getHighestColumn();
        $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);

        $rows = array();


        //debug($highestColumnIndex);
        if ($highestColumnIndex < 3) {
            return  array('result' => 'הקובץ לא תקין!!', 'cnt' => 0);
        }
        if (!isset($data['customerId'])) $data['customerId'] = 0;
        $productsIds = array();
        $count = 0;

        for ($row = 1; $row <= $highestRow; ++$row) {

            for ($col = 0; $col <= $highestColumnIndex; ++$col) {
                $rows[$col] = $objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
            }

            if ($rows[0] != '' && $rows[0] != 'טלפון') {

                if (substr($rows[0], 0, 1) != '0') $rows[0] = '0' . $rows[0];
                $rows[0] = str_replace('-', '', $rows[0]);

                $customerDetails    = $this->general_model->getRowById('customers', 'peTerminal', $rows[1]);
                $prepaid_packages   = $this->general_model->getRowById('prepaid_packages', 'special_code', $rows[2]);

                if (!empty($prepaid_packages)) {
                    $package_discount   = $this->general_model->getTableWhereArray('prepaid_packages_discounts', array('userId' => $customerDetails->customerId, "pid" => $prepaid_packages->pid));

                    if (!empty($package_discount)) {
                        $discount       = $package_discount[0]->discount;
                    } else {
                        $discount       = $prepaid_packages->discount;
                    }

                    $credit_before      = $customerDetails->creditsPP;
                    $price_before       = $prepaid_packages->price;
                    $company            = $prepaid_packages->company;
                    $packageId          = $prepaid_packages->pid;
                } else {
                    $discount           = 0;
                    $price_before       = $rows[6];
                    $company            = "new_others";
                    $packageId          = $rows[2];
                }
                if ($discount == 0) {
                    $discount_amount = 0;
                } else {
                    $discount_amount    = ($discount / 100) * $price_before;
                }

                $price_after        = $price_before - $discount_amount;

                $status = $rows[3];

                if ($status == 0) {
                    $credit_after       = $credit_before;
                } else {
                    $credit_after       = $credit_before - $price_after;
                }

                $date = $rows[5];

                if ($rows[6] < 0) {
                    $price_before   = $price_before * -1;
                    $price_after    = $price_after * -1;
                    $credit_after   = $credit_before + ($price_after * -1);
                } else {
                    $price_before = $price_before;
                    $price_after = $price_after;
                }

                $date1 = strtotime($date);
                $date2 = date('Y-m-d H:i:s', $date1);
                $orderData = array(
                    'customerId'      => $customerDetails->customerId,
                    'company'         => $company,
                    'packageId'       => $packageId,
                    'is_niyud'        => 0,
                    'phone'           => $rows[0],
                    'sim'             => '',
                    'price_before'    => $price_before,
                    'price_after'     => $price_after,
                    'discount_amount' => $discount_amount,
                    'credit_before'   => $credit_before,
                    'credit_after'    => $credit_after,
                    'api_result'      => $rows[4],
                    'status'          => $rows[3],
                    'date_created'    => $date2,
                    'lastupdate'      => date('Y-m-d H:i:s')
                );

                $re     = $this->general_model->updateRowById('customers', 'customerId', $customerDetails->customerId, array('creditsPP' => $credit_after));
                $result = $this->general_model->insertRow('prepaid_orders', $orderData);

                $count++;
            }
        }

        return array('result' => $result, 'cnt' => $count);
    }

    public function addPrepaidOrderManual()
    {

        $peTerminal         = $_POST['peTerminal'];
        $price              = $_POST['price'];
        $priceAfter         = $_POST['priceAfter'];
        $phone              = $_POST['phone'];
        $discountManual     = $_POST['discount'];
        $api_result         = $_POST['api_result'];
        $status             = $_POST['status'];
        $packageId          = $_POST['packageId'];
        $companyManual      = $_POST['company'];
        $date               = $_POST['date'];
        $date1              = strtotime($date);
        $date2              = date('Y-m-d H:i:s', $date1);
        $customerDetails    = $this->general_model->getRowById('customers', 'peTerminal', $peTerminal);
        $prepaid_packages   = $this->general_model->getRowById('prepaid_packages', 'special_code', $packageId);
        $credit_before      = $customerDetails->creditsPP;

        if (!empty($prepaid_packages)) {
            $package_discount   = $this->general_model->getTableWhereArray('prepaid_packages_discounts', array('userId' => $customerDetails->customerId, "pid" => $prepaid_packages->pid));
            $company            = $prepaid_packages->company;
            $package            = $prepaid_packages->pid;
            if (!empty($package_discount)) {
                $discount       = $package_discount[0]->discount;
            } else {
                $discount       = $prepaid_packages->discount;
            }

            $credit_before      = $customerDetails->creditsPP;
            $price_before       = $prepaid_packages->price;

            if ($discount == 0) {
                $discount_amount = 0;
            } else {
                $discount_amount    = ($discount / 100) * $price_before;
            }

            $price_after        = $price_before - $discount_amount;

            if ($status == 0) {
                $credit_after       = $credit_before;
            } else {
                $credit_after       = $credit_before - $price_after;
            }
        } else {

            $discount_amount    = $discountManual;
            $price_before       = $price;
            $price_after        = $price_before - $discount_amount;
            $credit_after       = $credit_before - $price_after;
            $company            = $companyManual;
            $package            = $packageId;
        }


        $orderData = array(
            'customerId'      => $customerDetails->customerId,
            'company'         => $company,
            'packageId'       => $package,
            'is_niyud'        => 0,
            'phone'           => $phone,
            'sim'             => '',
            'price_before'    => $price_before,
            'price_after'     => $price_after,
            'discount_amount' => $discount_amount,
            'credit_before'   => $credit_before,
            'credit_after'    => $credit_after,
            'api_result'      => $api_result,
            'status'          => $status,
            'date_created'    => date('Y-m-d H:i:s'),
            'lastupdate'      => date('Y-m-d H:i:s')
        );


        $re     = $this->general_model->updateRowById('customers', 'customerId', $customerDetails->customerId, array('creditsPP' => $credit_after));
        $result = $this->general_model->insertRow('prepaid_orders', $orderData);

        if (!empty($result)) {
            redirect('admin/PrepaidPackages');
        }
    }

    public function getRamiLevyStatus()
    {

        $phone = $_POST['phone'];

        $r              = RamiLevyStatus($phone);

        $status         = $r['status'];
        $Expiration     = isset($r['result']['Data']['Balance'][1]['Expiration']) ? $r['result']['Data']['Balance'][1]['Expiration'] : '';
        $LeftDays       = isset($r['result']['Data']['Balance'][1]['LeftDays']) ? $r['result']['Data']['Balance'][1]['LeftDays'] : '0';
        $Balance        = isset($r['result']['Data']['Balance'][1]['Balance']) ? $r['result']['Data']['Balance'][1]['Balance'] : '';
        $PackNameHe     = isset($r['result']['Data']['Balance'][1]['PackNameHe']) ? $r['result']['Data']['Balance'][1]['PackNameHe'] : '0';
        $smsBalanace    = isset($r['result']['Data']['Balance'][2]['Balance']) ? $r['result']['Data']['Balance'][2]['Balance'] : '0';
        $gbBalance      = isset($r['result']['Data']['Balance'][3]['Balance']) ? $r['result']['Data']['Balance'][3]['Balance'] : '0';

        $programm       = isset($r['result']['Data']['Balance'][1]['program']['minutes']) ? $r['result']['Data']['Balance'][1]['program']['minutes'] : '0';
        $programs       = isset($r['result']['Data']['Balance'][1]['program']['sms']) ? $r['result']['Data']['Balance'][1]['program']['sms'] : '0';
        $programg       = isset($r['result']['Data']['Balance'][1]['program']['gbs']) ? $r['result']['Data']['Balance'][1]['program']['gbs'] : '0';

        $data = array(
            'status'        => $status,
            'PackNameHe'    => $PackNameHe,
            'Expiration'    => date("d/m/Y H:i:s", strtotime($Expiration)),
            'LeftDays'      => $LeftDays,
            'Balance'       => $Balance,
            'programm'      => $programm,
            'smsBalanace'   => $smsBalanace,
            'programs'      => $programs,
            'gbBalance'     => $gbBalance,
            'programg'      => $programg,
        );

        echo json_encode($data);
    }

    public function updateCompanyDiscount()
    {

        $company    = $_POST['company'];
        $discount   = $_POST['discount'];
        $customerId = $_POST['customerId'];

        if (!empty($company) && !empty($customerId)) {

            $package = $this->general_model->getTableWhereArray('companies_to_parent_user', array('user_id' => $customerId, "company_id" => $company));

            if (!empty($package)) {
                $re  = $this->general_model->updateRowById('companies_to_parent_user', 'id', $package[0]->id, array('discount' => $discount));
            } else {
                $discountData = array(
                    'user_id'       => $customerId,
                    'company_id'    => $company,
                    'discount'      => $discount,
                    'dateCreation'  => date('Y-m-d H:i:s')
                );

                $re = $this->general_model->insertRow('companies_to_parent_user', $discountData);
            }

            if (!empty($re)) {
                echo json_encode(array("result" => true));
            } else {
                echo json_encode(array("result" => false));
            }
        } else {
            echo json_encode(array("result" => false));
        }
    }

    public function updateDiscountsAllPrePaid()
    {

        $data = (object)$_POST;
        $prepaid_packages = $this->db->query("SELECT `pid` FROM `prepaid_packages` WHERE `company` = '$data->company_all' ")->result();
        $packages = array();
        foreach ($prepaid_packages as $pp) {
            $packages[] = $pp->pid;
        }
        foreach ($packages as $pacakge) {
            $current_discount = $this->db->query("SELECT * FROM `prepaid_packages_discounts` WHERE `pid` = '$pacakge' AND `userId` = '$data->customerId' ")->row();
            if (!empty($current_discount)) {
                $add_discount = $this->general_model->updateRowById('prepaid_packages_discounts', 'dpid', $current_discount->dpid, array('discount' => $data->discount_amount_all, 'active' => 1, 'lastupdate' => date('Y-m-d H:i:s')));
            } else {
                $data = array(
                    'pid'           => $pacakge,
                    'userId'        => $data->customerId,
                    'discount'      => $data->discount_amount_all,
                    'active'        => 1,
                    'lastupdate'    => date('Y-m-d H:i:s')
                );
                $add_discount   = $this->general_model->insertRow('prepaid_packages_discounts', $data);
            }
        }

        if (!empty($add_discount)) {
            echo json_encode(array("result" => true));
        } else {
            echo json_encode(array("result" => false));
        }
    }

    public function updateDiscountsAllPostPaid()
    {

        $discount_type      = $_POST['discount_type_all'];
        $discount_amount    = $_POST['discount_amount_all'];
        $customerId         = $_POST['customerId'];
        $company            = $_POST['company_all'];

        $postpaid_packages = $this->db->query("SELECT * FROM `postpaid_packages` WHERE `company` = '$company' ")->result();

        foreach ($postpaid_packages as $package) {
            $current_package = $this->general_model->getTableWhereArray('postpaid_packages_discounts', array('userId' => $customerId, "packageId" => $package->id));
            if (empty($current_package)) {
                $data = array(
                    'packageId'         => $package->id,
                    'userId'            => $customerId,
                    'discount_type'     => $discount_type,
                    'discount_amount'   => $discount_amount,
                    'isActive'          => 1,
                    'dateCreation'      => date('Y-m-d H:i:s'),
                    'lastUpdate'        => date('Y-m-d H:i:s')
                );
                $add_discount   = $this->general_model->insertRow('postpaid_packages_discounts', $data);
            }
        }

        if (!empty($add_discount)) {
            echo json_encode(array("result" => true));
        } else {
            echo json_encode(array("result" => false));
        }
    }

    public function addPostPaidDiscountforAllCustomers()
    {

        $discount_type      = $_POST['discount_type_all'];
        $discount_amount    = $_POST['discount_amount_all'];
        $package_id         = $_POST['package_id'];

        $customers = $this->db->query("SELECT * FROM `customers` WHERE `isPostPaidActive` = 1")->result();

        foreach ($customers as $customer) {
            $current_packages = $this->general_model->getTableWhereArray('postpaid_packages_discounts', array('packageId' => $package_id, 'userId' => $customer->customerId));

            if (!empty($current_packages)) {
                foreach ($current_packages as $cPackage) {
                    $add_discount  = $this->general_model->updateRowById('postpaid_packages_discounts', 'id', $cPackage->id, array('discount_amount' => $discount_amount, 'discount_type' => $discount_type, 'isActive' => 1));
                }
            } else {
                $data = array(
                    'packageId'         => $package_id,
                    'userId'            => $customer->customerId,
                    'discount_type'     => $discount_type,
                    'discount_amount'   => $discount_amount,
                    'isActive'          => 1,
                    'dateCreation'      => date('Y-m-d H:i:s'),
                    'lastUpdate'        => date('Y-m-d H:i:s')
                );
                $add_discount   = $this->general_model->insertRow('postpaid_packages_discounts', $data);
            }
        }

        if (!empty($add_discount)) {
            echo json_encode(array("result" => true));
        } else {
            echo json_encode(array("result" => false));
        }
    }

    public function addchangePostPackageDiscount()
    {

        $data = $_POST;

        $packageId          = $data['data']['packageId'];
        $discount_type      = $data['data']['discount_type'];
        $discount_amount    = $data['data']['discount_amount'];
        $isActive           = $data['data']['isActive'];
        $customerId         = $data['data']['customerId'];

        $data = array(
            'packageId'         => $packageId,
            'userId'            => $customerId,
            'discount_type'     => $discount_type,
            'discount_amount'   => $discount_amount,
            'isActive'          => $isActive,
            'dateCreation'      => date('Y-m-d H:i:s'),
            'lastUpdate'        => date('Y-m-d H:i:s')
        );

        $discount = $this->general_model->getTableWhereArray('postpaid_packages_discounts', array('userId' => $customerId, "packageId" => $packageId));

        if (!empty($discount)) {
            $edit_discount  = $this->general_model->updateRowById('postpaid_packages_discounts', 'id', $discount[0]->id, $data);

            if (!empty($edit_discount)) {
                echo json_encode(array("result" => true));
            } else {
                echo json_encode(array("result" => false));
            }
        } else {
            $add_discount   = $this->general_model->insertRow('postpaid_packages_discounts', $data);
            if (!empty($add_discount)) {
                echo json_encode(array("result" => true));
            } else {
                echo json_encode(array("result" => false));
            }
        }
    }

    public function getMsgData()
    {

        $cmdId    = $_POST['cmtId'];

        $msg    = $this->general_model->getRowById('customer_messages', 'cmId', $cmdId);

        echo json_encode(array('contentHebrewEdit' => $msg->content, 'contentArabicEdit' => $msg->contentArabic, 'type' => $msg->mType));
    }

    public function updateMsgData()
    {

        $cmdId          = $_POST['cmtId'];
        $content        = $_POST['content'];
        $contentArabic  = $_POST['contentArabic'];
        $mTypeEdit      = $_POST['mTypeEdit'];

        $re     = $this->general_model->updateRowById('customer_messages', 'cmId', $cmdId, array('content' => $content, 'contentArabic' => $contentArabic, 'mType' => $mTypeEdit));
        echo json_encode(array("result" => true));
    }

    public function addCommentToLead($leadId, $cmtText, $text_id)
    {

        $cmtData = array(
            'leadId'       => $leadId,
            'userId'       => getUserId(),
            'adminId'      => getAdminId(),
            'text'         => $cmtText,
            'text_id'      => $text_id,
            'creationDate' => date('Y-m-d H:i:s')
        );

        $result = $this->general_model->insertRow('lead_comments', $cmtData);

        return true;
    }

    public function changeNumberStatustoNiyud()
    {

        $leadId         = $_POST['leadId'];
        $company        = $_POST['company'];

        $cmtText        = 'המספר אושר לניוד לחברה אחרת';
        $cmtData = array(
            'leadId'       => $leadId,
            'userId'       => getUserId(),
            'adminId'      => getAdminId(),
            'text'         => $cmtText,
            'text_id'      => 0,
            'creationDate' => date('Y-m-d H:i:s')
        );

        $result = $this->general_model->insertRow('lead_comments', $cmtData);

        $re     = $this->general_model->updateRowById('leads', 'leadId', $leadId, array('type' => 'niyud-number', 'is_need_niyud' => 1, 'status' => 1, 'phone2' => ''));
        if (!empty($re)) {
            echo json_encode(array("result" => true));
        } else {
            echo json_encode(array("result" => false));
        }
    }

    public function changeBoxConvertType()
    {

        $box_id         = $_POST['box_id'];
        $convertType    = $_POST['convertType'];

        $re     = $this->general_model->updateRowById('customer_invoices_boxes', 'box_id', $box_id, array('convert_type' => $convertType));

        if (!empty($re)) {
            echo json_encode(array("result" => true));
        } else {
            echo json_encode(array("result" => false));
        }
    }

    public function getMultiPaymentData()
    {

        $payment_id     = $_POST['payment_id'];
        $payment        = $this->general_model->getRowById('customer_invoices_payments', 'payment_id', $payment_id);
        $payment_ids    = $payment->converted_multi_ids;
        $payments       = $this->db->query("SELECT
                                              customer_invoices_payments.payment_id,
                                              customer_invoices_payments.invoice_id,
                                              customer_invoices_payments.payment_date,
                                              customer_invoices_payments.total,
                                              customers.customerName,
                                              customer_invoices_boxes.name
                                            FROM customer_invoices_payments
                                              LEFT OUTER JOIN customer_invoices_boxes
                                                ON customer_invoices_payments.payment_box = customer_invoices_boxes.box_id
                                              LEFT OUTER JOIN customers
                                                ON customer_invoices_payments.customer_id = customers.customerId
                                            WHERE customer_invoices_payments.payment_id IN ($payment_ids)")->result();
        echo json_encode($payments);
    }

    public function getOrderDetails()
    {

        $order_id   = $_POST['order_id'];
        $order      = $this->general_model->getRowById('prepaid_orders', 'order_id', $order_id);
        $customer   = $this->general_model->getRowById('customers', 'customerId', $order->customerId);
        $data       = array(
            'order_id'          => $order->order_id,
            'customerName'      => $customer->customerName,
            'phone'             => $order->phone,
            'price_before'      => $order->price_before * -1,
            'price_after'       => $order->price_after * -1,
            'discount_amount'   => $order->discount_amount * -1,
            'date_created'      => date('d/m/Y', strtotime($order->date_created)),
        );

        echo json_encode(array("result" => true, "data" => $data));
    }

    public function createRefundOrderManual()
    {

        $data       = (object)$_POST;
        $order      = $this->general_model->getRowById('prepaid_orders', 'order_id', $data->order_id);
        $customer   = $this->general_model->getRowById('customers', 'customerId', $order->customerId);

        $orderData = array(
            'customerId'      => $order->customerId,
            'company'         => $order->company,
            'packageId'       => $order->packageId,
            'is_niyud'        => $order->is_niyud,
            'phone'           => $order->phone,
            'sim'             => $order->sim,
            'price_before'    => $data->price_before,
            'price_after'     => $data->price_after,
            'discount_amount' => $data->discount_amount,
            'credit_before'   => $order->credit_before,
            'credit_after'    => $order->credit_before,
            'parentDiscount'  => $order->parentDiscount * -1,
            'api_result'      => $order->api_result,
            'status'          => 3,
            'is_Bonus'        => $order->is_Bonus,
            'date_created'    => date('Y-m-d 23:59:59', strtotime(str_replace('/', '-', $data->date_created))),
            'lastupdate'      => date('Y-m-d H:i:s')
        );

        $result = $this->general_model->insertRow('prepaid_orders', $orderData);
        $this->general_model->updateRowById('prepaid_orders', 'order_id', $data->order_id, array('status' => 2));
        $this->general_model->updateRowById('customers', 'customerId', $customer->customerId, array('creditsPP' => $customer->creditsPP + ($data->price_after * -1)));

        if ($customer->parentId > 1) {
            $parentDetails  = $this->general_model->getRowById('customers', 'customerId', $customer->parentId);
            if ($parentDetails->can_retail_pp == 1) {
                $resultDiscount = $this->general_model->updateRowById('customers', 'customerId', $parentDetails->customerId, array('retail_credit' => $parentDetails->retail_credit - $order->parentDiscount));
            }
        }

        echo json_encode(array("result" => true));
    }

    function deleteTaskFromLead()
    {
        $data = $_POST;

        $r = $this->general_model->deleteRowById('tasks', 'taskId', $data['taskId']);
        if ($r) echo json_encode(array('result' => true, ''));
        else echo json_encode(array('result' => false));
    }

    function getLineStatusForTask()
    {

        $taskId         = $_POST['taskId'];
        $task           = $this->general_model->getRowById('tasks', 'taskId', $taskId);
        $leadId         = $task->leadId;
        $lead           = $this->general_model->getRowById('leads', 'leadId', $leadId);
        $campaign       = $this->general_model->getRowById('campaigns', 'campaignId', $lead->campaignId);
        $company        = $campaign->campaignDesc;
        $phone_number   = $lead->phone;

        if ($company == 'cellcom') {
            $result = cellcomGetData($phone_number);
            if (!empty($result) && isset($result->data[0])) {
                $re = $result->data[0];
                $data = array(
                    'ICCID'         => $re->ICCID,
                    'MSISDN'        => $re->MSISDN,
                    'SIM_STATUS'    => $re->SIM_STATUS
                );
                echo json_encode($data);
            } else {
                echo json_encode(array('result' => false));
            }
        } else if ($company == 'golan') {
            $re = getGolanSubId($phone = $phone_number);
            if (isset($re->code) && $re->code == 0) {
                if ($re->msg->freeze === 0 || $re->msg->freeze === false) {
                    $freeze_status = 'פעיל';
                } else {
                    $freeze_status = 'מוקפא';
                }

                $msg = array(
                    'freeze'    => $freeze_status,
                    'iccid'     => $re->msg->iccid,
                    'id'        => $re->msg->id,
                    'status'    => $re->msg->status
                );
                echo json_encode($msg);
            } else {
                echo json_encode(array('msg' => ''));
            }
        } else if ($company == 'hot') {
            $r          = hotGetSubscriberStatus($phone_number);
            if (!empty($r)) {
                $re         = json_decode($r);
                if (isset($re->status) && isset($re->status)) {
                    $result     = array(
                        'mirreturn_code'        => isset($re->status->mirreturn_code) ? $re->status->mirreturn_code : '',
                        'mirreturn_message'     => isset($re->status->mirreturn_message) ? $re->status->mirreturn_message : '',
                        'csrmsisdn'             => isset($re->subscriber->csrmsisdn) ? $re->subscriber->csrmsisdn : '',
                        'csrsubscriberStatus'   => isset($re->subscriber->csrsubscriberStatus) ? $re->subscriber->csrsubscriberStatus : '',
                        'csrsimNumber'          => isset($re->subscriber->csrsimNumber) ? $re->subscriber->csrsimNumber : '',
                        'csrsubscriberPo'       => isset($re->subscriber->csrsubscriberPo) ? $re->subscriber->csrsubscriberPo : ''
                    );
                    echo json_encode($result);
                } else {
                    echo json_encode(array('result' => false));
                }
            } else {
                echo json_encode(array('result' => false));
            }
        } else if ($company == 'partner') {
            $r  = partnerGetData($phone_number);
            $re = json_decode(json_decode($r));
            if (!empty($re) && isset($re->ModelBO[0]) && !empty($re->ModelBO[0])) {
                echo json_encode($re->ModelBO[0]);
            } else {
                echo json_encode(array('result' => false));
            }
        } else if ($company == 'ramilevy') {
            $phone = $phone_number;
            $r = RamiLevyStatus($phone);
            if (!empty($r)) {
                echo  json_encode($r);
            } else {
                echo json_encode(array('result' => false));
            }
        } else if ($company == 'we4g') {
            $r = We4GgetNumberDetails($phone_number);
            if (!empty($r)) {
                echo $r;
            } else {
                echo json_encode(array('result' => false));
            }
        } else {
            echo json_encode(array('result' => false));
        }
    }

    public function getGolanUsageData()
    {

        $data   = $_POST;
        $phone  = $_POST['phone'];
        $r = getGolanSubId($phone);
        if (!empty($r) && isset($r->msg)) {
            $subId = $r->msg->id;
            $re = GolanGetSubUsage($subId);
            echo json_encode(array('result' => true, "msg" => $re->msg));
        } else {
            echo json_encode(array('result' => false));
        }
    }

    public function getDataForNumber()
    {

        $data = (object)$_POST;

        if (isset($data->leadId) && !empty($data->leadId)) {
            $lead = $this->general_model->getRowById('leads', 'leadId', $data->leadId);
            if (!empty($lead)) {
                $camp           = $this->general_model->getRowById('campaigns', 'campaignId', $lead->campaignId);
                $company        = $camp->campaignDesc;
                $type           = $data->type;
                $phone          = $lead->phone;
                $tempPhone      = $lead->phone2;
                $result         = (object)array();
                $result->data   = (object)array();
                if ($company == 'we4g' && $type == 'get_status') {
                    $getData    = We4GgetNumberDetails($phone_number = $phone);
                    $data       = json_decode($getData);
                    if (isset($data->phone_number) && !empty($data->phone_number)) {
                        if ($data->state == 'activated') {
                            $status = 'פעיל';
                        } else if ($data->state == 'freeze_reseller') {
                            $status = 'הקפאת משווק';
                        } else if ($data->state == 'porting') {
                            $status = 'בניוד';
                        } else if ($data->state == 'registered') {
                            $status = 'רשום';
                        } else if ($data->state == 'dectivated') {
                            $status = 'מנותק Deactivated';
                        } else {
                            $status = 'לא פעיל';
                        }
                        if (!empty($data)) {
                            $result->result = true;
                            $result->data->Phone    = $data->phone_number;
                            $result->data->Sim      = $data->sim_iccid;
                            $result->data->Status   = $status;
                            $result->data->Package  = $data->plan;
                            $result->data->Ported   = $data->ported;
                            $result->data->Niyud    = $data->np_status;
                            $result->data->Date     = $data->date_port_in;
                        } else {
                            $result->result = false;
                        }
                    } else {
                        $result->result = false;
                    }
                } else if ($company == 'we4g' && $type == 'get_usage') {
                    $getData    = We4GgetUsageData($phone_number = $phone);
                    if (!empty($getData) && isset($getData->data) && !empty($getData->data)) {
                        $result->result = true;
                        $result->data->Sms    = $getData->data->usages->sms;
                        $result->data->Call   = number_format($getData->data->usages->call / 100, 2) . ' / ' . number_format($getData->data->groups->call / 100, 2);
                        $result->data->Data   = number_format($getData->data->usages->data / 1000000000, 2) . ' / ' . number_format($getData->data->groups->data / 1000000000, 2) . ' GB';
                    } else {
                        $result->result = false;
                    }
                } else if ($company == 'golan' && $type == 'get_status') {
                    $re = getGolanSubId($phone);
                    if (isset($re->msg) && !empty($re->msg) && isset($re->msg->id)) {
                        $api_camp_code  = $this->general_model->getRowById('campaigns', 'apiCode', $re->msg->offer_id);
                        if ($re->msg->freeze === 0 || $re->msg->freeze === false) {
                            $freeze_status = 'לא מוקפא - Not Freezed';
                        } else {
                            $freeze_status = 'מוקפא - Freezed';
                        }
                        if ($re->msg->status == 'line_status_active') {
                            $active = 'מחובר';
                        } else if ($re->msg->status == 'line_status_porting_out') {
                            $active = 'בתהליך ניוד החוצה';
                        } else {
                            $active = 'לא מחובר';
                        }
                        if ($re->msg->lost_stolen == true) {
                            $lost = 'כן';
                        } else {
                            $lost = 'לא';
                        }
                        $result->result         = true;
                        $result->data->ID       = $re->msg->id;
                        $result->data->Phone    = $phone;
                        $result->data->Sim      = $re->msg->iccid;
                        $result->data->Freeze   = $freeze_status;
                        $result->data->Status   = $active;
                        $result->data->Lost     = $lost;
                        if (!empty($api_camp_code)) {
                            $result->data->Package  = $api_camp_code->campaignName;
                        } else {
                            $result->data->Package  = $re->msg->offer_name;
                        }
                    } else {
                        $result->result         = false;
                    }
                } else if ($company == 'golan' && $type == 'get_usage') {
                    $r = getGolanSubId($phone);
                    if (!empty($r) && isset($r->msg) && isset($r->msg->id)) {
                        $subId = $r->msg->id;
                        $re = GolanGetSubUsage($subId);
                        if (isset($re->code) && $re->code == 0) {
                            $result->result = true;
                            $result->data->Sms      = $re->msg->sms_usages . ' / ' . $re->msg->sms_limit;
                            $result->data->Call     = $re->msg->calls_usages . ' / ' . $re->msg->calls_limit;
                            $result->data->Data     = $re->msg->data_usages . ' / ' . $re->msg->data_limit;
                            $result->data->Package  = $r->msg->offer_name;
                        } else {
                            $result->result         = false;
                        }
                    } else {
                        $result->result         = false;
                    }
                } else if ($company == 'hot' && $type == 'get_status') {
                    $getData    = hotGetSubscriberStatus($phone_number = $phone);
                    $data       = json_decode($getData);
                    if (isset($data->subscriber) && !empty($data->subscriber) && isset($data->subscriber->csrsubscriberStatus)) {
                        if ($data->subscriber->csrsubscriberStatus == '1') {
                            $status = 'פעיל';
                        } else {
                            $status = 'לא פעיל';
                        }
                        $result->result         = true;
                        $result->data->Phone    = $data->subscriber->csrmsisdn;
                        $result->data->Sim      = $data->subscriber->csrsimNumber;
                        $result->data->Status   = $status;
                        $result->data->Package  = '';
                    } else {
                        $result->result         = true;
                        $result->data->Phone    = $phone;
                        $result->data->Sim      = '';
                        $result->data->Status   = '';
                        $result->data->Package  = '';
                    }
                    if (!empty($tempPhone)) {
                        $getData2   = hotGetSubscriberStatus($phone_number = $tempPhone);
                        $data2      = json_decode($getData2);
                        if (isset($data2->subscriber) && !empty($data2->subscriber) && isset($data2->subscriber->csrsubscriberStatus)) {
                            if ($data2->subscriber->csrsubscriberStatus == '1') {
                                $status2 = 'פעיל';
                            } else {
                                $status2 = 'לא פעיל';
                            }
                            $result->result         = true;
                            $result->data->Phone2   = $data2->subscriber->csrmsisdn;
                            $result->data->Sim2     = $data2->subscriber->csrsimNumber;
                            $result->data->Status2  = $status2;
                            $result->data->Package2 = '';
                        } else {
                            $result->result         = true;
                            $result->data->Phone2   = $tempPhone;
                            $result->data->Sim2     = '';
                            $result->data->Status2  = '';
                            $result->data->Package2 = '';
                        }

                        if (empty($result)) {
                            $result->result         = false;
                        }
                    }
                } else if ($company == 'hot' && $type == 'get_usage') {
                    $result->result         = false;
                } else if ($company == 'partner' && $type == 'get_status') {
                    $getData    = partnerGetData($phone);
                    $data       = json_decode(json_decode($getData));

                    if (isset($data->ModelBO) && !empty($data->ModelBO)) {
                        if ($data->StatusCode == 1) {
                            $status = 'פעיל';
                        } else {
                            $status = 'לא פעיל';
                        }
                        preg_match_all('!\d+!', $data->ModelBO[0]->ProductName, $matches);
                        $result->result         = true;
                        $result->data->Phone    = $phone;
                        $result->data->Status   = $status;
                        $result->data->Package  = $matches[0][0] . 'GB';
                    } else {
                        $result->result         = true;
                        $result->data->Phone    = '';
                        $result->data->Status   = '';
                        $result->data->Package  = '';
                    }
                    if (!empty($tempPhone)) {
                        $getData2   = partnerGetData($tempPhone);
                        $data2      = json_decode(json_decode($getData2));

                        if (isset($data2->ModelBO) && !empty($data2->ModelBO)) {
                            if ($data2->StatusCode == 1) {
                                $status2 = 'פעיל';
                            } else {
                                $status2 = 'לא פעיל';
                            }
                            preg_match_all('!\d+!', $data2->ModelBO[0]->ProductName, $matches);
                            $result->result         = true;
                            $result->data->Phone2   = $tempPhone;
                            $result->data->Status2  = $status2;
                            $result->data->Package  = $matches[0][0] . 'GB';
                        } else {
                            $result->result         = true;
                            $result->data->Phone2   = '';
                            $result->data->Status2  = '';
                        }
                    }
                    if (empty($result)) {
                        $result->result         = false;
                    }
                } else if ($company == 'partner' && $type == 'get_usage') {
                    $getData    = partnerGetData($phone);
                    $data       = json_decode(json_decode($getData));
                    if (isset($data->ModelBO) && !empty($data->ModelBO)) {
                        $result->result             = true;
                        $result->data->Phone        = $phone;
                        $result->data->UsedPercent  = $data->ModelBO[0]->UsedPercent;
                        $result->data->Data         = $data->ModelBO[0]->AppliedAmountGB . 'GB / ' . $data->ModelBO[0]->CreditAmmountGB . 'GB';
                    } else {
                        $result->result         = false;
                    }
                } else if ($company == 'cellcom' && $type == 'get_status') {
                    $getData    = cellcomGetData($phone);
                    if (isset($getData->result) && $getData->result == 'SUCCESS' && !empty($getData->data)) {
                        $result->result         = true;
                        $result->data->Phone    = $phone;
                        $result->data->Sim      = $getData->data[0]->ICCID;
                        $result->data->Status   = $getData->data[0]->SIM_STATUS;
                        $result->data->Package  = $getData->data[0]->PACKAGE_SIZE_GB . 'GB';
                        $now        = time();
                        $lead_data  = strtotime($lead->creationDate);
                        $datediff   = $now - $lead_data;
                        $days       = round($datediff / (60 * 60 * 24));

                        if ($days <= 8 && !empty($lead->jobId)) {
                            $jobList = CellcomGetProvisioningJobList($jobId = $lead->jobId);
                            if (!empty($jobList)) {
                                $jobs = reindex_by_key($jobList->jobs[0]->actions, 'requestType');
                                if (isset($jobs['SIM_SWAP'])) {
                                    $result->data->SimChangeOld     = $jobs['SIM_SWAP']->initialValue;
                                    $result->data->SimChangeNew     = $jobs['SIM_SWAP']->targetValue;
                                    $result->data->SimChangeStatus  = $jobs['SIM_SWAP']->status;
                                    $result->data->SimChangeText    = $jobs['SIM_SWAP']->errorDesc;
                                    $result->data->SimText          = $jobs['SIM_SWAP']->errorMsg;
                                }
                            }
                        }
                    } else {
                        $result->result         = true;
                        $result->data->Phone    = $phone;
                        $result->data->Sim      = '';
                        $result->data->Status   = '';
                        $result->data->Package  = '';
                    }
                    if (!empty($tempPhone)) {
                        $getData2   = cellcomGetData($tempPhone);
                        if (isset($getData2->result) && $getData2->result == 'SUCCESS' && !empty($getData2->data)) {
                            $result->result         = true;
                            $result->data->Phone2   = $tempPhone;
                            $result->data->Sim2     = $getData2->data[0]->ICCID;
                            $result->data->Status2  = $getData2->data[0]->SIM_STATUS;
                            $result->data->Package2 = $getData2->data[0]->PACKAGE_SIZE_GB . 'GB';
                        } else {
                            $result->data->Phone2   = $tempPhone;
                            $result->data->Sim2     = '';
                            $result->data->Status2  = '';
                            $result->data->Package2 = '';
                        }
                    }
                    if (empty($result)) {
                        $result->result         = false;
                    }
                } else if ($company == 'cellcom' && $type == 'get_usage') {
                    $getData    = cellcomGetData($phone);
                    if (isset($getData->result) && $getData->result == 'SUCCESS' && !empty($getData->data)) {
                        $result->result         = true;
                        $result->data->Sms      = $getData->data[0]->MONTHLY_USAGE_SMS;
                        $result->data->Call     = number_format($getData->data[0]->MONTHLY_USAGE_VOICE, 2);
                        $result->data->Data     = $getData->data[0]->MONTHLY_USAGE_GB . 'GB / ' . $getData->data[0]->PACKAGE_SIZE_GB . 'GB';;
                    } else {
                        $result->result         = false;
                    }
                } else if ($company == 'ramilevy' && $type == 'get_status') {
                    $result->result         = false;
                    $getData    = RamiLevyStatus($phone);
                    /*
                    if(isset($getData->result) && $getData->result == 'SUCCESS' && !empty($getData->data)){
                        $result->result         = true;
                        $result->data->Phone    = $phone;
                        $result->data->Sim      = $getData->data[0]->ICCID;
                        $result->data->Status   = $getData->data[0]->SIM_STATUS;
                    }else{
                        $result->result         = false;
                    }
                    */
                } else if ($company == 'ramilevy' && $type == 'get_usage') {
                    $result->result         = false;
                    /*
                    $getData    = cellcomGetData($phone);
                    if(isset($getData->result) && $getData->result == 'SUCCESS' && !empty($getData->data)){
                        $result->result         = true;
                        $result->data->Sms      = $getData->data[0]->MONTHLY_USAGE_SMS;
                        $result->data->Call     = number_format($getData->data[0]->MONTHLY_USAGE_VOICE, 2);
                        $result->data->Data     = $getData->data[0]->MONTHLY_USAGE_GB . 'GB / ' . $getData->data[0]->PACKAGE_SIZE_GB .'GB';;
                    }else{
                        $result->result         = false;
                    }
                    */
                } else if ($company == 'pelephone' && $type == 'get_status') {
                    $result->result         = false;
                    $get_data = PelephoneGetProvisioningData($phone);
                    if (!empty($get_data)) {
                        if ($get_data->SIM_STATUS_CHANGE == 'Activated') {
                            $status = $get_data->SIM_STATUS_CHANGE . ' - פעיל';
                        } else if ($get_data->SIM_STATUS_CHANGE == 'Suspended') {
                            $status = $get_data->SIM_STATUS_CHANGE . ' - מושהה';
                        } else {
                            $status = $get_data->SIM_STATUS_CHANGE;
                        }
                        $result->result         = true;
                        $result->data->Phone    = $phone;
                        $result->data->Sim      = $get_data->SIM_SWAP;
                        $result->data->Status   = $status;
                        $result->data->Package  = $get_data->RATE_PLAN_CHANGE_READ_ONLY;

                        $now        = time();
                        $lead_data  = strtotime($lead->creationDate);
                        $datediff   = $now - $lead_data;
                        $days       = round($datediff / (60 * 60 * 24));
                        if ($days <= 3 && !empty($lead->jobId)) {
                            $jobList = PelephoneGetProvisioningJobList($jobId = $lead->jobId);
                            if (!empty($jobList)) {
                                $jobs = reindex_by_key($jobList->jobs[0]->actions, 'requestType');
                                if (isset($jobs['SIM_SWAP'])) {
                                    $result->data->SimChangeOld     = $jobs['SIM_SWAP']->initialValue;
                                    $result->data->SimChangeNew     = $jobs['SIM_SWAP']->targetValue;
                                    $result->data->SimChangeStatus  = $jobs['SIM_SWAP']->status;
                                    $result->data->SimChangeText    = $jobs['SIM_SWAP']->errorDesc;
                                    $result->data->SimText          = $jobs['SIM_SWAP']->errorMsg;
                                }
                            }
                        }
                    } else {
                        $result->result         = true;
                        $result->data->Phone    = $phone;
                        $result->data->Sim      = '';
                        $result->data->Status   = '';
                        $result->data->Package  = '';
                    }
                } else if ($company == 'pelephone' && $type == 'get_usage') {
                    $result->result         = false;
                    $get_data = PelephoneGetProvisioningGenericData($phone);
                    if (!empty($get_data)) {
                        $get_data = reindex_by_key($get_data, 'iu_type_desc');
                        foreach ($get_data as $key => $value) {
                            $result->result = true;
                            if ($key == 'הורדות') $type = 'Downloads';
                            if ($key == 'הודעות') $type = 'SMS';
                            if ($key == 'דקות') $type = 'Call';
                            if ($key == 'MB גלישה ב') $type = 'Data';
                            $percent = ($value->sum_iu_used / $value->sum_iu_allowed) * 100;
                            $result->data->$type = $value->sum_iu_used . ' / ' . $value->sum_iu_allowed . ' ( ' . round($percent, 2) . '% )';
                        }
                    } else {
                        $result->result         = true;
                        $result->data->Phone    = $phone;
                        $result->data->Sim      = '';
                        $result->data->Status   = '';
                        $result->data->Package  = '';
                    }
                }
                echo json_encode($result);
            } else {
                echo json_encode(array('result' => false));
            }
        } else {
            echo json_encode(array('result' => false));
        }
    }

    public function setUserOnline()
    {
        $this->general_model->updateRowById('users', 'userId', getUserId(), array('isOnline' => 1, 'last_online' => date('Y-m-d H:i:s')));
        echo json_encode(array('result' => true));
    }

    public function setUserOffline()
    {
        $this->general_model->updateRowById('users', 'userId', getUserId(), array('isOnline' => 0));
        echo json_encode(array('result' => true));
    }

    public function changeNumberType()
    {
        if (isset($_POST['type']) && !empty($_POST['type']) &&  isset($_POST['leadId']) && !empty($_POST['leadId'])) {
            $update_lead = $this->general_model->updateRowById('leads', 'leadId', $_POST['leadId'], array('type' => $_POST['type']));
            if (!empty($update_lead)) {
                echo json_encode(array('result' => true));
            } else {
                echo json_encode(array('result' => false));
            }
        } else {
            echo json_encode(array('result' => false));
        }
    }

    function deleteBankRequest()
    {
        $request_id = $_POST['request_id'];
        $this->general_model->deleteRowById('bank_requests', 'id', $request_id);
        echo json_encode(array("result" => true));
    }

    public function checkPelephoneNumberForIvr()
    {

        if (isset($_POST['phone']) && !empty($_POST['phone'])) {
            $phone          = $_POST['phone'];
            $check_phone    = PelephoneCheckIVRdetails($phone);
            if (!empty($check_phone)) {
                $data = json_decode($check_phone);
                $msg = $data[0]->Msg;
            }
            echo json_encode(array("result" => true, "text" => $msg));
        } else {
            echo json_encode(array("result" => false));
        }
    }

    public function RefreshSimPelephone()
    {

        if (isset($_POST['phone']) && !empty($_POST['phone'])) {
            $phone          = $_POST['phone'];
            $refresh_sim    = PelephoneUpdateProvisioningData($actionType = 'SIM_REFRESH', $phone, $targetValue = 1);
            if (!empty($refresh_sim) && isset($refresh_sim->result) && $refresh_sim->result == 'SUCCESS') {
                echo json_encode(array("result" => true));
            } else {
                echo json_encode(array("result" => false));
            }
        } else {
            echo json_encode(array("result" => false));
        }
    }

    public function checkNewAuthJawwal2Ajax()
    {

        $order_id = $_POST['order_id'];
        $order = $this->db->query("SELECT * FROM `prepaid_orders` WHERE `order_id` = '$order_id' ")->row();
        if (!empty($order)) {
            if ($order->company == 'jawwal2') {
                $getAuth = getOrderAuthJawwal2($order_id);
                if (!empty($getAuth) && isset($getAuth->results) && !empty($getAuth->results)) {
                    foreach ($getAuth->results as $result) {
                        if (isset($result->result_text) && !empty($result->result_text)) {
                            $api_result = $result->result_text;
                            $this->general_model->updateRowById('prepaid_orders', 'order_id', $order_id, array('api_result' => $api_result, 'lastUpdate' => date('Y-m-d H:i:s')));
                            echo json_encode(array("result" => true, "msg" => $api_result));
                        } else {
                            echo json_encode(array("result" => false));
                        }
                    }
                } else {
                    echo json_encode(array("result" => false));
                }
            }

            if ($order->company == 'road6') {
                $getAuth = getOrderAuthJawwal2($order_id);
                if (!empty($getAuth) && isset($getAuth->results) && !empty($getAuth->results)) {
                    foreach ($getAuth->results as $result) {
                        if (isset($result->result_text) && !empty($result->result_text)) {
                            $api_result = $result->result_text;
                            $this->general_model->updateRowById('prepaid_orders', 'order_id', $order_id, array('api_result' => $api_result, 'lastUpdate' => date('Y-m-d H:i:s')));
                            echo json_encode(array("result" => true, "msg" => $api_result));
                        } else {
                            echo json_encode(array("result" => false));
                        }
                    }
                } else {
                    echo json_encode(array("result" => false));
                }
            }
        } else {
            echo json_encode(array("result" => false));
        }
    }

    public function tempFreezeTempPhone()
    {

        $leadId = intval($_POST['leadId']);
        $result = array();

        if (!empty($leadId)) {
            $lead = $this->db->query('SELECT * FROM leads as l
                                        INNER JOIN phone_lines as pl ON l.leadId = pl.leadId
                                        WHERE l.leadId = ' . $leadId)->row();
            if (!empty($lead)) {
                if ($lead->temp_freezed == 0) {
                    $company    = $lead->lineProvider;
                    $phone      = $lead->phone2;
                    if ($company == 'cellcom') {
                        $r = cellcomSimStateChange($phone, 0);
                        if ($r->result == 'SUCCESS') {
                            $result['result']   = true;
                            $result['msg']      = $r->result;
                        } else {
                            $result['result']   = false;
                            $result['msg']      = $r->result;
                        }
                    } elseif ($company == 'hot') {

                        $r = hotManuiActions($phone, 1);
                        if (strpos($r->mirreturn_message, 'Success') > -1) {
                            $result['result']   = true;
                            $result['msg']      = $r->mirreturn_message;
                        } else {
                            $result['result']   = false;
                            $result['msg']      = $r->mirreturn_message;
                        }
                    } elseif ($company == 'partner') {
                        $r = partnerManuiAction($phone, '2');
                        if (isset($r->ModelBO)) {
                            $arr = $r->ModelBO;
                            $result['result']   = true;
                            $result['msg']      = $arr->StatusReason;
                        } else {
                            $result['result']   = false;
                            $result['msg']      = isset($result->ErrorMsg) ? $result->ErrorMsg : 'Unknown';
                        }
                    }
                    if ($result['result'] == true) {
                        $this->general_model->updateRowById('leads', 'leadId', $leadId, array('temp_freezed' => 1, 'lastUpdate' => date('Y-m-d H:i:s')));
                    }
                    $apiMsg = 'השהית מספר זמני בוצעה בהצלחה';
                    $dataA = array(
                        'leadId'        => $leadId,
                        'userId'        => getUserId(),
                        'adminId'       => getAdminId(),
                        'text'          => $apiMsg,
                        'creationDate'  => date('Y-m-d H:i:s'),
                    );
                    $this->general_model->insertRow('lead_comments', $dataA);
                } else {
                    $company    = $lead->lineProvider;
                    $phone      = $lead->phone2;
                    if ($company == 'cellcom') {
                        $r = cellcomSimStateChange($phone, 1);
                        if ($r->result == 'SUCCESS') {
                            $result['result']   = true;
                            $result['msg']      = $r->result;
                        } else {
                            $result['result']   = false;
                            $result['msg']      = $r->result;
                        }
                    } elseif ($company == 'hot') {

                        $r = hotManuiActions($phone, 2);
                        if (strpos($r->mirreturn_message, 'Success') > -1) {
                            $result['result']   = true;
                            $result['msg']      = $r->mirreturn_message;
                        } else {
                            $result['result']   = false;
                            $result['msg']      = $r->mirreturn_message;
                        }
                    } elseif ($company == 'partner') {
                        $r = partnerManuiAction($phone, '1');
                        if (isset($r->ModelBO)) {
                            $arr = $r->ModelBO;
                            $result['result']   = true;
                            $result['msg']      = $arr->StatusReason;
                        } else {
                            $result['result']   = false;
                            $result['msg']      = isset($result->ErrorMsg) ? $result->ErrorMsg : 'Unknown';
                        }
                    }
                    if ($result['result'] == true) {
                        $this->general_model->updateRowById('leads', 'leadId', $leadId, array('temp_freezed' => 0, 'lastUpdate' => date('Y-m-d H:i:s')));
                    }
                    $apiMsg = 'ביטול השהית מספר זמני בוצע בהצלחה';
                    $dataA = array(
                        'leadId'        => $leadId,
                        'userId'        => getUserId(),
                        'adminId'       => getAdminId(),
                        'text'          => $apiMsg,
                        'creationDate'  => date('Y-m-d H:i:s'),
                    );
                    $this->general_model->insertRow('lead_comments', $dataA);
                }
            } else {
                $result['result']   = false;
            }
        } else {
            $result['result']   = false;
        }

        echo json_encode($result);
    }

    public function CreateIVRforNumber()
    {

        if (isset($_POST['company']) && isset($_POST['phone']) && !empty($_POST['company']) && !empty($_POST['phone'])) {
            $callerid   = strip_tags(mysql_real_escape_string(trim($_POST['phone'])));
            $company    = strip_tags(mysql_real_escape_string(trim($_POST['company'])));
            if (strtolower($company) == 'pelephone') $destination = '0505010010';
            $r = createIVR($destination = '0505010010', $callerid = $_POST['phone']);
            echo json_encode(array("result" => true));
        } else {
            echo json_encode(array("result" => false));
        }
    }

    function invoiceExcelReport()
    {
        $this->load->library('PHPExcel/IOFactory');
        $filename = 'CubeBilling';
        $invoices = array();

        $where = '';
        if (isset($_POST['customerId']) && !empty($_POST['customerId'])) {
            $customerId = $this->input->post('customerId');
            $where .= " AND customerId = '$customerId' ";
        }
        if (isset($_POST['invoiceDateFrom']) && !empty($_POST['invoiceDateFrom']) && isset($_POST['invoiceDateTo']) && !empty($_POST['invoiceDateTo'])) {
            $fromInvoiceData = date('Y-m-d 00:00:00', strtotime(str_replace("/", "-", $_POST['invoiceDateFrom'])));
            $toInvoiceDate = date('Y-m-d 23:59:59', strtotime(str_replace("/", "-", $_POST['invoiceDateTo'])));
            $where .= " AND `invoice_date` BETWEEN '$fromInvoiceData' AND '$toInvoiceDate' ";
        }
        if (isset($_POST['invoiceFrom']) && !empty($_POST['invoiceFrom']) && isset($_POST['invoiceTo']) && !empty($_POST['invoiceTo'])) {
            $fromInvoice = $this->input->post('invoiceFrom');
            $toInvoice = $this->input->post('invoiceTo');
            $where .= " AND `invoice_id` BETWEEN '$fromInvoice' AND '$toInvoice' ";
        }
        $invoices = $this->db->query("SELECT * FROM `customer_invoices` WHERE 1=1 $where ")->result();

        $phpExcel = new PHPExcel();
        $phpExcel = IOFactory::load("assets/template.xlsx");
        $prestasi = $phpExcel->getActiveSheet();
        $prestasi->setCellValue('A2', 'מס חשבונית');
        $prestasi->setCellValue('B2', "תאריך");
        $prestasi->setCellValue('C2', "מספר לקוח");
        $prestasi->setCellValue('D2', 'לקוח');
        $prestasi->setCellValue('E2', 'סכום');
        $prestasi->setCellValue('F2', 'פרטים');
        $no = 3;

        foreach ($invoices as $invoice) {
            $prestasi->setCellValue('A' . $no, $invoice->invoice_id);
            $prestasi->setCellValue('B' . $no, PHPExcel_Shared_Date::PHPToExcel(strtotime($invoice->invoice_date)));
            $prestasi->setCellValue('C' . $no, $invoice->customerId);
            $prestasi->setCellValue('D' . $no, getCustomerName($invoice->customerId));
            $prestasi->setCellValue('E' . $no, $invoice->total);
            $prestasi->setCellValue('F' . $no, $invoice->custComment);
            $prestasi->getStyle('A' . $no . ':G' . $no)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $no++;
        }

        $title = 'Billing Excel test';
        $prestasi->setTitle($title);
        ob_end_clean();
        $xls_writer = IOFactory::createWriter($phpExcel, 'Excel2007'); // Trouble maker
        header('Pragma: public');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0, max-age=0');
        header('Content-type: application/vnd.ms-excel');
        header('Content-Type: application/force-download');
        header('Content-Type: application/octet-stream');
        header('Content-Type: application/download');
        header('Content-Disposition: attachment;filename=' . $filename . '.xlsx');
        header('Content-Transfer-Encoding: binary');
        //$xls_writer->save('php://output');
        // debug($prestasi);
        $a = $xls_writer->save('assets/' . $filename . '.xlsx');
        echo json_encode($filename . '.xlsx');
    }

    function setLanguage($language)
    {
        $allowed = array('arabic', 'hebrew');
        if ($language !== null && !empty($language) && in_array($language, $allowed)) {
            $this->session->set_userdata('site_lang', $language);
            echo json_encode(array('result' => true));
        } else {
            echo json_encode(array('result' => false));
        }
    }

    public function getProducts()
    {
        $warehouse_id = $this->input->post('warehouse_id', TRUE);
        $type = $this->input->post('type', TRUE);
        $products   =  reindex_by_key($this->db->query("SELECT * FROM `products`  ")->result(), 'id');

        foreach ($products as $product) {
            if ($type == "cartoon_quantity" && $product->cartoon_quantity > 0) {
                $product->warehouse_quantity = (getWarehouseQuantity($warehouse_id, $product->id)) / $product->cartoon_quantity;
            } else if ($type == "unit") {
                $product->warehouse_quantity = getWarehouseQuantity($warehouse_id, $product->id);
            } else {
                $product->warehouse_quantity = 0;
            }
        }
        echo json_encode($products);
    }
}
