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

class ImportData extends CI_Controller {

	public function __construct() {
		parent::__construct();
		date_default_timezone_set("Asia/Kolkata");
		$this->load->model('Import_model');
		if(!$this->session->userdata('logged_in')) {
			redirect(base_url('Login'));
		}
 	}

    public function import_data(){
        $template['page'] = 'Import/importdata';
        $template['menu'] = 'Import Data';
        $template['smenu'] = 'Import Data';
        $template['pTitle'] = "Import Data";
        $template['import_id'] = '';
        $template['pDescription'] = "Import Data";
        $this->load->view('template',$template);
    }

    public function importCsvData(){
        if(!isset($_POST['import_id']) || empty($_POST['import_id'])){
            $flashMsg = array('message'=>'Select an Import Type','class'=>'error');
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('ImportData/import_data'));
        }
        if(!isset($_FILES) || empty($_FILES)){
            $flashMsg = array('message'=>'Select a File to Upload','class'=>'error');
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('ImportData/import_data'));
        }
        if($_POST['import_id'] == '1'){
            $this->addMechanics($_FILES);
        }else if($_POST['import_id'] == '2'){
            $this->addCustomers($_FILES);
        }else if($_POST['import_id'] == '3'){
            $this->addProduct($_FILES);
        }
    }

    public function addMechanics($files =array()){
        $this->load->model('Mechanic_model');
        if(isset($files) && !empty($files)){
            $filename = $files["file"]["tmp_name"];
            if(pathinfo($files["file"]['name'], PATHINFO_EXTENSION) == "csv"){
                $count = 0;
                $respMsg = '';
                $respError = 0;
                $respSuccess = 0;
                $file = fopen($filename, "r");
                while (($mechData = fgetcsv($file, 10000, ",")) !== FALSE){
                    $err = 0;
                    $count++;
                    $errMsg = '';
                    $new = array();
                    if($count == 1){
                        continue;
                    }
                    if($err == 0 && (!isset($mechData[0]) || empty($mechData[0]))){
                        $err = 1;
                        $errMsg = 'Provide a First Name';
                    }else if($err == 0 && (!isset($mechData[1]) || empty($mechData[1]))){
                        $err = 1;
                        $errMsg = 'Provide a Last Name';
                    }else if($err == 0 && (!isset($mechData[2]) || empty($mechData[2]))){
                        $err = 1;
                        $errMsg = 'Provide a Password';
                    }else if($err == 0 && (!isset($mechData[3]) || empty($mechData[3]))){
                        $err = 1;
                        $errMsg = 'Provide a Phone Number';
                    }else if($err == 0 && (!isset($mechData[4]) || empty($mechData[4]))){
                        $err = 1;
                        $errMsg = 'Provide an Email ID';
                    }else if($err == 0 && (!isset($mechData[5]) || empty($mechData[5]))){
                        $err = 1;
                        $errMsg = 'Provide a Display Name';
                    }else if($err == 0 && (!isset($mechData[6]) || empty($mechData[6]))){
                        $err = 1;
                        $errMsg = 'Provide a city';
                    }else if($err == 0 && (!isset($mechData[7]) || empty($mechData[7]))){
                        $err = 1;
                        $errMsg = 'Provide a state';
                    }else if($err == 0 && (!isset($mechData[8]) || empty($mechData[8]))){
                        $err = 1;
                        $errMsg = 'Provide an address';
                    }else if($err == 0 && (!isset($mechData[9]) || empty($mechData[9]))){
                        $err = 1;
                        $errMsg = 'Provide a Functional Area';
                    }else if($err == 0 && (!isset($mechData[10]) || empty($mechData[10]))){
                        $err = 1;
                        $errMsg = 'Provide Work Start Time';
                    }else if($err == 0 && (!isset($mechData[11]) || empty($mechData[11]))){
                        $err = 1;
                        $errMsg = 'Provide Work End Time';
                    }else if($err == 0 && (!isset($mechData[12]) || empty($mechData[12]))){
                        $err = 1;
                        $errMsg = 'Provide a Username';
                    }else if($err == 0 && ($mechData[10] >= $mechData[11])){
                        $err = 1;
                        $errMsg = 'Provide proper Working Hours';
                    }
                    $fnLocation = getLocationLatLng($mechData[9]);
                    if(empty($fnLocation)){
                        $err = 1;
                        $errMsg = 'Provide a Valid Functional Area';
                    }
                    if($err == 1){
                        $respError++;
                        $respMsg .= '<br>ERROR : Row-'.($count-1).', '.$errMsg;
                        continue;
                    }
                    $mechData[2] = md5($mechData[2]);
                    $new = array(
                        'first_name'=>$mechData[0],
                        'last_name'=>$mechData[1],
                        'password'=>$mechData[2],
                        'phone'=>$mechData[3],
                        'email_id'=>$mechData[4],
                        'display_name'=>$mechData[5],
                        'city'=>$mechData[6],
                        'state'=>$mechData[7],
                        'address'=>$mechData[8],
                        'location'=>$mechData[9],
                        'start_time'=>$mechData[10],
                        'end_time'=>$mechData[11],
                        'username'=>$mechData[12],
                        'location_lat'=>$fnLocation['lat'],
                        'location_lng'=>$fnLocation['lng'],
                        'licence'=>$fnLocation['lng'],
                        'licence_number'=>'',
                        'licence_exp_date'=>'',
                        'profile_image'=>'',
                        'shop_id'=>0
                    );
                    $status = $this->Mechanic_model->addMechanic($new);
                    if($status == '1'){
                        $respSuccess++;
                    } else if($status == 2){
                        $respError++;
                        $respMsg .= '<br>ERROR : Row-'.($count-1).', Email ID already exist.';
                    } else if($status == 3){
                        $respError++;
                        $respMsg .= '<br>ERROR : Row-'.($count-1).', Phone Number already exist.';
                    } else if($status == 4){
                        $respError++;
                        $respMsg .= '<br>ERROR : Row-'.($count-1).', User Name already exist.';
                    } else {
                        $respError++;
                        $respMsg .= '<br>ERROR : Row-'.($count-1).', Data Error.';
                    }
                }
                if($count > 0){
                    $respMsg = "Successfully Uploaded File with, ".
                                 $respSuccess.": Success & ".$respError.": Errors.<br>".$respMsg;

                    $flashMsg = array('message'=>$respMsg,'class'=>($respError==$count-1)?'error':'success');
                    $this->session->set_flashdata('message', $flashMsg);
                    redirect(base_url('ImportData/import_data'));
                }
            } else {
                $flashMsg = array('message'=>'Invalid file format','class'=>'error');
                $this->session->set_flashdata('message', $flashMsg);
                redirect(base_url('ImportData/import_data'));
            }
        }
    }

    public function addCustomers($files=array()){
        $this->load->model('Customer_model');
        if(isset($files) && !empty($files)){
            $filename=$files["file"]["tmp_name"];
            if(pathinfo($files["file"]['name'], PATHINFO_EXTENSION) =="csv"){
                $count = 0;
                $respMsg = '';
                $respError = 0;
                $respSuccess = 0;
                $file = fopen($filename, "r");
                while (($custData = fgetcsv($file, 10000, ",")) !== FALSE){
                    $err = 0;
                    $count++;
                    $errMsg = '';
                    $new = array();
                    if($count == 1){
                        continue;
                    }
                    if($err == 0 && (!isset($custData[0]) || empty($custData[0]))){
                        $err = 1;
                        $errMsg = 'Provide a First Name';
                    }
                    else if($err == 0 && (!isset($custData[1]) || empty($custData[1]))){
                        $err = 1;
                        $errMsg = 'Provide a Last Name';
                    }
                    else if($err == 0 && (!isset($custData[3]) || empty($custData[3]))){
                        $err = 1;
                        $errMsg = 'Provide a Phone Number';
                    }
                    else if($err == 0 && (!isset($custData[4]) || empty($custData[5]))){
                        $err = 1;
                        $errMsg = 'Provide an Email ID';
                    } 
                    else if($err == 0 && (!isset($custData[6]) || empty($custData[6]))){
                        $err = 1;
                        $errMsg = 'Provide a Password';
                    }
                    else if($err == 0 && (!isset($custData[2]) || empty($custData[2]))){
                        $err = 1;
                        $errMsg = 'Provide Date Of Birth';
                    }
                    else if($err == 0 && (!isset($custData[5]) || empty($custData[5]))){
                        $err = 1;
                        $errMsg = 'Provide an Address';
                    }
                    if($err == 1){
                        $respError++;
                        $respMsg .= '<br>ERROR : Row-'.($count-1).', '.$errMsg;
                        continue;
                    }
                    $custData[6] = md5($custData[6]);
                    $new = array(
                        'first_name'=>$custData[0],
                        'last_name'=>$custData[1],
                        'password'=>$custData[6],
                        'phone'=>$custData[3],
                        'email'=>$custData[4],
                        'address'=>$custData[5],
                        'date_of_birth'=>$custData[2],
                        'profile_image'=>'',
                    );
                    $status = $this->Customer_model->createCustomer($new);
                    if($status == 1){
                        $respSuccess++;
                    }else if($status == 2){
                        $respError++;
                        $respMsg .= '<br>ERROR : Row-'.($count-1).', Email ID already in use.';
                    }else if($status == 3){
                        $respError++;
                        $respMsg .= '<br>ERROR : Row-'.($count-1).', Phone Number already in use. ';
                    }
                }
                if($count > 0){
                    $respMsg = "Successfully Uploaded File with, ".
                                 $respSuccess.": Success & ".$respError.": Errors.<br>".$respMsg;
                    $flashMsg = array('message'=>$respMsg,'class'=>($respError==$count-1)?'error':'success');
                    $this->session->set_flashdata('message', $flashMsg);
                    redirect(base_url('ImportData/import_data'));
                }
            }else {
                $flashMsg = array('message'=>'Invalid file format','class'=>'error');
                $this->session->set_flashdata('message', $flashMsg);
                redirect(base_url('ImportData/import_data'));
            }
        }
    }

    public function addProduct($files =array()){
        if(isset($files) && !empty($files)){
            $filename=$files["file"]["tmp_name"];
            if(pathinfo($files["file"]['name'], PATHINFO_EXTENSION) =="csv"){
                $count = 0;
                $respMsg = '';
                $respError = 0;
                $respSuccess = 0;
                $file = fopen($filename, "r");
                while (($prdData = fgetcsv($file, 10000, ",")) !== FALSE){
                    $err = 0;
                    $count++;
                    $errMsg = '';
                    $new = array();
                    if($count == 1){
                        continue;
                    }
                    if($err == 0 && (!isset($prdData[0]) || empty($prdData[0]))){
                        $err = 1;
                        $errMsg = 'Provide a Product Name';
                    }
                    else if($err == 0 && (!isset($prdData[1]) || empty($prdData[1]))){
                        $err = 1;
                        $errMsg = 'Provide a Brand Name';
                    }
                    else if($err == 0 && (!isset($prdData[2]) || empty($prdData[2]))){
                        $err = 1;
                        $errMsg = 'Provide a Part Id';
                    }
                    else if($err == 0 && (!isset($prdData[3]) || empty($prdData[3]))){
                        $err = 1;
                        $errMsg = 'Provide a short Description';
                    } 
                    else if($err == 0 && (!isset($prdData[4]) || empty($prdData[4]))){
                        $err = 1;
                        $errMsg = 'Provide an Amount';
                    }
                    else if($err == 0 && (!isset($prdData[5]) || empty($prdData[5]))){
                        $err = 1;
                        $errMsg = 'Provide a Year';
                    }
                    else if($err == 0 && (!isset($prdData[6]) || empty($prdData[6]))){
                        $err = 1;
                        $errMsg = 'Provide a Vehicle Brand';
                    }
                    else if($err == 0 && (!isset($prdData[7]) || empty($prdData[7]))){
                        $err = 1;
                        $errMsg = 'Provide a Vehicle Model';
                    }
                    else if($err == 0 && (!isset($prdData[8]) || empty($prdData[8]))){
                        $err = 1;
                        $errMsg = 'Provide a Product Description';
                    }
                    else if($err == 0 && (!isset($prdData[9]) || empty($prdData[9]))){
                        $err = 1;
                        $errMsg = 'About Produt';
                    }
                    if($err == 1){
                        $respError++;
                        $respMsg .= '<br>ERROR : Row-'.($count-1).', '.$errMsg;
                        continue;
                    }
                    $brand_id = $this->Import_model->checkBrand($prdData[1]);
                    $cardetail_id = $this->Import_model->checkCardetails($prdData[5],$prdData[6],$prdData[7]);
                    $new = array(
                        'product_name'=>$prdData[0],
                        'brand_id'=>$brand_id,
                        'part_id'=>$prdData[2],
                        'short_description'=>$prdData[3],
                        'amount'=>$prdData[4],
                        'cardetail_id'=>$cardetail_id,
                        'description'=>$prdData[8],
                        'about'=>$prdData[9]
                    );
                    $status = $this->Import_model->addProduct($new);
                    if($status == 1){
                        $respSuccess++;
                    }else{
                        $respError++;
                        $respMsg .= '<br>ERROR : Row-'.($count-1).', Something Went Wrong.';
                    }
                }
                if($count > 0){
                    $respMsg = "Successfully Uploaded File with, ".
                                 $respSuccess.": Success & ".$respError.": Errors.<br>".$respMsg;
                    $flashMsg = array('message'=>$respMsg,'class'=>($respError==$count-1)?'error':'success');
                    $this->session->set_flashdata('message', $flashMsg);
                    redirect(base_url('ImportData/import_data'));
                }
            }else {
                $flashMsg = array('message'=>'Invalid file format','class'=>'error');
                $this->session->set_flashdata('message', $flashMsg);
                redirect(base_url('ImportData/import_data'));
            }
        }
    }
}

