middleware('auth')->except(['contactpreview']); $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
        // ]);
    }
    

    protected function lambdaResponseData($response, string $label = 'API')
    {
        if (!is_object($response)) {
            throw new \RuntimeException($label . ' returned an invalid response.');
        }
        if (isset($response->body) && is_string($response->body)) {
            $decoded = json_decode($response->body);
            if (is_object($decoded)) {
                $response = $decoded;
            }
        }
        if (isset($response->status) && $response->status !== 'success') {
            $message = !empty($response->message) && is_string($response->message)
                ? $response->message
                : ($label . ' request failed.');
            throw new \RuntimeException($message);
        }
        if (!isset($response->data)) {
            throw new \RuntimeException($label . ' response is missing data.');
        }
        return $response->data;
    }

    // contact exports starts here
    public function export(Request $request)
    {
        $response = LambdaRequest::signedrequest('get', 'contact', 'contact_exports' . '/get_all');
        $items = [];
        if(isset($response->data->items)){
            foreach ($response->data->items as $item) {
                $item->READABLE_DATE = Carbon::parse($item->createdAt)->setTimezone('Asia/Kolkata')->format('d M Y, h:i A');
                $item->DOWNLOAD_URL = $item->download_url === 'text' ? '#' : $item->download_url;
                $items[] = $item;
            }
        }

        $fields = [
            'actions' => ['title' => 'Actions', 'buttons' => ['delete', 'download' => ['icon' => 'cloud-download', 'href' => 'DOWNLOAD_URL']]],
            'file_status' => ['title' => 'File Status', 'type' => 'text', 'required' => true],
            'export_status' => ['title' => 'Export Status', 'type' => 'text', 'required' => true],
            'READABLE_DATE' => ['title' => 'Created On', 'type' => 'text', 'required' => true],
        ];

        $buttons = [['title' => 'Create Export', 'link' => $this->_base_url . '/exportcreate']];

        return $this->view('list')->with([
            'title' => $this->_title,
            'fields' => $fields,
            'base_url' => $this->_base_url,
            'items' => $items,
            'buttons' => $buttons,
        ]);
    }

    public function exportcreate(Request $request)
    {
        $hierar = $this->getlambda('get', 'ums', 'hierarchy', 'dropdown');
        $positionCode = [];
        $positionCode['all'] = 'All Position Code';
        foreach ($hierar->data->items as $hier) {
            $positionCode[$hier->code] = $hier->name . ' (' . $hier->code . ')';
        }
        return view('contact.export')->with(['title' => $this->_title, 'positioncode' => $positionCode]);
    }

    public function postexportcreate(Request $request)
    {
        $data = $request->except('_token');
        // echo '
'; print_r($data); exit;
        $response = LambdaRequest::signedrequest('post', 'contact', 'contact_exports/create', ['position_code' => $data['filter_position_code'], 'export_status' => $data['filter_status']]);
        return response()->json($response);
    }

    public function exportgetcreatedcsv(Request $request)
    {
        $id = $request->input('id');
        $response = LambdaRequest::signedrequest('get', 'contact', 'contact_exports/get_one', ['id' => $id]);
        return response()->json($response);
    }


    // 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->skipEmptyRecords();
    //         $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) {
    //             $record = (array)$record;
    //             if(!empty($record['name'])) {
    //                 $contacts[] = $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!');
    //     }
    // }

    public function postimport(Request $request) {
        $fullPath = $this->_uploadMedia($request, 'file_path', 'contact_import');
        $filedata = ['file_path' => $fullPath];
        $response = LambdaRequest::signedrequest('post', $this->_service, 'contact_imports/create', $filedata);
        return response()->json($response);
    }

    public function importfilegetbyid(Request $request) {
        $response = LambdaRequest::signedrequest('get', $this->_service, 'contact_imports/get_one', ['id' => $request->id]);
        return response()->json($response);
    }

    public function showfileimporterrors(Request $request) { 
        $id = $request->input('id', 0);
        $response = LambdaRequest::signedrequest('get', $this->_service, 'contact_imports/import_grid_cloumn', ['id' => $id]);
        return response()->json($response);
    }

    public function postfileimportupdate(Request $request){ 
        $response = LambdaRequest::signedrequest('post', $this->_service, 'contact_imports/row_wise_data_update', $request->all());
        return response()->json($response);
    }

    public function postimportactions(Request $request){
        $response = LambdaRequest::signedrequest('post', $this->_service, 'contact_imports/update', $request->all());
        return response()->json($response);
    }

    public function contactpreview(Request $request)
    {
        $data = $request->input('data');
        if (empty($data)) {
            return view('contact.contactpreview-error')->with([
                'message' => 'Invalid or missing preview link.',
            ]);
        }

        $response = LambdaRequest::postrequest('contact', 'contact/contactpreview', ['data' => $data]);
        if (!isset($response->status) || $response->status !== 'success') {
            return view('contact.contactpreview-error')->with([
                'message' => $response->message ?? 'Unable to load contact preview.',
            ]);
        }

        $contact = $response->data->contact ?? (object) [];
        $approval = $response->data->approval ?? (object) [];
        $changes = $response->data->changes ?? [];
        $hierarchyName = is_object($contact->hierarchy_info ?? null) ? ($contact->hierarchy_info->name ?? '') : '';
        $submittedBy = is_object($approval->user_info ?? null)
            ? ($approval->user_info->name ?? '')
            : (is_object($contact->user_info ?? null) ? ($contact->user_info->name ?? '') : '');

        $basicDetails = [
            ['label' => 'Name', 'value' => $contact->name ?? ''],
            ['label' => 'MSL Code', 'value' => $contact->msl_code ?? ''],
            ['label' => 'Phone', 'value' => $contact->phone ?? ''],
            ['label' => 'Email', 'value' => $contact->email ?? ''],
            ['label' => 'Type', 'value' => ucfirst($contact->type ?? '')],
            ['label' => 'Position', 'value' => $contact->position ?? $hierarchyName],
            ['label' => 'Territory / Hierarchy', 'value' => $hierarchyName],
            ['label' => 'Submitted By', 'value' => $submittedBy],
        ];

        $workflowStatus = $approval->workflow_status ?? 'unapproved';
        $statusLabel = ucfirst(str_replace('_', ' ', $workflowStatus));
        $typeLabel = ucfirst($approval->type ?? ($contact->type ?? 'contact'));

        return view('contact.contactpreview')->with([
            'contact' => $contact,
            'approval' => $approval,
            'changes' => $changes,
            'basic_details' => $basicDetails,
            'status_label' => $statusLabel,
            'type_label' => $typeLabel,
            'submission_id' => $response->data->submission_id ?? '',
        ]);
    }
}