<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Customer extends Epos_Template {

    function __construct() {
        parent::__construct();
        $this->load->model('Customer_Model');
        if ($this->Customer_Model->isThisUserAnEposLogger() && (($this->cookies && !empty($this->cookies)) || ($this->session->userdata('group') == 2))) {
            return true;
        } else {
            redirect('user/login/index/' . $this->session->userdata('branch') . '/' . $this->session->userdata('team'));
        }
    }

    public function index($id = null, $name = null, $phone = null, $email = null, $status = null, $city = null, $area = null) {
        $data['branch'] = $this->Customer_Model->get_single('branch', array('id' => $this->session->userdata('branch')))->row_array();
        $region = $this->Customer_Model->get_single('lregion', array('title' => $data['branch']['address_region']))->row();//->id;
        if(!empty($region)){
            $region =$region->id;
        }else{
             $region=0;
        }
        
        $data['branchAdjacentCities'] = $this->Customer_Model->get_list('lcity', array('region' => $region))->result();
        $data['customerOptions'] = $this->Customer_Model->get_list('customer', array('branch' => $this->session->userdata('branch')))->result();
        $data['refresh'] = base_url(uri_string());
        $data['customers'] = $this->Customer_Model->getCustomer($id, $name, $phone, $email, $status, $city, $area)->result();
        $data['filter'] = array(
            'name' => $name ? $name : '',
            'phone' => $phone ? $phone : '',
            'email' => $email ? $phone : '',
            'status' => $status ? $status : '',
            'city' => $city ? $city : '',
            'area' => $area ? $area : '',
        );
        $this->load->view('customer/index', $data, false);
    }

    public function add($id = null) {
        $data['refresh'] = base_url(uri_string());
        $data['branch'] = $this->Customer_Model->get_single('branch', array('id' => $this->session->userdata('branch')))->row_array();
        $regionObj = $this->Customer_Model->get_single('lregion', array('title' => $data['branch']['address_region']))->row();
        $region = !empty($regionObj) ? $regionObj->id : 0;
        $cityObj = $this->Customer_Model->get_single('lcity', array('title' => $data['branch']['address_city']))->row();
        $city = !empty($cityObj) ? $cityObj->id : 0;
        $data['thisCustomer'] = array();
        if ($id) {
            $data['thisCustomer'] = $this->Customer_Model->getCustomer($id, 0, 0, 0, 0, 0, 0)->row_array();
        }
        $data['branchAdjacentCities'] = $this->Customer_Model->get_list('lcity', array('region' => $region))->result();
        $data['branchAdjacentAreas'] = $this->Customer_Model->get_list('larea', array('city' => $city))->result();
        $this->load->view('customer/add', $data, false);
    }

    public function checkme() {
        $column = $this->input->post('column');
        $value = $this->input->post('value');
        $update = $this->input->post('update');
        $result = $this->Customer_Model->checkme($column, $value, $update);
        if ($result) {
            echo json_encode(sprintf($this->lang->line('item_already_taken'), $value));
        } else {
            echo json_encode(true);
        }
    }

    public function save() {
        $data = $this->preparePostedData();
        $insert_id = null;
        $uploadStatus = true;
        $uploadErrorMessage = null;
        $customerInfo = array(
            'name' => $this->input->post('name'),
            'gender' => $this->input->post('gender'),
            'email' => $this->input->post('email'),
            'phone' => $this->input->post('phone'),
            'username' => $this->input->post('username'),
            'password' => md5($this->input->post('password')),
            'status' => $this->input->post('status'),
            'branch' => $this->session->userdata('branch')
        );
        $customerInfoAddress = array(
            'country' => $this->input->post('country'),
            'region' => $this->input->post('region'),
            'city' => $this->input->post('city'),
            'area' => $this->input->post('area'),
            'postcode' => $this->input->post('postcode'),
            'sector' => $this->input->post('sector'),
            'street' => $this->input->post('street'),
            'building' => $this->input->post('building'),
            'floor' => $this->input->post('floor'),
            'apartment' => $this->input->post('apartment'),
            'branch' => $this->session->userdata('branch'),
            'type' => 'primary'
        );

        if (!empty($_FILES['photo'])) {
            $config = array('upload_path' => './uploads/customer', 'allowed_types' => 'gif|jpg|png|jpeg', 'max_size' => '1000', 'max_width' => '650', 'max_height' => '450', 'overwrite' => true);
            $uploadStatus = $this->uploadimage($config, 'photo');
            $uploadErrorMessage = $uploadStatus ? null : $this->upload->display_errors();
            $upload_data = $this->upload->data();
            if ($uploadStatus && !empty($upload_data['orig_name'])) {
                $customerInfo['photo'] = $upload_data['raw_name'] . $upload_data['file_ext'];
            }
        }
        if (!isset($data['id']) || $data['id'] == NULL) {
            $data['branch'] = $this->session->userdata('branch');
            $insert_id = $this->Customer_Model->saveCustomer($customerInfo, NULL);
            if ($insert_id) {
                $customerInfoAddress['cid'] = $insert_id;
                $this->db->insert('customer_address', $customerInfoAddress);
                $activity = array(
                    'activity' => ucfirst($this->session->userdata('name')) . ' has created a customer #' . $customerInfo['name']
                );
                $this->Customer_Model->posactivity($activity);
            }
        } else {
            $id = $data['id'];
            unset($data['id']);
            $insert_id = $this->Customer_Model->saveCustomer($customerInfo, $id);
            if ($insert_id) {
                $this->db->update('customer_address', $customerInfoAddress, array('cid' => $insert_id, 'type' => 'primary', 'branch' => $this->session->userdata('branch')));
                $activity = array(
                    'activity' => ucfirst($this->session->userdata('name')) . ' has updated customer #' . $customerInfo['name']
                );
                $this->Customer_Model->posactivity($activity);
            }
        }
        $message = $insert_id ? $this->lang->line('data_saved_successfully') : $this->lang->line('data_saving_failed');
        echo json_encode(array('status' => $insert_id, 'message' => $message, 'id' => $insert_id));
    }

    public function removeCustomerPhoto($id) {
        $data = $this->input->post();
        $status = checkfile($data['path'], $data['image']);
        if ($status) {
            $result = $this->Customer_Model->saveCustomer(array('photo' => ''), $id);
            unlink(realpath($data['path'] . $data['image']));
            if (!checkfile($data['path'], $data['image']) && $result) {
                $activity = array(
                    'activity' => ucfirst($this->session->userdata('name')) . ' has deleted a customer #' . $id . ' photo'
                );
                $this->Customer_Model->posactivity($activity);
                echo json_encode(array('status' => $result, 'id' => $id, 'message' => $this->lang->line('delete_success')));
            } else {
                echo json_encode(array('status' => false, 'message' => $this->lang->line('delete_failed')));
            }
        }
    }

}
