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

class Customers extends Admin_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('customers_model');
	}
	
	public function index() {
	    $ownerId = $this->session->userdata('userData');
        $customers = $this->general_model->getTableWhereArray('customers', array('customerId !=' => 1));
        
        foreach($customers as &$c) {            
            $agent = $this->db->query("SELECT * FROM users WHERE FIND_IN_SET(".$c->customerId.", allowedSuppliers) AND userLevel = 4 ")->row();
            $c->agent = '';
            if($agent) $c->agent = $agent->firstname.' '.$agent->lastname;
            $c->totalPays = 0;
            $c->cntSubs = $this->general_model->getCountByColumn('customers', 'parentId', $c->customerId);            
        }        
        
        $this->template
            ->set('view', 'admin/customers/index')
    		->set('customers', $customers)
            ->render();
	}
    
    public function customerForm() {
        
        $this->session->unset_userdata('flashMsg');
    	$campaignPrices = $leads = $lines = $openCustPayments = $subCusts = $subUsers = array();
        if($this->uri->segment(4) === FALSE) {
    		$customerId = '';
            $customer[0] = $this->general_model->getTableEmptyArray('customers');
            $mode = $this->lang->line('added');
    	} else {
    		$customerId = $this->uri->segment(4);
            $customer = $this->customers_model->getCustomerById($customerId);
            $mode = 'עריכת';
            $subUsers = $this->db->query("SELECT * FROM `users` WHERE `adminId` = '$customerId' ")->result();
            $current_customer = $this->general_model->getRowById('customers', 'customerId', $customerId);
    	}
    	
        $userTypes = $this->general_model->getUserTypes();
        $banks = $this->general_model->getTable('banks_codes');
        
    	$this->template
    		->set('view', 'admin/customers/customerForm')
    		->set('metaDescription', 'description')
            ->set('customer', $customer[0])
            ->set('userTypes', $userTypes)
            ->set('mode', $mode)
            ->set('subCusts', $subCusts)
            ->set('subUsers', $subUsers)
            ->set('banks', $banks)
    		->render();
    }
    
    function customerAction() {
        
        $this->load->library('encrypt');
        
        $customerId             = $this->input->post('customerId');	   
		$customerName           = $this->input->post('customername');
		$phoneNumber            = $this->input->post('phonenumber');
        $email                  = $this->input->post('email');
        $address                = $this->input->post('address');
        $city                   = $this->input->post('city');
        $credits                = $this->input->post('credits');
        $creditsLimit           = $this->input->post('creditsLimit');
        $isActive               = $this->input->post('isActive') ? 1 : 0;        
        $is_auto_pay_active     = $this->input->post('is_auto_pay_active') ? 1 : 0;
        $how_to_pay             = $this->input->post('how_to_pay');
        $days_to_pay            = $this->input->post('days_to_pay');
        $bank                   = $this->input->post('bank');
        $branch                 = $this->input->post('branch');
        $bank_account           = $this->input->post('bank_account');
        $invEmail               = $this->input->post('invEmail');
        $invName                = $this->input->post('invName');
        $invID                  = $this->input->post('invID');

		if(!isset($customerId) || $customerId == '' || $customerId == null) {
            $str = generateRandomString(32);
            $salt = $this->encrypt->encode($str);
                        
            $customerData = array(
                'category_id'           => 14,
                'customerName'          => $customerName,
                'phoneNumber'           => $phoneNumber,
                'email'                 => $email,
                'address'               => $address,
                'city'                  => $city,
                'isActive'              => 1,
                'credits'               => $credits,
                'creditsLimit'          => $creditsLimit,
                'creationDate'          => date('Y-m-d H:i:s'),
                'lastUpdate'            => date('Y-m-d H:i:s'),
                'bank'                  => $bank,
                'branch'                => $branch,
                'bank_account'          => $bank_account,
                'invEmail'              => $invEmail,
                'invName'               => $invName,
                'invID'                 => $invID
            );
            
            if(checkEmailExists($email, 'customers') || checkEmailExists($email, 'users')) {
                $this->session->set_flashdata('flashMsgType', 'Error');
                $this->session->set_flashdata('flashMsg', 'הכתובת '.$email.' קיימת במערכת!');
    			redirect('admin/customers/customerForm/', 'location');
            }      
          
			$result = $this->general_model->insertRow('customers', $customerData);
            $this->general_model->insertRow('customers_prefs', array('customerId' => $result, 'lastUpdate'    => date('Y-m-d H:i:s')));
            
			if (!$result == false) {
                $password   = generateRandomString(8);
                $str        = generateRandomString(32);
                $salt       = $this->encrypt->encode($str);
    		    $saltedPW   =  $password . $salt;
    		    $hashedPW   = hash('sha256', $saltedPW);
                $name       = $customerName;
                $userData = array(
                    'firstname'     => $name[0],
                    'lastname'      => $name[1],
                    'email'         => $email,
                    'phone'         => $phoneNumber,
                    'password'      => $hashedPW,
                    'isActive'      => 1,
                    'salt'          => $salt,
                    'typeId'        => 1,  
                    'userLevel'     => 3, 
                    'adminId'       => $result,
                    'isMain'        => 1,
                    'creationDate'  => date('Y-m-d H:i:s'),
                    'lastUpdate'    => date('Y-m-d H:i:s')
                );
    			$resultU = $this->general_model->insertRow('users', $userData);
                $this->general_model->updateRowById('customers', 'customerId', $result, array('adminId' => $resultU));
                //packages and companies
                $main_permessions = $this->db->query("SELECT `text`, `type` FROM `users_permissions_main`")->result();
        	    $permessions_array = $texts = array();
                foreach( $main_permessions as $mPer ){
                    $permessions_array[$mPer->type][$mPer->text] = 1;
                }
        	    foreach( $permessions_array as $key => $value ){
        	        foreach( $value as $k => $v ){
        	            $per_data = array(
                                'type'          => $key,
                                'userId'        => $resultU,
                                'text'          => $k,
                                'permission'    => 1,
                                'createdBy'     => 785,
                                'dateCreation'  => date('Y-m-d H:i:s'),
                                'lastUpdate'    => date('Y-m-d H:i:s')
                            );
                        $addPerm = $this->general_model->insertRow('users_permissions', $per_data);
        	        }
        	    }
                // $mailData = array( 'name' => $name[0].' '.$name[1] );
                // $message = $this->load->view('emails/wellcomeEmail', $mailData, true);
                // sendEmail($email, 'kreaot.callup@gmail.com', 'CallUp CMS', 'מפיץ חדש - '.$customerName, $message, $cc = '', $bcc = 'kreaot.callup@gmail.com', $html = true);
                
                $this->session->set_flashdata('flashMsgType', 'Success');
				$this->session->set_flashdata('flashMsg', $customerName.' נשמר בהצלחה');
				redirect('admin/customers/customerForm/'.$result, 'refresh');
			} else {
			    $this->session->set_flashdata('flashMsgType', 'Error'); 
				$this->session->set_flashdata('flashMsg', 'אופס! אירעה שגיאה, אנא נסה שנית.');
				redirect('admin/customers/', 'refresh');
			}
		} else {
		    $customer = $this->customers_model->getCustomerById($customerId);
            
            $sqlData = array(
                'category_id'           => 14,
                'customerName'          => $customerName,
                'phoneNumber'           => $phoneNumber,
                'email'                 => $email,
                'address'               => $address,
                'city'                  => $city,
                'isActive'              => 1,
                'credits'               => $credits,
                'creditsLimit'          => $creditsLimit,
                'creationDate'          => date('Y-m-d H:i:s'),
                'lastUpdate'            => date('Y-m-d H:i:s'),
                'bank'                  => $bank,
                'branch'                => $branch,
                'bank_account'          => $bank_account,
                'invEmail'              => $invEmail,
                'invName'               => $invName,
                'invID'                 => $invID
            );
            
            $customer = $this->general_model->getRowById('customers', 'customerId', $customerId);
            
			$result = $this->general_model->updateRowById('customers', 'customerId', $customerId, $sqlData);
			if ($result) {
			    $this->session->set_flashdata('flashMsgType', 'Success'); 
				$this->session->set_flashdata('flashMsg','השינויים נשמרו בהצלחה!');
			}
			else {
			    $this->session->set_flashdata('flashMsgType', 'Error');  
				$this->session->set_flashdata('flashMsg','אופס! אירעה שגיאה, אנא נסה שנית.');
			}
			redirect('admin/customers/customerForm/'.$customerId, 'location');
		}
	}
    public function customerPrice($customerId){

        $whereInvoice = $wherePayment = $join = $limit = "";
        $customerId = intval($this->uri->segment(4));
        if(isset($_POST['firstPayDate']) && !empty($_POST['firstPayDate']) && isset($_POST['firstPayToDate']) && !empty($_POST['firstPayToDate'])){
	        $date_from  = date('Y-m-d 00:00:00', strtotime(str_replace('/','-',$_POST['firstPayDate'])));
	        $date_to    = date('Y-m-d 23:59:59', strtotime(str_replace('/','-',$_POST['firstPayToDate'])));
	    }else{
	        $date_to    = date('Y-m-d 23:59:59', strtotime('now'));
	        $date_from  = date('Y-m-d 00:00:00', strtotime('-1 Week'));
	    }
        $whereInvoice = " AND `invoice_date` BETWEEN '$date_from' AND '$date_to'";
        $wherePayment = " AND `payment_date` BETWEEN '$date_from' AND '$date_to'";
        
        $invoices = $this->db->query("SELECT `invoice_id` as `id`, `total`, `invoice_date` as `date`, `customerId`, `dateCreation`, `reference_id`
                                        FROM `customer_invoices`
                                        WHERE `customerId`= '$customerId'
                                        AND `invoice_type` = 2 
                                        $whereInvoice
                                        ORDER BY `invoice_date` DESC" )->result();
        $payments = $this->db->query("SELECT `payment_id` as `id`, `total`, `payment_date` as `date`, `customerId`, `dateCreation`
                                        FROM `customer_invoices_payments`
                                        WHERE `customerId` = '$customerId'
                                        $wherePayment
                                        ORDER BY `payment_date` DESC")->result();

        $data = array();
        foreach($invoices as $invoice){
            $invoice->type = 'invoice';

            $data[] = $invoice;
        }
        foreach($payments as $payment){
            $payment->type = 'payment';
            $data[] = $payment;
        }

        function sortFunction( $a, $b ) {
            return strtotime($a->date) - strtotime($b->date);
        }
        usort($data, "sortFunction");
        $date_from_balance  = date('1970-01-01 00:00:00');
        $date_to_balance    = date('Y-m-d 23:59:59', strtotime('-1 day'. $date_from));
        $whereInvoice_balance = " AND `invoice_date` BETWEEN '$date_from_balance' AND '$date_to_balance'";
        $wherePayment_balance = " AND `payment_date` BETWEEN '$date_from_balance' AND '$date_to_balance'";
        
        $invoices_sum = $this->db->query("SELECT SUM(total) as total
                                        FROM `customer_invoices`
                                        WHERE `customerId`= '$customerId'
                                        $whereInvoice_balance
                                        ORDER BY `invoice_date` DESC" )->row();
        $payments_sum = $this->db->query("SELECT SUM(total) as total
                                        FROM `customer_invoices_payments`
                                        WHERE `customerId` = '$customerId'
                                        $wherePayment_balance
                                        ORDER BY `payment_date` DESC")->row();
        $sum = 0;
        if(!empty($invoices_sum) && isset($invoices_sum->total) ){
            $sum -= $invoices_sum->total;
        }
        if(!empty($payments_sum) && isset($payments_sum->total) ){
            $sum += $payments_sum->total;
        }
        
        $this->template
        ->set('view', 'admin/customers/customerPrice')
        ->set("data", $data)
        ->set('date_from', $date_from)
        ->set('date_to', $date_to)
        ->set('sum', $sum)
        ->render();

    }

    public function customersOnline(){
        
        if(isset($_POST['from_date']) && !empty($_POST['from_date'])){
            $date_from = date('Y-m-d 00:00:00', strtotime(str_replace('/','-',$_POST['from_date'])));
        }else{
            $date_from = date('Y-m-d 00:00:00', strtotime('-1 DAYS'));
        }
        if(isset($_POST['to_date']) && !empty($_POST['to_date'])){
            $date_to = date('Y-m-d 23:59:59', strtotime(str_replace('/','-',$_POST['to_date'])));
        }else{
            $date_to = date('Y-m-d 23:59:59', strtotime('now'));
        }
        if(isset($_POST['from_date']) && !empty($_POST['from_date']) && isset($_POST['to_date']) && !empty($_POST['to_date'])){
            $sessions   = $this->db->query("SELECT * FROM `customers_online` WHERE `session_date` BETWEEN '$date_from' AND '$date_to' ORDER BY `id` DESC")->result();
        }else{
            $sessions   = $this->db->query("SELECT * FROM `customers_online` WHERE date(`session_date`) = CURDATE() ORDER BY `id` DESC")->result();
        }
        $customers  = reindex_by_key( $this->db->query("SELECT customerName, customerId FROM customers WHERE isActive = 1")->result(), 'customerId');

        $this->template
            ->set('view', 'admin/customers/customersOnline')
            ->set('sessions', $sessions)
    		->set('customers', $customers)
    		->set('date_from', $date_from)
    		->set('date_to', $date_to)
            ->render();
    }
    
    public function customersLiveOnline(){
        
        $usersOnline    = reindex_by_key($this->db->query("SELECT `userId`, `firstname`, `lastname`, `userLevel`, `adminId`, `last_online`, `isOnline` FROM `users` WHERE `userLevel` != 4")->result(), 'userId');
        $customers      = reindex_by_key($this->db->query("SELECT customerId, customerName FROM `customers` WHERE isActive = 1")->result(), 'customerId');
        foreach( $usersOnline as $user ){
            $diff_mins      = ( time() - strtotime($user->last_online)) / 60;
            
            if($user->userLevel == 3){
                if(isset($customers[$user->adminId])){
                    $session            = $this->db->query("SELECT * FROM `customers_online` WHERE `customerId` = '$user->adminId' ORDER BY `id` DESC LIMIT 1")->row();
                    $user->name         = $customers[$user->adminId]->customerName;
                    if(!empty($session) && !empty((int)$user->last_online) ){
                        $user->ip_address   = $session->ip_address;
                        $user->session_date = date('d/m/Y - H:i', strtotime($user->last_online));
                    }elseif( !empty($session) && empty((int)$user->last_online) ){
                        $user->ip_address   = $session->ip_address;
                        $user->session_date = date('d/m/Y - H:i', strtotime($session->session_date));
                    }else{
                        $user->ip_address   = 'Unknown';
                        $user->session_date = 'Unknown';
                    }
                }else{
                    unset($usersOnline[$user->userId]);
                }
            }else{
                $session            = $this->db->query("SELECT * FROM `customers_online` WHERE `customerId` = '$user->userId' ORDER BY `id` DESC LIMIT 1")->row();
                $user->name         = $user->firstname . ' ' . $user->lastname;
                if(!empty($session) && !empty((int)$user->last_online) ){
                    $user->ip_address   = $session->ip_address;
                    $user->session_date = date('d/m/Y - H:i', strtotime($user->last_online));
                }elseif( !empty($session) && empty((int)$user->last_online) ){
                    $user->ip_address   = $session->ip_address;
                    $user->session_date = date('d/m/Y - H:i', strtotime($session->session_date));
                }else{
                    $user->ip_address   = 'Unknown';
                    $user->session_date = 'Unknown';
                }
            }
        }
        
        $this->template
            ->set('view', 'admin/customers/customersLiveOnline')
            ->set('usersOnline', $usersOnline)
            ->render();
    }
    
    public function categories(){
        
        $customers  = $this->general_model->getTableWhereArray('customers', array('customerId !=' => 1, 'isActive' => 1));
        $categories = reindex_by_key($this->db->query("SELECT * FROM `customers_categories` ORDER BY `category_id` ASC")->result(), 'category_id');
        
        $this->template
            ->set('view', 'admin/customers/categories')
    		->set('customers', $customers)
    		->set('categories', $categories)
            ->render();
    }
    
    public function addCategory(){
        
        $data = array(
                'category_name' => $_POST['text'],
                'description'   => $_POST['desc']
            );
        $result = $this->general_model->insertRow('customers_categories', $data);
        if(!empty($result)){
            echo json_encode(array( 'result' => true, "id" => $result ));
        }else{
            echo json_encode(array( 'result' => false ));
        }
    }
    
    public function editCategory(){
        
        $data = array(
                'category_name' => $_POST['text'],
                'description'   => $_POST['desc']
            );
        $update_data = $this->general_model->updateRowById('customers_categories', 'category_id', $_POST['cat'], $data );
        if(!empty($update_data)){
            echo json_encode(array( 'result' => true ));
        }else{
            echo json_encode(array( 'result' => false ));
        }   
    }
    
    public function deleteCategory(){
        
        $delete_row = $this->general_model->DeleteRowById('customers_categories', 'category_id', $_POST['cat'] );
        if(!empty($delete_row)){
            echo json_encode(array( 'result' => true ));
        }else{
            echo json_encode(array( 'result' => false ));
        }   
    }
    
    public function updateCustomerCategory(){
        $update_data        = $this->general_model->updateRowById('customers', 'customerId', $_POST['customerId'], array('category_id' => $_POST['cat']) );

        if(!empty($update_data)){
            echo json_encode(array( 'result' => true ));
        }else{
            echo json_encode(array( 'result' => false ));
        } 
        
    }
    
    public function limitChanges(){
        
        if(isset($_POST['from_date']) && !empty($_POST['from_date'])){
            $date_from = date('Y-m-d 00:00:00', strtotime(str_replace('/','-',$_POST['from_date'])));
        }else{
            $date_from = date('Y-m-d 00:00:00', strtotime('-1 DAYS'));
        }
        if(isset($_POST['to_date']) && !empty($_POST['to_date'])){
            $date_to = date('Y-m-d 23:59:59', strtotime(str_replace('/','-',$_POST['to_date'])));
        }else{
            $date_to = date('Y-m-d 23:59:59', strtotime('now'));
        }
        
        $limits     = $this->db->query("SELECT * FROM `customers_limit_changes` WHERE `dateCreation` BETWEEN '$date_from' AND '$date_to' ORDER BY `id` DESC ")->result();
        $sum = array();
        $sum['credits']       = $this->db->query("SELECT SUM(`creditsLimit`) as `total` FROM `customers` WHERE `parentId` = 1")->row()->total;
        $sum['creditPPLimit'] = $this->db->query("SELECT SUM(`creditPPLimit`) as `total` FROM `customers`")->row()->total;
        $sum['cards_limit']   = $this->db->query("SELECT SUM(`cards_limit`) as `total` FROM `customers`")->row()->total;
        
        $this->template
            ->set('view', 'admin/customers/limitChanges')
            ->set('limits', $limits)
            ->set('date_from', $date_from)
    		->set('date_to', $date_to)
    		->set('sum', $sum)
            ->render();
    }
    
    public function removeFromOblego(){
        if(isset($_POST['type']) && isset($_POST['total']) && !empty($_POST['type']) && !empty($_POST['total']) && $_POST['total'] > 0
        && isset($_POST['customerId']) && !empty($_POST['customerId']) && isset($_POST['creditType']) && !empty($_POST['creditType'])){
            $customer = $this->general_model->getRowById('customers', 'customerId', intval($_POST['customerId']));
            if( $_POST['creditType'] == 'credit' ){
                $newLimit = $customer->$_POST['type'] + $_POST['total'];
            }else{
                $newLimit = $customer->$_POST['type'] - $_POST['total'];
            }
            $updateCustomer = $this->general_model->updateRowById('customers', 'customerId', intval($_POST['customerId']), array( $_POST['type'] => $newLimit));
            if(!empty($updateCustomer)){
                
                $change_data = array(
                        'customerId'    => $_POST['customerId'],
                        'userId'        => getUserId(),
                        'app'           => $_POST['type'],
                        'type'          => $_POST['creditType'],
                        'total'         => $_POST['total'],
                        // 'limitBefore'   => $customer->$_POST['type'],
                        'limitAfter'    => $newLimit,
                        'dateCreation'  => date('Y-m-d H:i:s')
                    );
                
                $change_record = $this->general_model->insertRow('customers_limit_changes', $change_data);
                
                echo json_encode(array( 'result' => true ));
            }else{
                echo json_encode(array( 'result' => false ));
            }
        }else{
            echo json_encode(array( 'result' => false ));
        }
    }
    
    public function sendSmsCode(){
        $customerId = $this->input->post('customerId');
        if(!empty($customerId)){
            $user = $this->general_model->getRowById('users', 'userId', getUserId() );
            if(!empty($user->phone)){
                $userPhone = str_replace("-", "", $user->phone);
                $rand_code = rand(99999, 999999);
                $code = md5($rand_code);
                $sms_data = array(
                        'userId'        => getUserId(),
                        'customerId'    => $customerId,
                        'sms_code'      => $code,
                        'is_verfied'    => 0,
                        'ip_address'    => $_SERVER['REMOTE_ADDR'],
                        'lastUpdate'    => date('Y-m-d H:i:s'),
                        'creationDate'  => date('Y-m-d H:i:s')
                    );
                $addRow = $this->general_model->insertRow('customers_limit_sms', $sms_data);
                $notify = sendSms("SMS Verification Code is: $rand_code", 'Cube', $userPhone);
                echo json_encode(array( 'result' => true ));
            }else{
                echo json_encode(array( 'result' => false ));
            }
        }else{
            echo json_encode(array( 'result' => false ));
        }
    }
    
    public function checkCode(){
        $customerId = $this->input->post('customerId');
        $code       = $this->input->post('code');
        if(!empty($customerId) && !empty($code)){
            $new_code = md5($code);
            $userId = getUserId();
            $check_code = $this->db->query("SELECT * FROM customers_limit_sms WHERE userId = '$userId' AND `customerId` = '$customerId' AND `sms_code` = '$new_code' AND `is_verfied` = 0 ORDER BY `id` DESC ")->row();
            if(!empty($check_code)){
                $updateRow = $this->general_model->updateRowById('customers_limit_sms', 'id', $check_code->id, array('is_verfied' => 1, 'lastUpdate' => date('Y-m-d H:i:s') ));
                echo json_encode(array( 'result' => true ));
            }else{
                echo json_encode(array( 'result' => false ));
            }
        }else{
            echo json_encode(array( 'result' => false ));
        }
    }

    // public function disableCustomer() {

    // }
}






































