middleware('auth'); $this->_service = 'contact'; $this->_module = 'contact'; $this->_viewname = 'contact'; $this->_title = 'Contact'; $this->_base_url = '/contact'; $this->_listtype = 'ajaxlist'; } public function list(Request $request) { $fields = $this->get_list_fields(); //echo $this->_listtype; exit; return $this->view($this->_listtype)->with([ 'title' => $this->_title, 'fields' => $fields, 'base_url' => $this->_base_url, //'items' => $response->data->items, 'buttons' => $this->get_list_buttons() ]); } public function aggrid(Request $request) { $fields = [ //'actions' => ['title' => 'Actions', 'buttons' => [ 'edit', 'delete' ] ], 'name' => ['title' => 'Name', 'type' => 'text', 'editable' => false], 'msl_code' => ['title' => 'MSL Code', 'type' => 'text', 'editable' => false], 'position_name' => ['title' => 'Position', 'type' => 'text', 'editable' => false], 'user_name' => ['title' => 'Rep Name', 'type' => 'text', 'editable' => false], 'status' => ['title' => 'Status', 'type' => 'select', 'editable' => false], ]; $response = LambdaRequest::signedrequest('get', $this->_service, 'contactattribute/get_all'); foreach($response->data->items as $item) { $fields[$item->code] = ['title' => $item->attribute, 'type' => $item->type, 'editable' => $item->editable == 'yes' ? true : false, 'options' => $item->options ]; } //echo '
'; print_r($fields); exit;

        //echo $this->_listtype; exit;
        return $this->view('aggrid')->with([
            'title' => $this->_title,
            'fields' => $fields,
            'base_url' => $this->_base_url,
            //'items' => $response->data->items,
            'buttons' => $this->get_list_buttons()
        ]);
    }

    public function aggridajaxlist(Request $request) {
        $params = $request->input();
        $search = [];
        $fields = $this->get_list_fields();
        $response = LambdaRequest::signedrequest('get', $this->_service, $this->_module.'/get_all', ['start' => 0, 'length' => 100, 'search' => json_encode($search), 'keyword' => '' ]);

        $users = [];
        foreach($response->data->items as $item) {
            $user = [];
            if(isset($item->id)) {
                $user['id'] = $item->id;
            }
            foreach($fields as $field => $props){
                if($field != 'actions') {
                    switch($props['type']){
                        case('image'):
                            $user[$field] = ' ';
                            break;
                        case('text'):
                        case('select'):
                            $user[$field] = isset($item->{$field}) ? $item->{$field} : '';
                            break;
                        case('date'):
                            $user[$field] = date("d M Y", strtotime($item->{$field}));
                            break;
                    }
                } else {
                    // $user['actions'] = [];
                    // foreach($props['buttons'] as $key => $button){
                    //     switch($button) {
                    //         case 'edit':
                    //             $user['actions'][] = ['link' => '/edit?id='.$item->id, 'icon' => 'square-edit-outline text-warning'];
                    //             break;
                    //         case 'delete':
                    //             $user['actions'][] = ['link' => '/delete?id='.$item->id, 'icon' => 'delete text-danger'];
                    //             break;
                    //         default:
                    //             $querystring = $button['querystring'];
                    //             foreach((array)$item as $k => $v) {
                    //                 if(strpos($querystring,'{'.strtoupper($k).'}') !== false)
                    //                     $querystring = str_replace('{'.strtoupper($k).'}', $v, $querystring);
                    //             }
                    //             $user['actions'][] = ['link' => '/'.$key.'?'.$querystring, 'icon' => $button['icon']];
                    //             break;
                    //     }
                    // }
                }
            }
            $users[] = $user;
        }

        return response()->json($users);
    }

    protected function get_list_buttons() {
        return [ ['title' => 'Add New', 'link' => $this->_base_url.'/addnew' ], ['title' => 'Import Users', 'link' => $this->_base_url.'/import'], ['title' => 'Export Users', 'link' => $this->_base_url.'/export'] ];
    }

    protected function get_import_fields($records){
        $response = LambdaRequest::signedrequest('get', $this->_service, 'contactattribute/get_all');
        $hierar = $this->getlambda('get', 'ums', 'hierarchy', 'dropdown');
        $hierar_dd = [];
        foreach($hierar->data->items as $hier){
            $hierar_dd[$hier->code] = $hier->name . ' (' . $hier->code . ')';
        }

        //echo '
'; print_r($response); exit;
        $fields = [
            'name' => ['title' => 'Name', 'type' => 'text', 'required' => true],
            'email' => ['title' => 'Email', 'type' => 'email', 'required' => true],
            'phone' => ['title' => 'Phone', 'type' => 'text', 'required' => true],
            'msl_code' => ['title' => 'MSL Code', 'type' => 'text'],
            'position' => ['title' => 'Position', 'type' => 'select', 'required' => true, 'values' => $hierar_dd ],
            'status' => ['title' => 'Status', 'type' => 'select', 'required' => true, 'values' => ['active' => 'Active', 'disabled' => 'Disabled'] ],
        ];

        foreach ($response->data->items as $item) {
            $values = [];
            if(in_array($item->type, ['select', 'radio', 'checkbox']) ) {
                foreach($item->options as $op) {
                    $values[$op->value] = $op->display;
                }
            }
            $fields[$item->code] = ['title' => $item->attribute, 'type' => $item->type, 'required' => $item->required=='yes'?true:false, 'values' => $values];
        }
        return $fields;
    }

    // public function list(Request $request) {
    //     $response = LambdaRequest::signedrequest('get', $this->_service, $this->_module.'/get_all');
    //     //echo '
'; print_r($items); exit;
    //     $items = [];
    //     foreach ($response->data->items as $item) {
    //         $item->position = $item->hierarchy_info->code;
    //         unset($item->hierarchy_info);
    //         $items[] = $item;
    //     }
        
    //     $fields = $this->get_list_fields();
    //     return $this->view('list')->with([
    //         'title' => $this->_title,
    //         'fields' => $fields,
    //         'base_url' => $this->_base_url,
    //         'items' => $items,
    //         'buttons' => $this->get_list_buttons()
    //     ]);
    // }

    protected function get_list_fields(){
        return [
            'actions' => ['title' => 'Actions', 'buttons' => [ 'edit', 'delete' ] ],
            'name' => ['title' => 'Name', 'type' => 'text'],
            'msl_code' => ['title' => 'MSL Code', 'type' => 'text'],
            'position_name' => ['title' => 'Position', 'type' => 'text'],
            'user_name' => ['title' => 'Rep Name', 'type' => 'text'],
            'status' => ['title' => 'Status', 'type' => 'select'],
        ];
    }

    protected function get_form_fields($type, $values){
        $response = LambdaRequest::signedrequest('get', $this->_service, 'contactattribute/get_all');
        $hierar = $this->getlambda('get', 'ums', 'hierarchy', 'dropdown');
        $hierar_dd = [];
        foreach($hierar->data->items as $hier){
            $hierar_dd[$hier->code] = $hier->name . ' (' . $hier->code . ')';
        }

        //echo '
'; print_r($response); exit;
        $fields = [
            'name' => ['title' => 'Name', 'type' => 'text', 'required' => true],
            'email' => ['title' => 'Email', 'type' => 'email', 'required' => true],
            'phone' => ['title' => 'Phone', 'type' => 'text', 'required' => true],
            'msl_code' => ['title' => 'MSL Code', 'type' => 'text'],
            'position' => ['title' => 'Position', 'type' => 'select', 'required' => true, 'values' => $hierar_dd ],
            'status' => ['title' => 'Status', 'type' => 'select', 'required' => true, 'values' => ['active' => 'Active', 'disabled' => 'Disabled'] ],
        ];

        foreach ($response->data->items as $item) {
            $values = [];
            if(in_array($item->type, ['select', 'radio', 'checkbox']) ) {
                foreach($item->options as $op) {
                    $values[$op->value] = $op->display;
                }
            }
            $fields[$item->code] = ['title' => $item->attribute, 'type' => $item->type, 'required' => $item->required=='yes'?true:false, 'values' => $values];
        }

        return $fields;
    }

    protected function _beforesave($type, $request) {
        $data = $request->except('_token');
        $data['entity_id'] = $request->session()->get('entity_id');
        $options = [];
        if(isset($data['option_value'])) {
            foreach($data['option_value'] as $k => $ov) {
                $options[] = ['value' => $ov, 'display' => $data['option_name'][$k] ];
            }
            $data['options'] = $options;
            unset($data['option_value']);
            unset($data['option_name']);
        }
        return $data;
    }

    public function editall(Request $request) {
        $response = LambdaRequest::signedrequest('get', $this->_service, $this->_module.'/get_my_contacts');
        //echo '
'; print_r($response); exit;
        $fields = $this->get_list_fields();
        return $this->view('editall')->with([
            'title' => $this->_title,
            'fields' => $response->data->attributes,
            'base_url' => $this->_base_url,
            'items' => $response->data->items
        ]);
    }

    public function postsavelist(Request $request) {
        Log::debug(print_r($request->except('_token'), true));
        $response = LambdaRequest::signedrequest('post', $this->_service, $this->_module.'/savelist', $request->except('_token'));
        // //echo '
'; print_r($response); exit;
        // $fields = $this->get_list_fields();
        // return $this->view('editall')->with([
        //     'title' => $this->_title,
        //     'fields' => $response->data->attributes,
        //     'base_url' => $this->_base_url,
        //     'items' => $response->data->items
        // ]);
    }
    

    public function export(Request $request) {
        $attributes = LambdaRequest::signedrequest('get', $this->_service, 'contactattribute/get_all', []);
        $fields = [];
        foreach($attributes->data->items as $attri) {
            $fields[] = $attri->code;
        }
        $fields[] = 'user_info';
        $fields[] = 'msl_code';
        $fields[] = 'position';
        //echo '
'; print_r($response); exit;

        $response = LambdaRequest::signedrequest('get', $this->_service, $this->_module.'/get_all', ['source' => 'dynamodb', 'belowme' => 'yes', 'search' => json_encode([]), 'keyword' => "", 'fields' => json_encode($fields) ]);
        //echo '
'; print_r($response); exit;

        $headers = ['Name', 'Email', 'Phone', 'MSL Code', 'Position', 'Rep Name', 'Rep Employee Code', 'Position Name', 'Position Code', 'Status'];
        foreach($attributes->data->items as $attri) {
            $headers[] = $attri->attribute;
        }

        $exceldata[] = $headers;
        foreach($response->data->items as $user) {
            $row = [];
            $row[] = isset($user->name) ? $user->name : '-';
            $row[] = isset($user->email) ? $user->email : '-';
            $row[] = isset($user->phone) ? $user->phone : '-';
            $row[] = isset($user->msl_code) ? $user->msl_code : '-';
            $row[] = isset($user->position) ? $user->position : '-';

            $row[] = isset($user->user_info->name) ? $user->user_info->name : '-';
            $row[] = isset($user->user_info->employee_code) ? $user->user_info->employee_code : '-';

            $row[] = isset($user->hierarchy_info->name) ? $user->hierarchy_info->name : '-';
            $row[] = isset($user->hierarchy_info->code) ? $user->hierarchy_info->code : '-';
            $row[] = isset($user->status) ? $user->status : '-';

            foreach($attributes->data->items as $attri) {
                $row[] = isset($user->{$attri->code}) ? $user->{$attri->code} : '-';
            }            
            $exceldata[] = $row;
        }
        return Excel::download(new InvoicesExport($exceldata), 'contacts.xlsx');
    }


    // public function postimport(Request $request) {
    //     if( $request->file('importfile') ) {
    //         $path = $request->file('importfile')->store('user_import');
    //         $request->session()->put('user_import_path', $path);

    //         $csv = Reader::createFromPath(storage_path('app') .'/' . $path, 'r');
    //         $csv->setHeaderOffset(0);

    //         $header = $csv->getHeader(); //returns the CSV header record
    //         $records = $csv->getRecords(); //returns all the CSV records as an Iterator 
    //         $contacts = [];
    //          echo '
';
    //         foreach($records as $record) {
    //             $contacts[] = (array)$record;
    //         }

    //         $created = 0;
    //         $updated = 0;
    //         $count = 0;
    //         $total = sizeof($contacts);

    //         while($count < $total) {
    //             $tempdata = array_slice($contacts, $count, 20);
    //             Log::debug(print_r($tempdata, true));
    //             $response = LambdaRequest::signedrequest('post', $this->_service, $this->_module.'/import', $tempdata);
    //             Log::debug(print_r($response, true));
    //             $count = $count + 20;
    //             $created = $created + $response->data->created_count;
    //             $updated = $updated + (isset($response->data->updated_count) ? $response->data->updated_count : 0);
    //             Log::debug(print_r(['$count' => $count, '$created' => $created, '$updated' => $updated], true));
    //         }

    //         //echo '
'; print_r($response); exit;
    //         if($response->statusCode == 200 && $response->status == "success") {
    //             return redirect($this->_base_url.'s')->withMessage('Successfully Imported ' .$created. ' records and Updated ' .$updated. ' records out of ' .$total. ' records!!!');
    //         } else {
    //             return \Redirect::back()->withMessage('Some Error occured!');
    //         }


    //         exit;
    //         return redirect($this->_base_url.'/importmap')->withMessage('Successfully Uploaded !!!');
    //     } else {
    //         return \Redirect::back()->withMessage('Some Error occured!');
    //     }
    // }
}