<?php

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

class Location extends Epos_Template {

    function __construct() {
        parent::__construct();
        $this->load->model('Location_Model');
        if ($this->Location_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($country = null, $region = null, $city = null, $area = null) {
        $branch = $this->Location_Model->get_single('branch', array('id' => $this->session->userdata('branch')))->row();
        if (!empty($branch) && $country == null && $region == null && $area == null) {
            $countryObj = $this->Location_Model->get_single('lcountry', array('title' => $branch->address_country))->row();
            $country = !empty($countryObj) ? $countryObj->id : 0;
            $regionObj = $this->Location_Model->get_single('lregion', array('title' => $branch->address_region))->row();
            $region = !empty($regionObj) ? $regionObj->id : 0;
            $cityObj = $this->Location_Model->get_single('lcity', array('title' => $branch->address_city))->row();
            $city = !empty($cityObj) ? $cityObj->id : 0;
            $areaObj = $this->Location_Model->get_single('larea', array('title' => $branch->address_area))->row();
            $area = !empty($areaObj) ? $areaObj->id : 0;
        }
        $data = array();
        $data['countries'] = $this->Location_Model->get_list('lcountry', null, null, null, 0, 'position', 'ASC')->result();
        if (!empty($data['countries'])) {
            if ($country != null && (int) $country > 0) {
                $data['loaded_country'] = $this->Location_Model->get_single('lcountry', array('id' => trim($country)))->row_array();
                $data['loaded_country_region'] = $this->Location_Model->get_list('lregion', array('country' => trim($country)), null, null, 0, 'position', 'ASC')->result();
            } else {
                $data['loaded_country'] = objectToArray($data['countries'][0]);
                $data['loaded_country_region'] = $this->Location_Model->get_list('lregion', array('country' => trim($data['loaded_country']['id'])), null, null, 0, 'position', 'ASC')->result();
            }
            if ($region !== null && (int) $region > 0) {
                $data['loaded_region_cities'] = $this->Location_Model->get_list('lcity', array('region' => $region), null, null, 0, 'position', 'ASC')->result();
                $data['loaded_region'] = $this->Location_Model->get_single('lregion', array('id' => trim($region)))->row_array();
            } else {
                if (!empty($data['loaded_country_region'][0])) {
                    $data['loaded_region_cities'] = $this->Location_Model->get_list('lcity', array('region' => $data['loaded_country_region'][0]->id), null, null, 0, 'position', 'ASC')->result();
                    $data['loaded_region'] = objectToArray($data['loaded_country_region'][0]);
                } else {
                    $data['loaded_region'] = array();
                }
            }
            if ($city !== null && (int) $city > 0) {
                $data['loaded_city_areas'] = $this->Location_Model->get_list('larea', array('city' => trim($city)), null, null, 0, 'title', 'ASC')->result();
                $data['loaded_city'] = $this->Location_Model->get_single('lcity', array('id' => trim($city)))->row_array();
            } else {
                if (!empty($data['loaded_region_cities'][0])) {
                    $data['loaded_city_areas'] = $this->Location_Model->get_list('larea', array('city' => trim($data['loaded_region_cities'][0]->id)), null, null, 0, 'position', 'ASC')->result();
                    $data['loaded_city'] = objectToArray($data['loaded_region_cities'][0]);
                } else {
                    $data['loaded_city'] = array();
                }
            }
            if ($area != null && (int) $area > 0) {
                $data['loaded_area'] = $this->Location_Model->get_single('larea', array('id' => trim($area)))->row_array();
            } else {
                if (!empty($data['loaded_city_areas'][0])) {
                    $data['loaded_area'] = objectToArray($data['loaded_city_areas'][0]);
                } else {
                    $data['loaded_area'] = array();
                }
            }
        }
        $data['refresh'] = base_url(uri_string());
        $this->load->view('settings/location/index', $data, false);
    }

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

    public function save_country() {
        $data = $this->preparePostedData();
        $insert_id = null;
        $result = true;
        if (!isset($data['id']) || $data['id'] == NULL) {
            $insert_id = $this->Location_Model->save_country($data, NULL);
            $result = $insert_id ? $this->Location_Model->save_country(array('position' => $insert_id), $insert_id) : false;
        } else {
            $id = $data['id'];
            unset($data['id']);
            $insert_id = $this->Location_Model->save_country($data, $id);
        }
        $message = $insert_id && $result ? $this->lang->line('data_saved_successfully') : $this->lang->line('data_saving_failed');
        $activity = array(
            'activity' => ucfirst($this->session->userdata('name')) . ' has added/updated country'
        );
        $this->Location_Model->posactivity($activity);
        echo json_encode(array('status' => $insert_id && $result, 'message' => $message, 'country' => $insert_id));
    }

    public function sortcountry() {
        $func = $this->input->post('func');
        $id = $this->input->post('id');
        $position = $this->input->post('position');
        $newPosition = $position;
        if ($func == 'up') {
            $newPosition = $position + 1;
        }
        if ($func == 'down' && $position > 1) {
            $newPosition = $position - 1;
        }
        $MinMax = $this->Location_Model->get_min_max('lcountry', 'position')->row();
        if (true === in_array($newPosition, range($MinMax->min, $MinMax->max))) {
            $s1 = $this->db->update('lcountry', array('position' => $position), array('position' => $newPosition));
            $s2 = $this->db->update('lcountry', array('position' => $newPosition), array('id' => $id));
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has resorted country'
            );
            $this->Location_Model->posactivity($activity);
            echo json_encode(array('status' => $s1 && $s2));
        }
    }

    public function save_region($country = null) {
        if ($country != null && $this->Location_Model->exists('lcountry', 'id', trim($country))) {
            $data = $this->preparePostedData();
            $data['country'] = trim($country);
            $insert_id = null;
            $result = true;
            if (!isset($data['id']) || $data['id'] == NULL) {
                $insert_id = $this->Location_Model->save_region($data, NULL);
                $result = $insert_id ? $this->Location_Model->save_region(array('position' => $insert_id), $insert_id) : false;
            } else {
                $id = $data['id'];
                unset($data['id']);
                $insert_id = $this->Location_Model->save_region($data, $id);
            }
            $message = $insert_id && $result ? $this->lang->line('data_saved_successfully') : $this->lang->line('data_saving_failed');
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has added/updated region'
            );
            $this->Location_Model->posactivity($activity);
            echo json_encode(array('status' => $insert_id && $result, 'message' => $message, 'country' => trim($country), 'region' => $insert_id));
        }
    }

    public function checkregion() {
        $column = $this->input->post('column');
        $value = $this->input->post('value');
        $old = $this->input->post('old');
        $update = $this->input->post('update');
        $country = $this->input->post('country');
        $result = null;
        $status = true;
        if ($update == 'yes') {
            if (trim(strtolower($old)) === trim(strtolower($value))) {
                $status = false;
            } else {
                $this->db->where($column, $value);
                $this->db->where('country', $country);
                $result = $this->db->count_all_results('lregion') > 0;
            }
        } else {
            $this->db->where($column, $value);
            $this->db->where('country', $country);
            $result = $this->db->count_all_results('lregion') > 0;
        }

        if ($result) {
            echo json_encode(sprintf($this->lang->line('item_already_taken'), $value));
        } else {
            echo json_encode(true);
        }
    }

    public function sortregion() {
        $func = $this->input->post('func');
        $id = $this->input->post('id');
        $position = $this->input->post('position');
        $newPosition = $position;
        if ($func == 'up') {
            $newPosition = $position + 1;
        }
        if ($func == 'down' && $position > 1) {
            $newPosition = $position - 1;
        }
        $MinMax = $this->Location_Model->get_min_max('lregion', 'position')->row();
        if (true === in_array($newPosition, range($MinMax->min, $MinMax->max))) {
            $s1 = $this->db->update('lregion', array('position' => $position), array('position' => $newPosition));
            $s2 = $this->db->update('lregion', array('position' => $newPosition), array('id' => $id));
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has resorted region'
            );
            $this->Location_Model->posactivity($activity);
            echo json_encode(array('status' => $s1 && $s2));
        }
    }

    public function checkcity() {
        $column = $this->input->post('column');
        $value = $this->input->post('value');
        $old = $this->input->post('old');
        $update = $this->input->post('update');
        $region = $this->input->post('region');
        $result = null;
        $status = true;
        if ($update == 'yes') {
            if (trim(strtolower($old)) === trim(strtolower($value))) {
                $status = false;
            } else {
                $this->db->where($column, $value);
                $this->db->where('region', $region);
                $result = $this->db->count_all_results('lcity') > 0;
            }
        } else {
            $this->db->where($column, $value);
            $this->db->where('region', $region);
            $result = $this->db->count_all_results('lcity') > 0;
        }

        if ($result) {
            echo json_encode(sprintf($this->lang->line('item_already_taken'), $value));
        } else {
            echo json_encode(true);
        }
    }

    public function save_city($country = null, $region = null) {
        if ($region != null && $this->Location_Model->exists('lregion', 'id', trim($region))) {
            $data = $this->preparePostedData();
            $data['region'] = trim($region);
            $insert_id = null;
            $result = true;
            if (!isset($data['id']) || $data['id'] == NULL) {
                $insert_id = $this->Location_Model->save_city($data, NULL);
                $result = $insert_id ? $this->Location_Model->save_city(array('position' => $insert_id), $insert_id) : false;
            } else {
                $id = $data['id'];
                unset($data['id']);
                $insert_id = $this->Location_Model->save_city($data, $id);
            }
            $message = $insert_id && $result ? $this->lang->line('data_saved_successfully') : $this->lang->line('data_saving_failed');
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has added/updated city'
            );
            $this->Location_Model->posactivity($activity);
            echo json_encode(array('status' => $insert_id && $result, 'message' => $message, 'country' => trim($country), 'region' => $region, 'city' => $insert_id));
        }
    }

    public function sortcity() {
        $func = $this->input->post('func');
        $id = $this->input->post('id');
        $position = $this->input->post('position');
        $newPosition = $position;
        if ($func == 'up') {
            $newPosition = $position + 1;
        }
        if ($func == 'down' && $position > 1) {
            $newPosition = $position - 1;
        }
        $MinMax = $this->Location_Model->get_min_max('lcity', 'position')->row();
        if (true === in_array($newPosition, range($MinMax->min, $MinMax->max))) {
            $s1 = $this->db->update('lcity', array('position' => $position), array('position' => $newPosition));
            $s2 = $this->db->update('lcity', array('position' => $newPosition), array('id' => $id));
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has resorted city'
            );
            $this->Location_Model->posactivity($activity);
            echo json_encode(array('status' => $s1 && $s2));
        }
    }

    public function checkarea() {
        $column = $this->input->post('column');
        $value = $this->input->post('value');
        $old = $this->input->post('old');
        $update = $this->input->post('update');
        $city = $this->input->post('city');
        $result = null;
        $status = true;
        if ($update == 'yes') {
            if (trim(strtolower($old)) == trim(strtolower($value))) {
                $status = false;
            } else {
                $this->db->where($column, $value);
                $this->db->where('city', $city);
                $result = $this->db->count_all_results('larea') > 0;
            }
        } else {
            $this->db->where($column, $value);
            $this->db->where('city', $city);
            $result = $this->db->count_all_results('larea') > 0;
        }

        if ($result) {
            echo json_encode(sprintf($this->lang->line('item_already_taken'), $value));
        } else {
            echo json_encode(true);
        }
    }

    public function save_area($country = null, $region = null, $city = null) {
        if ($city != null && $this->Location_Model->exists('lcity', 'id', trim($city))) {
            $data = $this->preparePostedData();
            $data['city'] = trim($city);
            $insert_id = null;
            $result = true;
            if (!isset($data['id']) || $data['id'] == NULL) {
                $insert_id = $this->Location_Model->save_area($data, NULL);
                $result = $insert_id ? $this->Location_Model->save_area(array('position' => $insert_id), $insert_id) : false;
            } else {
                $id = $data['id'];
                unset($data['id']);
                $insert_id = $this->Location_Model->save_area($data, $id);
            }
            $message = $insert_id && $result ? $this->lang->line('data_saved_successfully') : $this->lang->line('data_saving_failed');
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has added/updated area'
            );
            $this->Location_Model->posactivity($activity);
            echo json_encode(array('status' => $insert_id && $result, 'message' => $message, 'country' => trim($country), 'region' => $region, 'city' => $city));
        }
    }

    public function sortarea() {
        $func = $this->input->post('func');
        $id = $this->input->post('id');
        $position = $this->input->post('position');
        $newPosition = $position;
        if ($func == 'up') {
            $newPosition = $position + 1;
        }
        if ($func == 'down' && $position > 1) {
            $newPosition = $position - 1;
        }
        $MinMax = $this->Location_Model->get_min_max('larea', 'position')->row();
        if (true === in_array($newPosition, range($MinMax->min, $MinMax->max))) {
            $s1 = $this->db->update('larea', array('position' => $position), array('position' => $newPosition));
            $s2 = $this->db->update('larea', array('position' => $newPosition), array('id' => $id));
            $activity = array(
                'activity' => ucfirst($this->session->userdata('name')) . ' has added/updated area'
            );
            $this->Location_Model->posactivity($activity);
            echo json_encode(array('status' => $s1 && $s2));
        }
    }

    public function dooraddress($city = null, $area = null, $postcode = null) {
        $data['cities'] = $this->Location_Model->get_list('lcity')->result();
        //-------------------------
        $data['areas'] = array();
        if ($city) {
            $data['activeCity'] = $this->Location_Model->get_single('lcity', array('id' => (int) $city))->row_array();
            $data['areas'] = $this->Location_Model->get_list('larea', array('city' => $city))->result();
        } else {
            if (!empty($data['cities'])) {
                $data['activeCity'] = objectToArray($data['cities'][0]);
                $data['areas'] = $this->Location_Model->get_list('larea', array('city' => !empty($data['cities']) ? $data['cities'][0]->id : 0))->result();
            }
        }
        //----------------------------
        $data['postcodes'] = array();
        if ($area) {
            $data['activeArea'] = $this->Location_Model->get_single('larea', array('id' => $area))->row_array();
            $data['postcodes'] = $this->Location_Model->get_list('lpostcode', array('area' => $area), null, null, null, 'title', 'ASC')->result();
        } else {
            $data['activeArea'] = !empty($data['areas'][0]) ? objectToArray($data['areas'][0]) : array();
            $data['postcodes'] = $this->Location_Model->get_list('lpostcode', array('area' => !empty($data['areas']) ? $data['areas'][0]->id : 0), null, null, null, 'title', 'ASC')->result();
        }
        //------------------------
        $data['dooraddress'] = array();
        if ($postcode) {
            $data['activePostcode'] = $activePostcode = $this->Location_Model->get_single('lpostcode', array('id' => (int) $postcode))->row_array();
            $data['dooraddress'] = $this->Location_Model->get_list('ldooraddress', array('postcodeId' => $postcode))->result();
        } else {
            $data['activePostcode'] = $activePostcode = !empty($data['postcodes']) ? objectToArray($data['postcodes'][0]) : array();
            $data['dooraddress'] = $data['dooraddress'] = $this->Location_Model->get_list('ldooraddress', array('postcodeId' => !empty($activePostcode) ? $activePostcode['id'] : 0))->result();
        }
        //-------------------------------
        $data['refresh'] = base_url(uri_string());
        $this->load->view('settings/location/dooraddress', $data, false);
    }

    public function savepostcode($city = null, $area = null) {
        if ((int) $city > 0 && (int) $area > 0) {
            $data = $this->preparePostedData();
            $data['title'] = $title = postcodeFormat($data['title']);
            $doesThisPostcodeExit = $this->db->where(array('title' => $title, 'city' => (int) $city, 'area' => (int) $area))->count_all_results('lpostcode') > 0;
            if ($doesThisPostcodeExit) {
                echo json_encode(array('status' => false, 'message' => sprintf($this->lang->line('item_already_taken'), $title)));
            } else {
                $data['city'] = $city;
                $data['area'] = $area;
                $insert_id = $this->Location_Model->save_postcode($data, NULL);
                if ($insert_id) {
                    $insertedPostcodeObj = $this->Location_Model->get_single('lpostcode', array('id' => $insert_id), array('id', 'title', 'city', 'area'))->row();
                }
                $message = $insert_id ? $this->lang->line('data_saved_successfully') : $this->lang->line('data_saving_failed');
                echo json_encode(array('status' => $insert_id, 'message' => $message, 'city' => trim($data['city']), 'area' => $data['area'], 'postcode' => $insert_id, 'obj' => $insertedPostcodeObj));
            }
        }
    }

    public function savepostcodeDooraddress($city = null, $area = null, $postcode = null) {
        if ((int) $city > 0 && (int) $area > 0 && (int) $postcode > 0) {
            $data = $this->preparePostedData();
            $data['street_number'] = strtoupper($data['street_number']);
            $data['route'] = ucwords($data['route']);
            $data['postal_town'] = ucwords($data['postal_town']);
            $cityObj = $this->Location_Model->get_single('lcity', array('id' => $city))->row();
            $regionObj = $this->Location_Model->get_single('lregion', array('id' => $cityObj->region))->row();
            $countryObj = $this->Location_Model->get_single('lcountry', array('id' => $regionObj->country))->row();
            $data['administrative_area_level_2'] = $cityObj->title;
            $data['administrative_area_level_1'] = $regionObj->title;
            $data['country'] = $countryObj->title;
            $data['postal_code'] = get_title('lpostcode', array('id' => $postcode));
            $data['postcodeId'] = $postcode;
            $doesThisPostcodeExit = $this->db->where($data)->count_all_results('ldooraddress') > 0;
            if ($doesThisPostcodeExit) {
                echo json_encode(array('status' => false, 'message' => sprintf($this->lang->line('item_already_taken'), $data['street_number'] . ', ' . $data['route'] . ' ' . $data['postal_town'] . ', ' . $data['administrative_area_level_2'] . ', ' . $data['postal_code'])));
            } else {
                $insert_id = $this->Location_Model->save_postcodeDooraddress($data, NULL);
                if ($insert_id) {
                    $insertedPostcodeObj = $this->Location_Model->get_single('ldooraddress', array('id' => $insert_id), array('id', 'street_number', 'postal_town', 'route', 'administrative_area_level_2', 'postal_code'))->row();
                }
                $message = $insert_id ? $this->lang->line('data_saved_successfully') : $this->lang->line('data_saving_failed');
                echo json_encode(array('status' => $insert_id, 'message' => $message, 'obj' => $insertedPostcodeObj));
            }
        }
    }

    public function deleteCountryById($id) {
        $resions = $this->Location_Model->get_list('lregion', array('country' => $id))->result();
        if (!empty($resions)) {
            foreach ($resions as $aRegion) {
                $this->deleteRegionById($aRegion->id);
            }
        }
        $status = $this->db->delete('lcountry', array('id' => $id));
        echo json_encode(array('status' => $status));
    }

    public function deleteRegionById($id, $ajax = 'no') {
        $cities = $this->Location_Model->get_list('lcity', array('region' => $id))->result();
        if (!empty($cities)) {
            foreach ($cities as $acity) {
                $this->deleteCityById($acity->id);
            }
        }
        $status = $this->db->delete('lregion', array('id' => $id));
        if ($ajax == 'yes') {
            echo json_encode(array('status' => $status));
        }
    }

    public function deleteCityById($id, $ajax = 'no') {
        $areas = $this->Location_Model->get_list('larea', array('city' => $id))->result();
        if (!empty($areas)) {
            foreach ($areas as $area) {
                $this->deleteAreaById($area->id);
            }
        }
        $status = $this->db->delete('lcity', array('id' => $id));
        if ($ajax == 'yes') {
            echo json_encode(array('status' => $status));
        }
    }

    public function deleteAreaById($id, $ajax = 'no') {
        $postcodes = $this->Location_Model->get_list('lpostcode', array('area' => $id))->result();
        if (!empty($postcodes)) {
            foreach ($postcodes as $apostcode) {
                $this->deletePostcodeById($apostcode->id);
            }
        }
        $status = $this->db->delete('larea', array('id' => $id));
        if ($ajax == 'yes') {
            echo json_encode(array('status' => $status));
        }
    }

    public function deletePostcodeById($id, $ajax = 'no') {
        $doorAddress = $this->Location_Model->get_list('ldooraddress', array('postcodeId' => $id))->result();
        if (!empty($doorAddress)) {
            foreach ($doorAddress as $adoor) {
                $this->deleteDoorAddressById($adoor->id);
            }
        }
        $status = $this->db->delete('lpostcode', array('id' => $id));
        if ($ajax == 'yes') {
            echo json_encode(array('status' => $status));
        }
    }

    public function deleteDoorAddressById($id, $ajax = 'no') {
        $status = $this->db->delete('ldooraddress', array('id' => $id));
        if ($ajax == 'yes') {
            echo json_encode(array('status' => $status));
        }
    }

    function deleteDoorAddress() {
        $id = $this->input->post('id');
        $status = $this->db->delete('ldooraddress', array('id' => $id));
        echo json_encode(array('status' => $status));
    }

}
