<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of ACCAjax
 *
 * @author Ola
 */
class crmAjax extends mainController {

    public function __construct() {
        parent::__construct();
        $this->load->model('crm');
    }

    public function landing() {

    }

    public function submitCustomer() {
        $submit = $this->_registry->crmClass->setData($_POST)->submitCustomer();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }
    public function getCustomerData() {
        $customerData = CommonFunctions::CommonView('all_organizations', ['organization_id'], [$_GET['organization_id']]);
        $contactData = CommonFunctions::CommonView('tbl_contacts', ['organization_id', 'is_primary'], [$_GET['organization_id'], '1']);
        $attachments = Forms::get_attachments_div('uploads/crm_customers/'.$_GET['organization_id']);
        die(json_encode([$customerData, $contactData,$attachments]));
    }
    public function customerList() {
        $condition = '';
        if(is_numeric($_GET['is_contacted'])){
            $condition .= ' and is_contacted = "'.$_GET['is_contacted'].'"';
        }
        if(is_numeric($_GET['is_potiential'])){
            $condition .= ' and is_potiential = "'.$_GET['is_potiential'].'"';
        }
        if(is_numeric($_GET['is_existing'])){
            $condition .= ' and is_moved = "'.$_GET['is_existing'].'"';
        }
        if(!empty($_GET['group_id'])){
            $condition .= ' and organization_group_id = "'.$_GET['group_id'].'"';
        }
        $columns = array(array(
            'db' => 'organization_customer_name',
            'formatter' => function( $d, $row, $isExcel) {
                return $isExcel ? $d : '<a href="' . SITE_LINK . '/crm/customerProfile/' . $row['organization_id'] . '">' . $d . '</a>';
            }
        ), 'orgaization_mobile_phone', 'organization_address','contact_name','group_name','job_description',
                         array(
                             'db' => 'is_contacted',
                             'formatter' => function( $d, $row, $isExcel) {
                                 return '<span class="label text-white" style="background-color:'.($d == 0 ? 'red': 'blue').' ">'.CommonLanguage::getMessage($d == 0 ? 'no': 'yes').'</span>';
                             }
                         ), 
                         array(
                             'db' => 'is_potiential',
                             'formatter' => function( $d, $row, $isExcel) {
                                 return '<span class="label text-white" style="background-color:'.($d == 0 ? 'red': 'blue').' ">'.CommonLanguage::getMessage($d == 0 ? 'no': 'yes').'</span>';
                             }
                         ), 
                         array(
                             'db' => 'is_moved',
                             'formatter' => function( $d, $row, $isExcel) {
                                 return '<span class="label text-white" style="background-color:'.($d == 0 ? 'red': 'blue').' ">'.CommonLanguage::getMessage($d == 0 ? 'no': 'yes').'</span>';
                             }
                         ),          
                         array(
                             'db' => 'organization_id',
                             'formatter' => function( $d ) {
                                 $html = Forms::action_snippet(["color" => "complete-dark",
                                                                "isDropDown" => false, "data_id" => $d,
                                                                "ActionOption" => [["title" => CommonLanguage::getMessage("Edit"),
                                                                                    'data-target' => '#customer_modal',
                                                                                    "class" => "edit_customer",
                                                                                    "icon" => "fa-pencil",
                                                                                    "permission" => "edit_crm_customer"
                                                                                   ]
                                                                                  ]]);
                                 return $html;
                             }
                         )
                        );
        $key = 'organization_id';
        $table = 'all_organizations';
        $data = DataTable::complex($_GET, $table, $key, $columns,' 1=1 '.$condition);
        echo json_encode($data);
    }

    public function submitContact() {
        $submit = $this->_registry->crmClass->setData($_POST)->submitContact();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }
    public function contactList() {
        $condition = '';
        if(!empty($_GET['organization_id']))
            $condition .= ' and organization_id = "'.$_GET['organization_id'].'"';
        $columns = array(array(
            'db' => 'contact_name',
            'dt' => 0,
            'formatter' => function( $d, $row, $isExcel) {
                return $isExcel ? $d : '<a href="' . SITE_LINK . '/crm/contactProfile/' . $row[6] . '">' . $d . '</a>';
            }
        ), array(
            'db' => 'organization_customer_name',
            'dt' => 1,
            'formatter' => function( $d, $row, $isExcel) {
                return $isExcel ? $d : '<a href="' . SITE_LINK . '/crm/customerProfile/' . $row[7] . '">' . $d . '</a>';
            }
        ), 'contact_work_phone', 'contact_mobile_phone', 'contact_email',
                         array(
                             'db' => 'contact_id',
                             'dt' => 5,
                             'formatter' => function( $d ) {
                                 $html = Forms::action_snippet(["color" => "complete-dark", "isDropDown" => false, "data_id" => $d,
                                                                "ActionOption" => [["title" => CommonLanguage::getMessage("Edit"),
                                                                                    'data-target' => '#contact_modal',
                                                                                    "class" => "edit_contact",
                                                                                    "icon" => "fa-pencil",
                                                                                    "permission" => "edit_crm_contact"
                                                                                   ]
                                                                                  ]]);
                                 return $html;
                             }
                         ), 'contact_id', 'organization_id'
                        );
        $key = 'contact_id';
        $table = 'all_contacts';
        $data = DataTable::complex($_GET, $table, $key, $columns,' 1=1 '.$condition);
        echo json_encode($data);
    }

    public function submitDeal() {
        $submit = $this->_registry->crmClass->setData($_POST)->submitDeal();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }
    public function deleteDeal() {
        $submit = $this->_registry->crmClass->setData($_POST)->deleteDeal();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }
    public function getDealDetails() {
        $data['main'] = CommonFunctions::CommonView('all_deals', ['deal_id'], [$_GET['rowId']]);
        $data['product_category'] = $this->_registry->crmClass->getDealProductCat($data['main'][0]['Cat_ID']);
        $data['attachments'] = Forms::get_attachments_div('uploads/deals/'.$_GET['rowId']);
        die(json_encode($data));
    }
    public function dealList() {
        $condition = $_GET['deal_state'] == '' ? '' : ' and deal_state="' . $_GET['deal_state'] . '"';
        if (isset($_GET['Date_From']) && isset($_GET['Date_To'])) {
            $FromDate = $_GET['Date_From'];
            $ToDate = $_GET['Date_To'];
            $condition .= ' and  Date(date_last_contacted) >= "' . $FromDate . '" AND Date(date_last_contacted) <= "' . $ToDate . '"';
        }
        $columns = array('deal_id', array(
            'db' => 'deal_title',
            'formatter' => function( $d, $row, $isExcel) {
                return $isExcel ? $d : '<a href="' . SITE_LINK . '/crm/dealDetails/' . $row['deal_id'] . '">' . $d . '</a>';
            }
        ), 'stage_title', array(
            'db' => 'deal_state',
            'formatter' => function( $d, $row) {
                return CommonLanguage::getMessage($d);
            }
        ), array(
            'db' => 'deal_value',
            'formatter' => function( $d, $row) {
                return CommonLanguage::getMessage($d).' '.$row['Currency_Symbol'];
            }
        ),'deal_probability', 'reason_for_loss',
                         array(
                             'db' => 'organization_customer_name',
                             'formatter' => function( $d, $row, $isExcel) {
                                 return $isExcel ? $d : '<a href="' . SITE_LINK . '/crm/customerProfile/' . $row['organization_id'] . '">' . $d . '</a>';
                             }
                         ), 'date_last_contacted', 'User_Name', array(
                             'db' => 'Cat_ID',
                             'formatter' => function( $d, $row) {
                                 return self::getDealProductCategory($d);
                             }
                         ),
                         array(
                             'db' => 'deal_id',
                             'formatter' => function( $d ) {
                                 $html = Forms::action_snippet(["color" => "complete-dark", "isDropDown" => false, "data_id" => $d,
                                                                "ActionOption" => [["title" => CommonLanguage::getMessage("Edit"),
                                                                                    'data-target' => '#deal_modal',
                                                                                    "class" => "edit_deal",
                                                                                    "icon" => "fa-pencil",
                                                                                    "permission" => "edit_deal"
                                                                                   ]
                                                                                  ]]);
                                 return $html;
                             }), 'organization_id','Currency_Symbol'
                        );
        $key = 'deal_id';
        $table = 'all_deals';
        $data = DataTable::complex($_GET, $table, $key, $columns, ' 1=1 ' . $condition);
        echo json_encode($data);
    }
    public function getDealProductCategory($category_id) {
        $data = $this->_registry->crmClass->getDealProductCategory($category_id);
        return $data;
    }

    public function UploadExcelFileAjax() {
        if (isset($_FILES['Document_File_Name'])) {
            $logged_id = Session::getUserID();
            array_push($_POST, $logged_id);
            $submit = $this->_registry->crmClass->setdata($_POST)->uploadExcelSheet();
            die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
        }
    }

    public function submitActivity() {
        $submit = $this->_registry->crmClass->setData($_POST)->submitActivity();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    } 
    public function activityList() {
        $condition = '';
        $current_date_filter = $_GET['current_date'];
        if ($current_date_filter == 'planned') {
            $condition .= ' and start > "' . date('Y-m-d h:i:s') . '" and activity_checked = 0';
        } else if ($current_date_filter == 'overdue') {
            $condition .= ' and start < "' . date('Y-m-d h:i:s') . '" and activity_checked = 0';
        } else if ($current_date_filter == '') {
            $condition .= '';
        } else {
            $data = explode("->", $current_date_filter);
            $condition .= '  and   (   Date(start) >= "' . $data[0] . '"
                and
                    Date(start) <= "' . $data[1] . '"
                  and activity_checked =0  )
                    or
                    ( Date(end) >= "' . $data[0] . '"
                and
                    Date(end) <=  "' . $data[1] . '" 
                    and activity_checked =0) ';
        }
        $condition .= $_GET['activity_type_id'] == 0 ? '' : ' and activity_type_id ="' . $_GET['activity_type_id'] . '"';
        if(!empty($_GET['action_type_id']))
            $condition .= ' and action_type_id ="'.$_GET['action_type_id'].'"';
        if(is_numeric($_GET['status_id']))
            $condition .= ' and activity_checked ="'.$_GET['status_id'].'"';
        $columns = array(array(
            'db' => 'activity_checked',
            'formatter' => function( $d, $row, $isExcel) {
                return $isExcel ? ($d == 0 ? 'Not Done' : 'Done') : '<input type="checkbox" name="check_done"  class="' . ($d == 0 ? '' : 'text-line-through') . '" data-id="' . $row['id'] . '" ' . ($d == 0 ? '' : ' checked') . '  />';
            }
        ), array(
            'db' => 'organization_customer_name',
            'formatter' => function( $d, $row, $isExcel) {
                return $isExcel ? $d : '<a href="' . SITE_LINK . 'crm/customerProfile/' . $row['organization_id'] . '" >' . $d . '</a>';
            }
        ), array(
            'db' => 'deal_title',
            'formatter' => function( $d, $row, $isExcel) {
                return $isExcel ? $d : '<a href="' . SITE_LINK . 'crm/dealDetails/' . $row['deal_id'] . '" >' . $d . '</a>';
            }
        ), 'activity_type_title', 'activity_notes', 'start', 'activity_duration','action_type_name',
                         array(
                             'db' => 'id',
                             'formatter' => function( $d, $row) {
                                 $html = Forms::action_snippet(
                                     ["color" => "complete-dark",
                                      "isDropDown" => false, "data_id" => $d,
                                      "ActionOption" => [["title" => CommonLanguage::getMessage("Edit"),
                                                          'data-target' => '#activity_modal',
                                                          "class" => "edit_activity",
                                                          "icon" => "fa-pencil",
                                                          "attr"=>"data-origin=calendar",
                                                          "permission" => "edit_crm_activity"
                                                         ]
                                                        ]]);
                                 return $html;
                             }), 'organization_id', 'deal_id'
                        );
        $key = 'id';
        $table = 'all_activities';
        $data = DataTable::complex($_GET, $table, $key, $columns, ' 1=1 ' . $condition);
        echo json_encode($data);
    }
    public function getAllActivities() {
        $data = $this->_registry->crmClass->setData($_GET)->getAllActivities();
        echo json_encode($data);
    }

    public function pipelineData() {
        $data = $this->_registry->crmClass->pipelineData();
        die(json_encode($data));
    }
    public function getPlannedOverDueActivity() {
        $divided = array_key_exists('divided', $_POST) ? 1 : null;
        if(!empty($_POST['deal_id']))
            $data['deal_details'] = CommonFunctions::CommonView('all_deals', ['deal_id'], [$_POST['deal_id']])[0];
        $data['main'] = $this->_registry->crmClass->setData($_POST)->getPlannedOverdueActivities($divided);
        die(json_encode($data));
    }

    public function getProfileLog() {
        $data = $this->_registry->crmClass->setData($_GET)->getProfileLog();
        die(json_encode($data));
    }

    public function submitCurrentCall() {
        $submit = $this->_registry->crmClass->setData($_POST)->submitCurrentCall();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }
    public function updateActivityStatus() {
        $submit = $this->_registry->crmClass->setData($_POST)->updateActivityStatus();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }
    public function addNote() {
        $submit = $this->_registry->crmClass->setData($_POST)->submitNote();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }

    public function submitDealState() {
        $submit = $this->_registry->crmClass->setData($_POST)->submitDealState();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }

    public function updateDealStage() {
        $submit = $this->_registry->crmClass->setData($_POST)->updateDealStage();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }
    public function dealTransaction() {
        $data = CommonFunctions::CommonView('tbl_deals_progress', ['deal_id'], [$_POST['deal_id']]);
        die(json_encode($data));
    }

    public function contraList() {
        $columns = array('contra_nb', 'Customer_Name', 'contra_date',
                         array('db' => 'contra_amount',
                               'formatter' => function( $d, $row ) {
                                   return ($d . ' ' . $row['Currency_Symbol']);
                               }),
                         array(
                             'db' => 'contra_id',
                             'formatter' => function( $d ) {
                                 $html = Forms::action_snippet(["color" => "complete-dark",
                                                                "isDropDown" => false, "data_id" => $d,
                                                                "ActionOption" => [["title" => CommonLanguage::getMessage("Edit"),
                                                                                    //                                                                                    'data-target' => '#customer-modal',
                                                                                    "class" => "edit_contra",
                                                                                    "icon" => "fa-pencil",
                                                                                    "permission" => "edit_crm_contra"
                                                                                   ]
                                                                                  ]]);
                                 return $html;
                             }
                         ), 'Currency_Symbol'
                        );
        $key = 'contra_id';
        $table = 'crm_contra_list';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }
    public function add_edit_contra(){
        $insert = $this->_registry->crmClass->setData($_POST)->add_edit_contra();
        die(json_encode(empty($insert) ? ['success',  CommonLanguage::getMessage('Submitted_Successfully')] : ['danger',$insert[0]]));
    }
    public function get_contra_by_id(){
        $data = $this->_registry->crmClass->get_contra_by_id($_GET['id']);
        die(json_encode($data));
    }

    public function UpdateActivityTime() {
        $submit = $this->_registry->crmClass->setData($_POST)->UpdateActivityTime();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }
    public function updateCustomerPotiential() {
        $submit = $this->_registry->crmClass->setData($_GET)->updateCustomerPotiential();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }
public function general_contact_list() {
        $columns = array('contact_name', 'contact_phone','contact_mobile',
                       'contact_job','contact_note',
                         array(
                             'db' => 'contact_id',
                             'formatter' => function( $d ) {
                                 $html = Forms::action_snippet(["color" => "complete-dark",
                                                                "isDropDown" => true, "data_id" => $d,
                                                                "ActionOption" => [["title" => CommonLanguage::getMessage("Edit"),
                                                                                    //                                                                                    'data-target' => '#customer-modal',
                                                                                    "class" => "edit_contact",
                                                                                    "icon" => "fa-pencil",
                                                                                    "permission" => "edit_general_contact"
                                                                                   ],
                                                                    ["title" => CommonLanguage::getMessage("delete"),
                                                                                    //                                                                                    'data-target' => '#customer-modal',
                                                                                    "class" => "delete_general_contact",
                                                                                    "icon" => "fa-trash",
                                                                                    "permission" => "delete_general_contact"
                                                                                   ]
                                                                                  ]]);
                                 return $html;
                             }
                         )
                        );
        $key = 'contact_id';
        $table = 'tbl_general_contact';
        $data = DataTable::complex($_GET, $table, $key, $columns);
        echo json_encode($data);
    }
     public function submit_general_contact() {
        $submit = $this->_registry->crmClass->setData($_POST)->submit_general_contact();
        die(json_encode(empty($submit) ? [CommonLanguage::getMessage('Submitted_Successfully'), 'success'] : [$submit[0], 'danger']));
    }
     public function delete_general_contact() {
        $submit = $this->_registry->crmClass->delete_general_contact($_GET['contact_id']);
        die(empty($submit) ? "ok" : $submit[0]);   
    }
    public function general_guide_report() {
        $cond=' 1=1 ';
        if(isset($_GET['type']) && $_GET['type'] !=''){
            $cond.=' and type = "'.$_GET['type'].'" ';
        }
        $columns = array('contact_name', 'contact_phone','contact_mobile',
                       'contact_job','contact_note');
        $key = 'contact_id';
        $table = "(SELECT concat('con',contact_id) as contact_id,contact_name,contact_job,contact_phone,
            contact_mobile,contact_note,0 as type FROM `tbl_general_contact` 
            UNION select concat('cust',Customer_ID) as contact_id,Customer_Name as contact_name,
            '' as contact_job,Customer_Phone as contact_phone,Customer_Mobile as contact_mobile,
            Customer_Note as contact_note,1 as type from tbl_customers 
            UNION select concat('pos',customer_id) as contact_id,customer_name as contact_name,
            '' as contact_job,'' as contact_phone ,customer_phone as customer_mobile,
            customer_address as customer_note,2 as type from tbl_pos_customers) as temp";
        $data = DataTable::complex($_GET, $table, $key, $columns,$cond);
        echo json_encode($data);
    }
}
