middleware('auth'); $this->_service = 'form'; $this->_module = 'formentity'; $this->_viewname = 'formentity'; $this->_title = 'Form'; $this->_base_url = '/formentity'; } protected function get_list_fields(){ return [ 'actions' => ['title' => 'Actions', 'buttons' => [ 'edit', 'delete', 'questions' => ['icon' => 'progress-question', 'querystring' => 'id={ID}&form_title={TITLE}&map_auth_key={MAP_AUTH_KEY}'], 'import' => ['icon' => 'cloud-upload', 'querystring' => 'id={ID}'] ] ], 'title' => ['title' => 'Title', 'type' => 'text'], 'workflow' => ['title' => 'Workflow', 'type' => 'text'], 'status' => ['title' => 'Status', 'type' => 'select'], ]; } protected function get_form_fields($type, $values){ $users = $this->getlambda('get', 'ums', 'users', 'dropdown'); //Log::debug(print_r($users, true)); exit; $users_dd = ['l1manager' => 'L1 Manager', 'l2manager' => 'L2 Manager', 'l3manager' => 'L3 Manager', 'l4manager' => 'L4 Manager']; $notify_users_dd = []; foreach($users->data->items as $user){ $label = $user->firstname . ' ' . $user->lastname . ' (' . $user->employee_code . ')'; $users_dd[$user->id] = $label; $notify_users_dd[$user->id] = $label; } $roles = $this->getlambda('get', 'ums', 'roles', 'dropdown'); $roles_dd = []; foreach($roles->data->items as $role){ $roles_dd[$role->id] = $role->name; } $coattr = $this->getlambda('get', 'contact', 'contactattribute', 'get_all'); $coattr_dd = []; foreach($coattr->data->items as $coatt){ $coattr_dd[$coatt->code] = $coatt->attribute; } $userattr_dd = $this->getUserAttributeOptions(); return [ 'title' => ['title' => 'Title', 'type' => 'text', 'required' => true], 'status' => ['title' => 'Status', 'type' => 'select', 'required' => true, 'values' => ['active' => 'Active', 'disabled' => 'Disabled'] ], 'metric_submission' => ['title' => 'Metric Submission', 'type' => 'yesno', 'required' => true], 'metric_authkey' => ['title' => 'Auth Key', 'type' => 'text', 'required' => true], 'metric_ready_on_submit' => ['title' => 'Metric Ready On Submit', 'type' => 'yesno', 'required' => true, 'default' => 'no'], 'manager_de_roles' => ['title' => 'Manager Data Entry Roles', 'type' => 'multiselect', 'values' => $roles_dd ], // 'manager_data_child_role' => ['title' => 'Manager Data Child Entry Roles', 'type' => 'multiselect', 'values' => $roles_dd ], 'manager_data_child_type' => ['title' => 'Manager Data Child Type', 'type' => 'multiselect', 'values' => ['Territory' => 'Territory', 'Area' => 'Area', 'Region' => 'Region', 'Zone' => 'Zone', 'Country' => 'Country' ]], 'export_manager_levels' => ['title' => 'Export Manager Levels', 'type' => 'multiselect', 'required' => true, 'values' => ['l1manager' => 'L1 Manager', 'l2manager' => 'L2 Manager', 'l3manager' => 'L3Manager','l4manager' => 'L4 Manager']], 'contact_attributes' => ['title' => 'Include Doctor Attributes in Export', 'type' => 'multiselect', 'values' => $coattr_dd], 'show_user_attributes' => ['title' => 'Show User Attributes', 'type' => 'yesno', 'required' => true, 'default' => 'no'], 'user_attributes' => ['title' => 'Include User Attributes in Export', 'type' => 'multiselect', 'values' => $userattr_dd, 'default' => []], 'form_type' => ['title' => 'Enter From Type', 'type' => 'select', 'required' => false, 'values' => ['plan_vs_execution' => 'Plan vs Execution', 'enrollment_form' => 'Enrollment Form'] ], 'enrollment_form_attributes' => ['title' => 'Enter Attributes for Enrollment Form', 'type' => 'multiselect', 'values' => $coattr_dd], 'self_notification' => ['title' => 'Self Email Notification', 'type' => 'yesno', 'required' => true, 'fullwidth' => true], 'manager1_email_notification' => ['title' => '1st Level Manager Email Notification', 'type' => 'yesno', 'required' => true], 'manager1_push_notification' => ['title' => '1st Level Manager Mobile Notification', 'type' => 'yesno', 'required' => true], 'manager2_email_notification' => ['title' => '2nd Level Manager Email Notification', 'type' => 'yesno', 'required' => true], 'manager2_push_notification' => ['title' => '2nd Level Manager Mobile Notification', 'type' => 'yesno', 'required' => true], 'roles_email_notification' => ['title' => 'Email Notification to Roles', 'type' => 'multiselect', 'values' => $roles_dd ], 'roles_push_notification' => ['title' => 'Push Notification to Roles', 'type' => 'multiselect', 'values' => $roles_dd ], 'show_positions' => ['title' => 'Show Positions on Submitted Data', 'type' => 'yesno', 'required' => true, 'default' => 'no'], 'show_positions_type' => ['title' => 'Show Positions Type', 'type' => 'select', 'required' => true, 'values' => ['all' => 'All', 'loggedin' => 'Logged In'], 'default' => 'all'], 'show_manager_details' => ['title' => 'Show Managers details on Submitted Data', 'type' => 'yesno', 'required' => true, 'default' => 'no'], 'roles_info' => ['title' => 'Roles Info', 'type' => 'yesno', 'required' => true, 'default' => 'no'], 'allow_non_hierarchy_submission' => ['title' => 'Allow Non Hierarchy Submission', 'type' => 'yesno', 'required' => true], 'workflow' => ['title' => 'Enable Workflow', 'type' => 'yesno', 'required' => true], 'workflow_type' => ['title' => 'Workflow type', 'type' => 'select', 'required' => true, 'values' => ['single' => 'Single Persoon', 'multiple' => 'Multiple person', 'sequencial' => 'Sequencial'] ], 'retain_status_on_resubmit' => ['title' => 'Retain workflow status on resubmit', 'type' => 'yesno', 'required' => true], 'approver_can_edit' => ['title' => 'Approver can edit entry', 'type' => 'yesno', 'required' => true], 'send_email_workflow_notification' => ['title' => 'Send Email Workflow Notification', 'type' => 'yesno', 'required' => true], 'send_approval_to_manager_if_approver_vacant' => ['title' => 'Send Approval Notification to Manager if Approver is Vacant', 'type' => 'yesno', 'required' => true], 'is_personalized' => ['title' => 'Is Personalization Needed', 'type' => 'yesno', 'required' => true], 'allow_delete_by_user' => ['title' => 'Allow Submission Delete by User', 'type' => 'yesno', 'required' => true], 'auto_approve' => ['title' => 'Want To Auto Approve', 'type' => 'yesno', 'required' => true], 'auto_approve_condition' => ['title' => 'Auto Approve Condition If Any', 'type' => 'textarea', 'required' => false, 'fullwidth' => true ], 'export_fields' => ['title' => 'Export Fields', 'type' => 'textarea', 'required' => false, 'fullwidth' => true ], 'workflow_approvers' => ['title' => 'Metric', 'type' => 'mapping', 'required' => true, 'approvers' => $users_dd, 'fullwidth' => true ], 'email_notification' => ['title' => 'Email Notification', 'type' => 'yesno', 'required' => true, 'default' => 'no', 'fullwidth' => true], 'email_notification_rules' => [ 'title' => 'Email Notification Rules', 'type' => 'email_notifications', 'required' => false, 'fullwidth' => true, 'hide_label' => true, 'manager_levels' => [ 'l1manager' => 'L1 Manager', 'l2manager' => 'L2 Manager', 'l3manager' => 'L3 Manager', 'l4manager' => 'L4 Manager', ], 'roles' => $roles_dd, 'users' => $notify_users_dd, ], ]; } protected function _beforeform($type, $values) { if($type == 'edit') { $values->self_notification = isset($values->self_notification) ? $values->self_notification : 'no'; $values->manager1_email_notification = isset($values->manager1_email_notification) ? $values->manager1_email_notification : 'no'; $values->manager1_push_notification = isset($values->manager1_push_notification) ? $values->manager1_push_notification : 'no'; $values->manager2_email_notification = isset($values->manager2_email_notification) ? $values->manager2_email_notification : 'no'; $values->manager2_push_notification = isset($values->manager2_push_notification) ? $values->manager2_push_notification : 'no'; $values->send_approval_to_manager_if_approver_vacant = isset($values->send_approval_to_manager_if_approver_vacant) ? $values->send_approval_to_manager_if_approver_vacant : 'no'; $values->export_fields = isset($values->export_fields) ? $values->export_fields : ''; $values->email_notification_rules = $this->normalizeEmailNotificationRules($values->email_notification_rules ?? null); $values->email_notification = $values->email_notification ?? 'no'; if ($values->email_notification !== 'yes' && count($values->email_notification_rules) > 0) { $values->email_notification = 'yes'; } $values->form_type = $values->form_type ?? ''; $values->enrollment_form_attributes = $values->enrollment_form_attributes ?? []; $values->auto_approve = $values->auto_approve ?? 'no'; $values->auto_approve_condition = $values->auto_approve_condition ?? ''; $values->roles_info = $values->roles_info ?? 'no'; // Prefer show_positions; fall back to legacy show_position for existing forms. if (!isset($values->show_positions) || $values->show_positions === '') { $values->show_positions = $values->show_position ?? 'no'; } $values->show_positions = strtolower((string) $values->show_positions); if (!isset($values->show_positions_type) || $values->show_positions_type === '') { $values->show_positions_type = $values->show_position_type ?? 'all'; } $values->show_positions_type = strtolower((string) $values->show_positions_type); if (!in_array($values->show_positions_type, ['all', 'loggedin'], true)) { $values->show_positions_type = 'all'; } $values->show_manager_details = $values->show_manager_details ?? 'no'; $values->show_user_attributes = (($values->show_user_attributes ?? 'no') === 'yes') ? 'yes' : 'no'; $values->user_attributes = $this->normalizeAttributeCodes($values->user_attributes ?? []); } //echo '
'; print_r($values); exit;
        return $values;
    }

    public function questions(Request $request) {
        $entity_id = $request->input('id', 0);
        $form_title = $request->input('form_title', '');
        $map_auth_key = $request->input('map_auth_key', '');

        if($entity_id === 0) {
            return redirect('/formentitys')->withError('Form not found!');
        } else {
            $request->session()->put('entity_id', $entity_id);
            $request->session()->put('form_title', $form_title);
            $request->session()->put('map_auth_key', $map_auth_key);
            return redirect('/formquestions');
        }
    }

    public function postimport(Request $request) {
        $entity_id = $request->input('id');
        if( $request->file('importfile') ) {
            $path = $request->file('importfile')->store('form_import');
            $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 object

            $response = LambdaRequest::signedrequest('get', $this->_service, 'formquestion/get_all', ['entity_id' => $entity_id]);
            $forfields = [];
            foreach ($response->data->items as $q) {
                $forfields[] = $q->code;
            }

            $count = 0;
            $recs = [];
            // $forfields = ['is-aware-of-the-customer-perspective-potential-prescription-position','has-customer-plan-based-on-customer-perspective','rcpawardicu-quantified-rcpa-comp-taken-pob-dr-perspective-on-molecule-or-price-etc','call-objective-planned-question-opening-statement-materials-and-objection-anticipated','greeted-customer-appropriately','used-planned-opening-statement','gained-attention-of-the-customer','was-ready-with-tab-maintained-eye-contact-with-doctor-had-a-clear-voice','asked-planned-question-as-per-call-planning','asked-question-related-to-customer-behaviourbelief-service','listened-attentively-and-asked-follow-up-question-if-required','generated-desired-response-from-customer','maintained-the-sequence-of-product-as-per-the-speciality-p1p2p3','shared-benefit-of-productdevicesservices-as-per-marketing-strategy','shared-informationused-the-materialstools-as-per-plan-demonstrated-and-discussed-cipla-devices','utilized-the-tab-effectively-smooth-navigation-highlighted-studies-zoomed-graphs-etc','listened-attentively-acknowledged-concern','asked-questions-to-seek-clarity-on-questionobjection','shared-the-relevant-information','confirmed-if-objectionquestion-was-addressed-assured-follow-through-actions-if-required-and-returned-to-call-flow','summarized-the-key-discussion-points','gained-agreement-basis-call-objective-from-the-doctor','quantified-the-demand-with-rx','left-lblreminder-of-focused-product','total_score','area-of-strength','area-of-development','coaching-objective','development-time-frame','next-coaching-visit','development-action-plan'];

            foreach ($records as $record) {
                $record['record_date'] = '2024-04-02';
                $record['created_date'] = strtotime("now");
                $formdata = [];
                foreach($forfields as $field) {
                    if(isset($record[$field])) {
                        $formdata[$field] = $record[$field] == 'Yes' ? 1 : (  $record[$field] == 'No' ? 0 : $record[$field] ) ;
                    }
                }
                $recs[] = [
                    'entity_id' => $entity_id,
                    'formdata' => $formdata,
                    'employee_code' => $record['employee_code'],
                    'partition' => 'rapport-'.Auth::user()->domain,
                    'record_date' => strtotime($record['record_date']),
                    'createdAt' => strtotime($record['created_date'])
                ];
                if(sizeof($recs) >= 25) {
                    $response = LambdaRequest::signedrequest('post', $this->_service, $this->_module.'/import', $recs);
                    $recs = [];
                }
            }
            $response = LambdaRequest::signedrequest('post', $this->_service, $this->_module.'/import', $recs);
            return redirect($this->_base_url.'s')->withMessage('Successfully Uploaded !!!');
        } else {
            return \Redirect::back()->withMessage('Some Error occured!');
        }
    }

    protected function _beforesave($type, $request) {
        $data = $request->except('_token');

        if (!isset($data['manager_data_child_type']) || empty($data['manager_data_child_type'])) {
            $data['manager_data_child_type'] = [];
        }

        if (!isset($data['export_manager_levels']) || empty($data['export_manager_levels'])) {
            $data['export_manager_levels'] = [];
        }

        if($type == 'new'){
            $metricmappingdata = [];
            $metricmappingdata['name'] = $data['title'];
            $metricmappingdata['status'] ='active';
            $metricmapping = LambdaRequest::signedrequest('post', 'metric', 'injestion_mapping/create', $metricmappingdata);
            $data['map_auth_key'] = $metricmapping->data->item->id;
            $data['metric_submission'] = 'yes';
        }

        $data['email_notification'] = ($data['email_notification'] ?? 'no') === 'yes' ? 'yes' : 'no';
        $data['roles_info'] = ($data['roles_info'] ?? 'no') === 'yes' ? 'yes' : 'no';
        $data['show_user_attributes'] = ($data['show_user_attributes'] ?? 'no') === 'yes' ? 'yes' : 'no';
        $data['user_attributes'] = $this->normalizeAttributeCodes($data['user_attributes'] ?? []);
        if ($data['email_notification'] === 'no') {
            $data['email_notification_rules'] = [];
        } else {
            $data['email_notification_rules'] = $this->buildEmailNotificationRulesFromRequest($request);
        }

        return $data;
    }

    protected function normalizeEmailNotificationRules($raw): array
    {
        if (is_string($raw) && $raw !== '') {
            $decoded = json_decode($raw, true);
            $raw = is_array($decoded) ? $decoded : [];
        }
        if (!is_array($raw)) {
            return [];
        }

        $rules = [];
        foreach ($raw as $rule) {
            if (!is_array($rule) && !is_object($rule)) {
                continue;
            }
            $rule = (array) $rule;
            $rules[] = [
                'enabled' => ($rule['enabled'] ?? 'yes') === 'no' ? 'no' : 'yes',
                'manager_levels' => array_values(array_filter((array) ($rule['manager_levels'] ?? []))),
                'role_ids' => array_values(array_filter((array) ($rule['role_ids'] ?? []))),
                'selected_users' => array_values(array_filter((array) ($rule['selected_users'] ?? []))),
                'condition' => (string) ($rule['condition'] ?? ''),
                'subject' => (string) ($rule['subject'] ?? ''),
                'body' => (string) ($rule['body'] ?? ''),
            ];
        }

        return $rules;
    }

    protected function buildEmailNotificationRulesFromRequest(Request $request): array
    {
        $rawRules = $request->input('email_notification_rules', []);
        if (!is_array($rawRules)) {
            return [];
        }

        $rules = [];
        foreach ($rawRules as $rule) {
            if (!is_array($rule)) {
                continue;
            }

            $managerLevels = array_values(array_filter((array) ($rule['manager_levels'] ?? [])));
            $roleIds = array_values(array_filter((array) ($rule['role_ids'] ?? [])));
            $selectedUsers = array_values(array_filter((array) ($rule['selected_users'] ?? [])));
            $condition = trim((string) ($rule['condition'] ?? ''));
            $subject = trim((string) ($rule['subject'] ?? ''));
            $body = trim((string) ($rule['body'] ?? ''));
            $enabled = ($rule['enabled'] ?? 'yes') === 'no' ? 'no' : 'yes';

            if (
                $enabled === 'no'
                && empty($managerLevels)
                && empty($roleIds)
                && empty($selectedUsers)
                && $condition === ''
                && $subject === ''
                && $body === ''
            ) {
                continue;
            }

            if ($condition !== '') {
                json_decode($condition, true);
                if (json_last_error() !== JSON_ERROR_NONE) {
                    continue;
                }
            }

            $rules[] = [
                'enabled' => $enabled,
                'manager_levels' => $managerLevels,
                'role_ids' => $roleIds,
                'selected_users' => $selectedUsers,
                'condition' => $condition,
                'subject' => $subject,
                'body' => $body,
            ];
        }

        return $rules;
    }

    public function save($type, $request ) {
    	if($type == 'edit') {
    		$url = '/update';
    	} else {
    		$url = '/create';
    	}
        $data = $this->_beforesave($type, $request);
        // echo "
";
        // print_r($data);
        // exit;
    	$response = LambdaRequest::signedrequest('post', $this->_service, $this->_module.$url, $data);
        
        if($type == 'new'){
            $updateform = ['metric_authkey' => $data['map_auth_key'] , 'id' => $response->data->item->id];
            $formupdateinjetionkey = LambdaRequest::signedrequest('post', 'form', 'formentity/update', $updateform);
        }
        
    	if($response->statusCode == 200 && $response->status == "success") {
            return redirect($this->_base_url.'s')->withMessage('Successfully Saved !!!');
    	} else {
            return redirect($this->_base_url.'s')->withError('Some Error occured! '. $response->message);
    	}
    }

    protected function getUserAttributeOptions(): array
    {
        $options = [];
        $userAttrs = $this->getlambda('get', 'ums', 'userattribute', 'get_all');
        foreach (($userAttrs->data->items ?? []) as $attr) {
            if (($attr->status ?? 'active') === 'disabled') {
                continue;
            }
            $code = $attr->code ?? '';
            if ($code === '') {
                continue;
            }
            $options[$code] = $attr->attribute ?? $code;
        }
        return $options;
    }

    protected function normalizeAttributeCodes($raw): array
    {
        if (is_string($raw) && $raw !== '') {
            $decoded = json_decode($raw, true);
            $raw = is_array($decoded) ? $decoded : explode('#', $raw);
        }
        if (!is_array($raw)) {
            return [];
        }

        $codes = [];
        foreach ($raw as $code) {
            if (is_object($code)) {
                $code = $code->code ?? '';
            }
            $code = trim((string) $code);
            if ($code !== '') {
                $codes[] = $code;
            }
        }

        return array_values(array_unique($codes));
    }
}