_service = 'form'; $this->_module = 'formaction'; $this->_viewname = 'formaction'; $this->_title = 'Quick Actions'; $this->_base_url = '/formaction'; } protected function deliverform($formdata, $questions, $id = false) { $additional_info = $this->get_additional_info($formdata); // if($formdata->form_id == '1711609582-e93dba24-9c98-43e7-b97a-b22d64d9b9fc') { // echo '
'; print_r($formdata); print_r($questions); exit;
        // }
        //echo '
'; print_r($formdata); print_r($questions); exit;
        $data = ['questions' => $questions, 'form' => $formdata, 'form_id' => $formdata->form_id, 'id' => false, 'id' => $id ];
        Log::debug(print_r($data, true));
        //echo '
'; print_r($data); exit;
        if(sizeof($additional_info) > 0) {
            $data['additional'] = $additional_info;
        }
        if (\View::exists('form.'.$formdata->partition.'.'.$formdata->form_id)) {
            return view('form.'.$formdata->partition.'.'.$formdata->form_id)->with($data);
        } elseif (\View::exists('form.'.$formdata->form_id)) {
            return view('form.'.$formdata->form_id)->with($data);
        } else {
            return view('form.common')->with($data);
        }
    }

    protected function muscle_questions($formdata) {
        switch($formdata->form_id) {
            case '63c2ff17-a69c-4b47-af33-1d9909c608b6':
            case 'eaef2abf-f16b-414c-b6a5-df3fd2282b2e':
                $hierarchy = LambdaRequest::getrequest('ums', 'hierarchy/hierarchy_below_me', ['partition' => $formdata->partition, 'user_id' => $formdata->user_id ]);
                $team = [];
                foreach($hierarchy->data->hierarchies as $hie) {
                    if(isset($hie->owner_info->id)) {
                        $team[$hie->owner_info->id] = ['name' => $hie->owner_info->name, 'code' => $hie->owner_info->employee_code ];
                    }
                }
                return ['team' => $team];
            break;

            default:
                return [];
            break;
        }
    }

    public function handle($finfo, Request $request) {
        $time = strtotime("now");
        Log::debug('enter handle - ' . $time);
        $request->session()->put('finfo', $finfo);
        // $finfo = Cache::remember($finfo, 3600, function () use ($finfo) {
        //    return LambdaRequest::postrequest('form', 'formentity/getforminfo', ['finfo' => $finfo]);
        // });
        $finfo = LambdaRequest::postrequest('form', 'formentity/getforminfo', ['finfo' => $finfo]);
        //echo '
'; print_r($finfo); exit;
        // if($finfo->data->formdata->partition == 'rapport-dc') {
        //     echo 'Temporary down for maintanance, please check back after 10 min'; exit;
        // }
        Log::debug('after getforminfo - ' . $time);
        Log::debug(print_r($finfo, true));
        if( isset($finfo->data->users) && sizeof($finfo->data->users) > 0 ) {
            $finfo->data->formdata->users = $finfo->data->users;
            $finfo->data->formdata->manager_can_submit = true;
        }
        $request->session()->put('formdata', isset($finfo->data->formdata) ? $finfo->data->formdata : $finfo->data->form );
        if($finfo->status == 'success' && $finfo->data->formdata->link_type == 'form' && isset($finfo->data->personalizations) && sizeof($finfo->data->personalizations) > 0 ){
            return $this->deliverpersonalization($finfo->data->formdata, $finfo->data->questions, $finfo->data->personalizations);
        } else if($finfo->status == 'success' && $finfo->data->formdata->link_type == 'form') {
            return $this->deliverform($finfo->data->formdata, $finfo->data->questions);
        } elseif($finfo->status == 'success' && $finfo->data->formdata->link_type == 'list') {
            //echo '
'; print_r($finfo->data); exit;
            if (\View::exists('form.'.$finfo->data->formdata->partition.'.list-'.$finfo->data->formdata->form_id)) {
                return view('form.'.$finfo->data->formdata->partition.'.list-'.$finfo->data->formdata->form_id)->with(['questions' => $finfo->data->questions, 'submissions' => $finfo->data->submissions, 'formname' => $finfo->data->formdata->title, 'form_id' => $finfo->data->formdata->form_id, 'lastkey' => $finfo->data->lastkey, 'formdata' => $finfo->data->formdata ]);
            } elseif (\View::exists('form.list-'.$finfo->data->formdata->form_id)) {
                return view('form.list-'.$finfo->data->formdata->form_id)->with(['questions' => $finfo->data->questions, 'submissions' => $finfo->data->submissions, 'formname' => $finfo->data->formdata->title, 'form_id' => $finfo->data->formdata->form_id, 'lastkey' => $finfo->data->lastkey, 'formdata' => $finfo->data->formdata ]);
            } elseif (\View::exists('form.'.$finfo->data->formdata->partition.'.list')) {
                return view('form.'.$finfo->data->formdata->partition.'.list')->with(['questions' => $finfo->data->questions, 'submissions' => $finfo->data->submissions, 'formname' => $finfo->data->formdata->title, 'form_id' => $finfo->data->formdata->form_id, 'lastkey' => $finfo->data->lastkey, 'formdata' => $finfo->data->formdata ]);
            } else {
                return view('form.list')->with(['questions' => $finfo->data->questions, 'submissions' => $finfo->data->submissions, 'formname' => $finfo->data->formdata->title, 'form_id' => $finfo->data->formdata->form_id, 'lastkey' => $finfo->data->lastkey, 'formdata' => $finfo->data->formdata ]);
            }
        }
    }

    public function loadmore(Request $request) {
        $finfo = $request->session()->get('finfo');
        //echo $finfo; exit;
        $lastkey = $request->input('lastkey', '');
        //print_r(['finfo' => $finfo, 'lastkey' => $lastkey]);
        $finfo = LambdaRequest::postrequest('form', 'formentity/getforminfo', ['finfo' => $finfo, 'lastkey' => $lastkey]);
        Log::debug(print_r($finfo->data, true));
        $html = '';
        foreach($finfo->data->submissions as $submission) {
            if(isset($submission->user_info->name)) {
                $html .= '
                        '.date("d M Y", strtotime($submission->updatedAt)).'
                        
                            
'.$submission->user_info->name.'

'.(isset($submission->user_info->designation)?$submission->user_info->designation:'-').'

'.(isset($submission->user_info->employeecode)?$submission->user_info->employeecode:'-').'
'; if(isset($finfo->data->formdata) && isset($finfo->data->formdata->workflow) && $finfo->data->formdata->workflow == 'yes' ) { $html .= ''.ucwords($submission->workflow_status).''; } foreach($finfo->data->questions as $code => $question) { if($question->type == 'file'){ $html .= ' Download'; } else { $html .= ''.( isset($submission->formdata->{$code}) ? (is_array($submission->formdata->{$code}) ? implode(', ', $submission->formdata->{$code}) : $submission->formdata->{$code}) : '' ).''; } } $html .= ''; //if( in_array('edit', $submission->actions) && (strtotime("now") - strtotime($submission->createdAt)) < 432000 ){ $html .= 'Edit'; if(isset($finfo->data->formdata) && isset($finfo->data->formdata->workflow) && $finfo->data->formdata->workflow == 'yes' && $submission->workflow_status == 'unapproved' ){ $html .= ''; $html .= ''; } //} $html .= ' '; } } return response()->json(['html' => $html, 'lastkey' => $finfo->data->lastkey]); } public function show(Request $request) { $formdata = $request->session()->get('formdata'); //Log::debug(print_r($formdata, true)); $id = $request->input('id', false); $action = $request->input('action', false); Log::debug(print_r(['form_id' => $formdata->form_id, 'user_id' => $formdata->user_id, 'partition' => $formdata->partition, 'id' => $id ], true)); $finfo = LambdaRequest::postrequest('form', 'formentity/getformdefination', ['form_id' => $formdata->form_id, 'user_id' => $formdata->user_id, 'partition' => $formdata->partition, 'id' => $id ]); //Log::debug(print_r($finfo, true)); $formdata->formdata = $finfo->data->formdata; //echo '
'; print_r($formdata);  print_r($finfo); exit;
        if($formdata->form_id == '1711947857-4fbd5d43-d176-4ec7-aff2-e4dec4b6e02a' && isset($action) && $action == 'delete') {
            $contact_id = false;
            foreach($finfo->data->questions as $que) {
                if($que->code == 'contact_id') {
                    $contact_id = $que->value;
                }
            }
            list($application, $domain) = explode("-", $formdata->partition);
            $token = DB::table('users')->select("access_token")->where("domain", $domain)->where("permissions", 'like', '%contact_delete%')->orderBy('updated_at', 'desc')->skip(0)->take(1)->get();
            LambdaRequest::getrequest('contact', 'contact/delete', ['id' => $contact_id], $token[0]->access_token);
            LambdaRequest::getrequest('form', 'formentity/deletesubmission', ['id' => $id, 'form_id' => $formdata->form_id], $token[0]->access_token);
            return redirect('/form/history')->withMessage('Successfully Deleted !!!');
        }
        $formdata->title = $finfo->data->formdata->title;
        return $this->deliverform($formdata, $finfo->data->questions, $id);
    }

    public function deletesubmission(Request $request) {
        $formdata = $request->session()->get('formdata');
        //Log::debug(print_r($formdata, true));
        $id = $request->input('id', false);
        $form_id = $request->input('form_id', false);
        list($application, $domain) = explode("-", $formdata->partition);
        $token = DB::table('users')->select("access_token")->where("domain", $domain)->where("permissions", 'like', '%contact_create%')->orderBy('updated_at', 'desc')->skip(0)->take(1)->get();
        LambdaRequest::getrequest('form', 'formentity/deletesubmission', ['form_id' => $form_id, 'id' => $id ], $token[0]->access_token);
        return redirect('/form/history')->withMessage('Successfully Deleted !!!');
    }
    
    public function submit(Request $request) {
        $post = $request->except('_token');
        $files = $request->file();
        foreach($files as $fname => $file) {
            $post[$fname] = $this->_uploadMedia($request, $fname, 'form/'.$post['form_id'].'/'.$fname);
        }
        if(isset($post['id']) && $post['id']=='') unset($post['id']);
        $formdata = $request->session()->get('formdata');
        if(isset($post['user_id']) && $post['user_id'] != '') {
            $formdata->user_id = $post['user_id'];
        }

        // if($formdata->partition == 'rapport-copd') {
        //     return response()->json(['status' => 'failure']);
        // }

        if(isset($formdata) && !empty($formdata) && $formdata->user_id != '') {
            $post = $this->processformdata($formdata->form_id, $post);
            //Log::debug(print_r($post, true));
            $finfo = LambdaRequest::postrequest('form', 'formentity/submitform', ['formdata' => $post, 'entity_id' => $formdata->form_id, 'user_id' => $formdata->user_id, 'partition' => $formdata->partition ]);
            if($formdata->link_type == 'list') {
                return redirect('/form/'.$request->session()->get('finfo') )->withMessage('Successfully Saved !!!');
            } else {
                return redirect('/form/history')->withMessage('Successfully Saved !!!');
            }            
        } else {
            echo '

Something looks wrong. Try again!!!

'; exit; } } protected function createSlug($string) { // Convert to lowercase $slug = strtolower($string); // Transliterate accented characters to ASCII $slug = iconv('UTF-8', 'ASCII//TRANSLIT', $slug); // Remove special characters $slug = preg_replace('/[^a-z0-9\s]/', '', $slug); // Replace spaces with hyphens $slug = str_replace(' ', '-', $slug); // Trim leading and trailing hyphens $slug = trim($slug, '-'); return $slug; } protected function sanitizeArray($input) { foreach ($input as $key => $value) { if (is_array($value)) { $input[$key] = $this->sanitizeArray($value); } elseif (is_string($value)) { $value = trim($value); // CSV Injection prevention if (preg_match('/^[=+\-@]/', $value)) { $value = "'".$value; } // Basic XSS prevention (optional if output escaping is consistent) $value = strip_tags($value); // Removes HTML tags entirely $input[$key] = $value; } } return $input; } public function ajaxsubmit(Request $request) { $post = $request->except('_token'); $files = $request->file(); //Log::debug(print_r($files, true)); // if($post['form_id'] == '1663069943-2d45ab0c-ccbe-4047-a77f-bce46b93257a') { // exit; // } foreach($files as $fname => $file) { $post[$fname] = $this->_uploadMedia($request, $fname, 'form/'.$post['form_id'].'/'.$fname); } $post = $this->sanitizeArray($post); if(isset($post['id']) && $post['id']=='') unset($post['id']); $formdata = $request->session()->get('formdata'); if(!$formdata) { $formdata = (object)[]; } $formdata->form_id = $post['form_id']; if(isset($post['user_id']) && $post['user_id'] != '') { $formdata->user_id = $post['user_id']; } if(isset($post['partition']) && $post['partition'] != '') { $formdata->partition = $post['partition']; } if($formdata->form_id == '1740377155-6ef021d0-d8cf-42e6-bc7d-d00743b7b354') { // emcurecv Hospital Enrollment $inputs = $request->input(); list($application, $domain) = explode("-", $formdata->partition); $token = DB::table('users')->select("access_token")->where("domain", $domain)->where("permissions", 'like', '%contact_create%')->orderBy('updated_at', 'desc')->skip(0)->take(1)->get(); Log::debug(print_r($token, true)); $conts = LambdaRequest::getrequest('contact', 'contact/get_all', ['keyword'=>$inputs['hospital_name'], 'search' => '{"type":"hospital"}', 'start' => 0, 'length' => 10000], $token[0]->access_token); Log::debug(print_r($conts, true)); //return response()->json(['status' => 'error']); $exists = false; if($conts->data->count > 0) { foreach($conts->data->items as $item) { if($item->hospital_name == $inputs['hospital_name'] && $item->state == $inputs['state_of_hospital'] && $item->city == $inputs['city_of_hospital']) { $exists = true; } } } Log::debug(print_r($exists, true)); if(!$exists) { $contactdata = [ 'domain' => $domain, 'application' => $application, 'user_id' => $post['user_id'], 'name' => $post['hospital_name'], 'msl_code' => 'HOS_' . strtotime("now").rand(0,99), 'type' => 'hospital', 'hospital_name' => $post['hospital_name'], 'total_no_of_listed_drs_in_hospital' => $post['total_no_of_listed_drs_in_hospital'], 'no_of_beds_in_hospital' => $post['no_of_beds_in_hospital'], 'state' => $post['state_of_hospital'], 'city' => $post['city_of_hospital'], 'suppy_distributor_name_1' => $post['suppy_distributor_name_1'], 'suppy_distributor_name_2' => $post['suppy_distributor_name_2'], ]; $cont = LambdaRequest::postrequest('contact', 'contact/create', $contactdata, $token[0]->access_token); return response()->json(['status' => 'success']); } else { return response()->json(['status' => 'error', 'message' => 'The Hospital you are trying add already exists in the system.', 'description' => 'Please check the added hospital list or change the name' ]); } exit; } if($formdata->form_id == '1750312866-ea213e07-7786-4e99-9e1b-3bb8784ee219') { // gennovadc center/hospital enrollment $inputs = $request->input(); list($application, $domain) = explode("-", $formdata->partition); $token = DB::table('users')->select("access_token")->where("domain", $domain)->where("permissions", 'like', '%contact_create%')->orderBy('updated_at', 'desc')->skip(0)->take(1)->get(); Log::debug(print_r($token, true)); $conts = LambdaRequest::getrequest('contact', 'contact/get_all', ['keyword'=>$inputs['dialysis_centre_hospital_name'], 'start' => 0, 'length' => 10000], $token[0]->access_token); Log::debug(print_r($conts, true)); // return response()->json(['data' => $conts]); $exists = false; if($conts->data->count > 0) { foreach($conts->data->items as $item) { if (strcasecmp(trim($item->hospital_name), trim($inputs['dialysis_centre_hospital_name'])) === 0 && strcasecmp(trim($item->center_type), trim($post['center_type'])) === 0 ) { $exists = true; } } } //Log::debug(print_r($exists, true)); if(!$exists) { $contactdata = [ 'domain' => $domain, 'application' => $application, 'user_id' => $post['user_id'], 'name' => $post['dialysis_centre_hospital_name'], 'msl_code' => 'HOS_' . strtotime("now").rand(0,99), 'hospital_name' => $post['dialysis_centre_hospital_name'], 'center_type' => $post['center_type'], ]; $cont = LambdaRequest::postrequest('contact', 'contact/create', $contactdata, $token[0]->access_token); $post['contact_id'] = $cont->data->item->id; //return response()->json(['status' => 'success']); } else { return response()->json(['status' => 'error', 'message' => 'The Hospital you are trying add already exists in the system.', 'description' => 'Please check the added hospital list or change the name' ]); } //exit; } if($formdata->form_id == '1718178830-d871301e-312b-4a60-9c68-15afa4ce6163') { $exists = false; if(!isset($post['id'])) { $history = LambdaRequest::postrequest('form', 'formentity/getformhistory', ['form_id' => $formdata->form_id, 'user_id' => $formdata->user_id, 'partition' => $formdata->partition ]); foreach($history->data->submissions as $submission) { if(isset($submission->formdata->execution_id) && $submission->formdata->execution_id == $post['execution_id'] && $submission->formdata->no_of_follow_up == $post['no_of_follow_up']) { return response()->json(['status' => 'failure', 'message' => 'You have already submitted for '.$post['no_of_follow_up'].' Follow Up. Please select other option']); } } } if(!isset($post['id']) && $formdata->form_id == '1718178830-d871301e-312b-4a60-9c68-15afa4ce6163') { DB::table('team3_nebyatra_doctors')->where('execution_id', $post['execution_id'])->increment('no_of_followups', 1); DB::table('team3_nebyatra_doctors')->where('execution_id', $post['execution_id'])->update(['last_followup_date' => date('Y-m-d H:i:s', strtotime('now'))] ); } if(!isset($post['id']) && $formdata->form_id == '1718178830-d871301e-312b-4a60-nebmitra-15afa4ce6163') { DB::table('team3_nebyatra_doctors')->where('execution_id', $post['execution_id'])->increment('nm_no_of_followups', 1); DB::table('team3_nebyatra_doctors')->where('execution_id', $post['execution_id'])->update(['nm_last_followup_date' => date('Y-m-d H:i:s', strtotime('now'))] ); } } if($formdata->form_id == '1718178830-d871301e-312b-4a60-9c68-tmfollowup') { $exists = false; $history = LambdaRequest::postrequest('form', 'formentity/getformhistory', ['form_id' => $formdata->form_id, 'user_id' => $formdata->user_id, 'partition' => $formdata->partition ]); foreach($history->data->submissions as $submission) { if($submission->formdata->execution_id == $post['execution_id'] && $submission->formdata->no_of_follow_up == $post['no_of_follow_up']) { return response()->json(['status' => 'failure', 'message' => 'You have already submitted for '.$post['no_of_follow_up'].' Follow Up. Please select other option']); } } if(!isset($post['id'])) { DB::table('team3_nebyatra_doctors')->where('execution_id', $post['execution_id'])->increment('tm_no_of_followups', 1); DB::table('team3_nebyatra_doctors')->where('execution_id', $post['execution_id'])->update(['tm_last_followup_date' => date('Y-m-d H:i:s', strtotime('now'))] ); } } if($formdata->form_id == '1731476724-fa8c01ad-3ec5-4052-8e84-70e4c5a7933e') { $urls = [ '4 to 17 years of age' => 'https://did94hhhcgq1d.cloudfront.net/vgreet/ciclohale/a-4-17-years.png', '6 to 11 years of age 1' => 'https://did94hhhcgq1d.cloudfront.net/vgreet/ciclohale/b-6-11-years.png', '6 to 11 years of age 2' => 'https://did94hhhcgq1d.cloudfront.net/vgreet/ciclohale/c-multicenterstudy.png', '6 to 11 years of age 3' => 'https://did94hhhcgq1d.cloudfront.net/vgreet/ciclohale/d-gina-6-11.png', '12 years of age' => 'https://did94hhhcgq1d.cloudfront.net/vgreet/ciclohale/e-gina-12.png', '12 to 17 years of age' => 'https://did94hhhcgq1d.cloudfront.net/vgreet/ciclohale/f-12-17-years.png' ]; $post_fields = [ 'messaging_product' => 'whatsapp', 'to' => '91'.$post['whatsapp_number'], 'type' => 'template', 'template' => json_encode([ 'name' => 'ciclesonide_clinical_evidence', 'language' => ['code' => 'en'], 'components' => [ [ 'type' => 'header', 'parameters' => [ [ 'type' => 'image', 'image' => [ 'link' => $urls[$post['years_range']] ] ] ] ], [ 'type' => 'body', 'parameters' => [ [ 'type' => 'text', 'text' => $post['doctor_name'] ] ] ] ] ]) ]; Log::debug(print_r($post_fields, true)); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/v20.0/105856779114949/messages'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Authorization: Bearer EAAWVZCWNeZAGMBAIcr8e7kBoWeEUXIQZBWFpm6Dn8FCrAxLBVQWDOvLjiXi20URBMZCxeSnMZCT7tgvZBv4rzjwGZCr6yc6hYovDYbRYHZB50gS3yCdu9aA7k9ZBuZC9X7EkC6uBgcfIZBJogrdOCFuZCoTsJ9LyMevHLhdgnqYAvpGRaO15p5TiqPZBv', ]); curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields); $response = curl_exec( $ch ); $err = curl_error( $ch ); curl_close( $ch ); if ( $err ) { Log::debug(print_r($err, true)); } else { $post['whatsapp_response'] = $response; Log::debug(print_r($response, true)); } } if($formdata->form_id == '1737368490-73a87163-7381-46a6-9fdf-3b11fc49ca3f') { if(isset($post['cresar_bs_launched']) && $post['cresar_bs_launched'] == 'Yes' ) { list($application, $domain) = explode("-", $formdata->partition); $token = DB::table('users')->select("access_token","user_id")->where("domain", $domain)->where("permissions", 'like', '%contact_create%')->orderBy('updated_at', 'desc')->skip(0)->take(1)->get(); $contactdata = [ 'domain' => $domain, 'application' => $application, 'user_id' => $post['user_id'], 'cresar_bs_launched' => 'Yes', 'id' => $post['contact_id'], ]; $cont = LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token[0]->access_token); $post['cresar_bs_launched_count'] = "1"; } } if($formdata->form_id == '1741672502-78ceeb99-b393-47b7-9e3b-850a1d42c204') { list($application, $domain) = explode("-", $formdata->partition); if(isset($post['empacip_launched']) && $post['empacip_launched'] == 'Yes' ) { $token = DB::table('users')->select("access_token","user_id")->where("domain", $domain)->where("permissions", 'like', '%contact_create%')->orderBy('updated_at', 'desc')->skip(0)->take(1)->get(); $contactdata = [ 'domain' => $domain, 'application' => $application, 'user_id' => $post['user_id'], 'empacip_launched' => 'Yes', 'id' => $post['contact_id'], ]; $cont = LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token[0]->access_token); $post['empacip_launched_count'] = "1"; } } if($formdata->form_id == '1741694174-665474ba-4492-4e00-9c87-78ccea51e6a9') { list($application, $domain) = explode("-", $formdata->partition); $contactdata = [ 'domain' => $domain, 'application' => $application, 'user_id' => $post['user_id'], 'id' => $post['contact_id'], ]; $toupdate = false; if(isset($post['empa_launched']) && $post['empa_launched'] == 'Yes' ) { $token = DB::table('users')->select("access_token","user_id")->where("domain", $domain)->where("permissions", 'like', '%contact_create%')->orderBy('updated_at', 'desc')->skip(0)->take(1)->get(); $contactdata['empa_launched'] = 'Yes'; //$cont = LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token[0]->access_token); $post['empa_launched_count'] = "1"; $toupdate = true; } if(!isset($post['empa_conversion']) && isset($post['no_of_empa_rx_generated']) && (int)$post['no_of_empa_rx_generated'] > 0 ) { $token = DB::table('users')->select("access_token","user_id")->where("domain", $domain)->where("permissions", 'like', '%contact_create%')->orderBy('updated_at', 'desc')->skip(0)->take(1)->get(); $contactdata['empa_conversion'] = 'Yes'; $post['empa_conversion_count'] = "1"; $toupdate = true; } if($toupdate) { $cont = LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token[0]->access_token); } } if($formdata->form_id == '1718178830-d871301e-312b-4a60-nebmitra-15afa4ce6163') { $exists = false; // if(!isset($post['id'])) { // $history = LambdaRequest::postrequest('form', 'formentity/getformhistory', ['form_id' => $formdata->form_id, 'user_id' => $formdata->user_id, 'partition' => $formdata->partition ]); // foreach($history->data->submissions as $submission) { // if(isset($submission->formdata->execution_id) && $submission->formdata->execution_id == $post['execution_id'] && $submission->formdata->no_of_follow_up == $post['no_of_follow_up']) { // return response()->json(['status' => 'failure', 'message' => 'You have already submitted for '.$post['no_of_follow_up'].' Follow Up. Please select other option']); // } // } // } if(!isset($post['id'])) { DB::table('team3_nebmitra_doctors')->where('id', $post['doctor_id'])->increment('no_of_followups', 1); DB::table('team3_nebmitra_doctors')->where('id', $post['doctor_id'])->update(['last_followup_date' => date('Y-m-d H:i:s', strtotime('now'))] ); } else if(isset($post['remarks_rejection_reason'])) { // $notification_data = [ // 'domain' => 'team3', // 'application' => 'team3', // 'user_id' => 'team3', // 'title' => 'team3', // 'description' => 'team3', // 'payload' => [ // 'type' => // ] // ]; // LambdaRequest::postrequest('ums', 'notification/create', ['form_id' => $formdata->form_id, 'user_id' => $formdata->user_id, 'partition' => $formdata->partition ]); } } if($formdata->form_id == '1747214698-91cb34fd-d1fb-49cb-b90d-139ab0699c54') { list($application, $domain) = explode("-", $formdata->partition); $token = DB::table('users')->select("access_token")->where("domain", $domain)->where("permissions", 'like', '%contact_create%')->orderBy('updated_at', 'desc')->skip(0)->take(1)->get(); $contactdata = [ 'domain' => $domain, 'application' => $application, 'nursing_home_format_enrollment' => 'yes', 'name' => $post['nursing_home_name'], 'state' => $post['state'], 'user_id' => $post['user_id'], 'msl_code' => strtotime("now").'-'.rand(1000,9999), 'current_business' => $post['current_businessmonth_at_the_time_of_enrollment'], 'potential_business' => $post['respi_potential_businessmonth_at_the_time_of_enrollment'] ]; $cont = LambdaRequest::postrequest('contact', 'contact/create', $contactdata, $token[0]->access_token); Log::debug(print_r($post, true)); return response()->json(['status' => 'success', 'data'=> $cont]); } if($formdata->form_id == '1747907662-381b8a4b-b944-493c-a242-37ef94e600dd') { list($application, $domain) = explode("-", $formdata->partition); $token = DB::table('users')->select("access_token")->where("domain", $domain)->where("permissions", 'like', '%contact_create%')->orderBy('updated_at', 'desc')->skip(0)->take(1)->get(); $contactdata = [ 'domain' => $domain, 'application' => $application, 'hl_associate_enrollment' => 'yes', 'name' => $post['hl_associate_name'], 'state' => $post['state'], 'user_id' => $post['user_id'], 'msl_code' => strtotime("now").'-'.rand(1000,9999), 'nebulization_potential_business' => $post['nebulization_potential_businessmonth_value_at_the_time_of_enrollment'], 'expected_nebulization_business' => $post['expected_nebulization_businessmonth_value_at_the_time_of_enrollment'] ]; $cont = LambdaRequest::postrequest('contact', 'contact/create', $contactdata, $token[0]->access_token); Log::debug(print_r($post, true)); Log::debug(print_r($contactdata, true)); return response()->json(['status' => 'success', 'data'=> $cont]); } if($formdata->form_id == '1744959804-4f16d406-e57e-4ba8-a805-231422c7a2bf') { $formdata->form_id = '1745558346-87594722-9a7c-41b8-9fb9-4f37ab631133'; if(isset($post['contact_id']) && $post['contact_id'] == 'other'){ list($application, $domain) = explode("-", $formdata->partition); $token = DB::table('users')->select("access_token")->where("domain", $domain)->where("permissions", 'like', '%contact_create%')->orderBy('updated_at', 'desc')->skip(0)->take(1)->get(); $contactdata = [ 'domain' => $domain, 'application' => $application, 'name' => $post['other_doctor_name'], 'unique_doctor_code' => $post['unique_doctor_code'], 'user_id' => $post['user_id'], 'msl_code' => strtotime("now").'-'.rand(1000,9999), ]; $cont = LambdaRequest::postrequest('contact', 'contact/create', $contactdata, $token[0]->access_token); Log::debug(print_r($cont, true)); $post['contact_id'] = $cont->data->item->id; Log::debug(print_r($post, true)); Log::debug(print_r($contactdata, true)); // echo "
";
                // print_r($post);
                // exit;
            }
            
        }

        if($formdata->form_id == '1748599846-8198a6e1-49f2-4965-b8b3-35cbfa83364e') {
            // echo "
";
            // print_r($formdata);
            // exit;
            DB::table('team3_nebmitra_doctors')
            ->insert([
                'user_id'=> $post['user_id'],
                'hierarchy_id' => $post['hierarchy_id'],
                'doctor_name' => $post['doctor_name'],
                'mobile_number' => $post['mobile_number'],
                'speciality' => $post['speciality'],
                'degree' => $post['degree'],
                'type' => 'doctor',
                'location' => $post['location'],
                'micro_interior'=> $post['micro_interior'],
                'state'=> $post['state']
            ]);
            return response()->json(['status' => 'success']);
        }

         if($formdata->form_id == '1750914801-153443b9-94d0-4dcb-b3f3-4fa11588a0a9') {

            $userid = $post['user_id'];

            $depot = DB::table('team3_neblogistics_tms')
            ->join('team3_neblogistics_depot', 'team3_neblogistics_tms.depot_id', '=', 'team3_neblogistics_depot.id')
            ->where('team3_neblogistics_tms.user_id', $userid)
            ->select('team3_neblogistics_depot.id', 'team3_neblogistics_depot.name')
            ->first();
            
            // $depot = false;

            if(!$depot){
              return response()->json(['status' => 'mapping error', 'message' => 'Data not submitted. You are not mapped to a depot. Please contact system administrator']);  
            }

            $datatosave = [
                    //'record_id' => '',
                    // 'request_type' => $post[''], 
                    'emp_id' => $post['emp_id'], 
                    'user_id' => $post['user_id'],
                    'hierarchy_id' => $post['hierarchy_id'],
                    'emp_name' => $post['employee_name'], 
                    'emp_phone' => $post['employee_phone'], 
                    'emp_email' => $post['employee_email'], 
                    'abm_name' => $post['abm_name'], 
                    'abm_email' => $post['abm_email'], 
                    'rbm_name' => $post['rbm_name'], 
                    'msl_code' => $post['msl_code'],
                    'form_submit_type' => $post['form_submit_type'],
                    'doctor_name' => $post['dr_name'], 
                    'doctor_phone' => $post['doctor_mobile_number'], 
                    'doctor_speciality' => $post['speciality'], 
                    'nebulizer_purpose' => $post['for_what_purpose_nebulisers_will_be_used_by_dr'], 
                    // 'patient_name' => $post[''], 
                    // 'patient_phone' => $post[''], 
                    'type_of_nebulizer' => $post['type_of_nebuliser'], 
                    'no_of_nebulizer' => $post['no_of_nebulizer'], 
                    'value_of_parcel' => $post['value_of_the_parcel'], 
                    // 'address_type' => $post[''], 
                    'address_building' => $post['building_name'], 
                    'address_line_1' => $post['address_line_1'], 
                    'address_line_2' => $post['address_line_2'], 
                    // 'address_landmark' => $post[''], 
                    'address_state' => $post['state'], 
                    'address_city' => $post['city'], 
                    'address_pin_code' => $post['pin_code'], 
                    'clinic_hospital_name' => $post['clinic_hospital_home_name'],
                    // 'address_landmark' => $post['landmark'],
                    // 'pickup_type' => $post[''], 
                    // 'pickup_building' => $post[''], 
                    // 'pickup_line_1' => $post[''], 
                    // 'pickup_line_2' => $post[''], 
                    // 'pickup_landmark' => $post[''], 
                    // 'pickup_state' => $post[''], 
                    // 'pickup_city' => $post[''], 
                    // 'pickup_pin_code' => $post[''], 
                    'status' => $post['status'],
                    // 'rejected_reason' => $post[''], 
                    'team' => $post['team'], 
                    'geolocation_latitude' => $post['geolocation_latitude'] ?? null, 
                    'geolocation_longitude' => $post['geolocation_longitude'] ?? null, 
                    'geolocation_address' => $post['geolocation_address'] ?? null, 
                    'geolocation_json' => $post['geolocation_json'] ?? null,
                    'depot_id' => $depot->id,
                    'depot_name' => $depot->name
            ];

            Log::debug(print_r($datatosave, true));

            if (!empty($post['upload_request_letter'])) {
                $datatosave['request_letter'] = $post['upload_request_letter'];
            } elseif (!empty($post['existing_letter'])) {
                $datatosave['request_letter'] = $post['existing_letter'];
            }

            $request->session()->put('formdata', $formdata);
            if(isset($formdata) && !empty($formdata) && $formdata->user_id != '') {
                $post = $this->processformdata($formdata->form_id, $post, $formdata->user_id, $formdata->partition);
                Log::debug(print_r($post, true));
                $finfo = LambdaRequest::postrequest('form', 'formentity/submitform', ['formdata' => $post, 'entity_id' => $formdata->form_id, 'user_id' => $formdata->user_id, 'partition' => $formdata->partition ]);
                Log::debug(print_r($finfo, true));
                if($finfo->status == 'success') {

                    if (!empty($post['submission_id'])) {
                        DB::table('neblogistic')->where('submission_id', $post['submission_id'])->update($datatosave);
                    } else {
                        $datatosave['submission_id'] = $finfo->data->submission->id;
                        DB::table('neblogistic')->insertGetId($datatosave);
                    }
                    return response()->json(['status' => 'success']);
                } else {
                    if($finfo->statusCode == 401) {
                        return response()->json(['status' => 'failure', 'message' => $finfo->data ]);
                    }
                    return response()->json(['status' => 'failure']);
                }          
            } else {
                return response()->json(['status' => 'failure']);
            }

            
        }

        if($formdata->form_id == '1748871942-6e9199c8-89c4-44ac-8c70-5d5df140d70a') {
            // echo "
";
            // print_r($formdata);
            // exit;
            DB::table('team3_nebmitra_doctors')
            ->insert([
                'user_id'=> $post['user_id'],
                'hierarchy_id' => $post['hierarchy_id'],
                'doctor_name' => $post['chemist_name'],
                'mobile_number' => $post['mobile_number'],
                // 'speciality' => $post['speciality'],
                // 'degree' => $post['degree'],
                'type' => 'chemist',
                'location' => $post['location'],
                'micro_interior'=> $post['micro_interior'],
                'state'=> $post['state']
            ]);
            return response()->json(['status' => 'success']);
        }

        Log::debug(print_r($formdata, true));
        $request->session()->put('formdata', $formdata);
        if(isset($formdata) && !empty($formdata) && $formdata->user_id != '') {
            $post = $this->processformdata($formdata->form_id, $post, $formdata->user_id, $formdata->partition);
            Log::debug(print_r($post, true));
            $finfo = LambdaRequest::postrequest('form', 'formentity/submitform', ['formdata' => $post, 'entity_id' => $formdata->form_id, 'user_id' => $formdata->user_id, 'partition' => $formdata->partition ]);
            
            Log::debug(print_r($finfo, true));
            if($finfo->status == 'success') {
                return response()->json(['status' => 'success']);
            } else {
                if($finfo->statusCode == 401) {
                    return response()->json(['status' => 'failure', 'message' => $finfo->data ]);
                }
                return response()->json(['status' => 'failure']);
            }          
        } else {
            return response()->json(['status' => 'failure']);
        }
    }

    public function ajaxsubmitmultiple(Request $request) {
        $post = $request->except('_token');
        $formdata = $request->session()->get('formdata');
        $formdata->form_id = $post['form_id'];
        // if($formdata->partition == 'rapport-copd') {
        //     return response()->json(['status' => 'failure']);
        // }
        if(isset($post['user_id']) && $post['user_id'] != '') {
            $formdata->user_id = $post['user_id'];
        }
        $request->session()->put('formdata', $formdata);
        Log::debug(print_r($formdata, true));

        $files = $request->file();
        foreach($files as $fname => $file) {
            $post[$fname] = $this->_uploadMedia($request, $fname, 'form/'.$post['form_id'].'/'.$fname);
        }

        if($formdata->form_id == '1741323247-1a1a77b7-ba13-40db-a8bf-9f56fa1181ed') {
            $post['upload_screening_data'] = explode(",", $post['upload_screening_data']);
        }
        Log::debug(print_r($post, true));

        if($formdata->form_id == '1728057395-75288ee5-a1a6-4210-9073-430d96fbc636') {
            $contacts = [];
            foreach($post['contact_id'] as $i => $contact_id) {
                $contacts[] = ['contact_id' => $contact_id, 'pulmosmart_g' => isset($post['pulmosmart_g'][$i])?'Yes':'No' ];
            }
            list($application, $domain) = explode("-", $formdata->partition);
            $token = DB::table('users')->select("access_token")->where("domain", $domain)->where("permissions", 'like', '%contact_create%')->orderBy('updated_at', 'desc')->skip(0)->take(1)->get();
            $history = LambdaRequest::postrequest('form', 'formentity/getformhistory', ['form_id' => $formdata->form_id, 'user_id' => $post['user_id'], 'partition' => 'rapport-pulmocare' ]);
            $pulmosmart_g = [];
            $id = [];
            foreach($contacts as $contact) {
                $contactdata = [
                    'domain' => $domain,
                    'application' => $application,
                    'user_id' => $post['user_id'],
                    //'hierarchy' => $post['hierarchy_id'],
                    'pulmosmart_g' => $contact['pulmosmart_g'],
                    'id' => $contact['contact_id'],
                ];
                $cont = LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token[0]->access_token);
                if($contact['pulmosmart_g'] == 'Yes') {
                    $pulmosmart_g[] = 'Yes';
                } else {
                    $pulmosmart_g[] = 'No';
                }
                $found = false;
                foreach($history->data->submissions as $his) {
                    if($his->formdata->cont_id == $contact['contact_id']) {
                        $id[] = $his->id;
                        $found = true;
                    }
                }
                if(!$found) {
                    $id[] = '';
                }
            }
            $post['id'] = $id;
            $post['pulmosmart_g'] = $pulmosmart_g;

            //return response()->json(['status' => 'success', 'history' => $history, 'post' => $post]);
        }

        if($formdata->form_id == '1729328418-92e5a1fd-8a62-4ba5-a0a7-99362654159d') {
            $contacts = [];
            foreach($post['contact_id'] as $i => $contact_id) {
                $contacts[] = [ 'contact_id' => $contact_id,
                                'eptus_adboard' => isset($post['eptus_adboard'][$i])?'Yes':'No',
                                'sitazit_ddm_adboard' => isset($post['sitazit_ddm_adboard'][$i])?'Yes':'No',
                                'sitazit_ddm_pmos' => isset($post['sitazit_ddm_pmos'][$i])?'Yes':'No',
                                'ziten_pmos' => isset($post['ziten_pmos'][$i])?'Yes':'No',
                                'mr' => isset($post['mr'][$i])?'Yes':'No',
                                'eptus_webinar_speakerattendee' => isset($post['eptus_webinar_speakerattendee'][$i])?'Yes':'No',
                                'eptus_rtm_speakerattendee' => isset($post['eptus_rtm_speakerattendee'][$i])?'Yes':'No',
                                'ziten_ecme_speakerattendee' => isset($post['ziten_ecme_speakerattendee'][$i])?'Yes':'No',
                                'eptus_isp_attendee' => isset($post['eptus_isp_attendee'][$i])?'Yes':'No',
                                'sitazit_ddm_isp_attendee' => isset($post['sitazit_ddm_isp_attendee'][$i])?'Yes':'No',
                                'whd_clinic' => isset($post['whd_clinic'][$i])?'Yes':'No',
                                'wdd_clinic' => isset($post['wdd_clinic'][$i])?'Yes':'No',
                                'social_connect' => isset($post['social_connect'][$i])?'Yes':'No',
                                'hidden_gems' => isset($post['hidden_gems'][$i])?'Yes':'No',
                            ];
            }
            list($application, $domain) = explode("-", $formdata->partition);
            $token = DB::table('users')->select("access_token")->where("domain", $domain)->where("permissions", 'like', '%contact_create%')->orderBy('updated_at', 'desc')->skip(0)->take(1)->get();
            
            foreach($contacts as $contact) {
                $contactdata = [
                    'domain' => $domain,
                    'application' => $application,
                    'user_id' => $post['user_id'],
                    //'hierarchy' => $post['hierarchy_id'],
                    'eptus_adboard' => $contact['eptus_adboard'],
                    'mr' => $contact['mr'],
                    'sitazit_ddm_adboard' => $contact['sitazit_ddm_adboard'],
                    'sitazit_ddm_pmos' => $contact['sitazit_ddm_pmos'],
                    'ziten_pmos' => $contact['ziten_pmos'],
                    'eptus_webinar_speakerattendee' => $contact['eptus_webinar_speakerattendee'],
                    'eptus_rtm_speakerattendee' => $contact['eptus_rtm_speakerattendee'],
                    'ziten_ecme_speakerattendee' => $contact['ziten_ecme_speakerattendee'],
                    'eptus_isp_attendee' => $contact['eptus_isp_attendee'],
                    'sitazit_ddm_isp_attendee' => $contact['sitazit_ddm_isp_attendee'],
                    'whd_clinic' => $contact['whd_clinic'],
                    'wdd_clinic' => $contact['wdd_clinic'],
                    'social_connect' => $contact['social_connect'],
                    'hidden_gems' => $contact['hidden_gems'],
                    'id' => $contact['contact_id'],
                ];
                $cont = LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token[0]->access_token);
            }
            return response()->json(['status' => 'success']);
        }

        if($formdata->form_id == '1716267411-74ef7199-6298-4bae-8c8b-c069a405c864') {
            $contacts = [];
            foreach($post['contact_id'] as $i => $contact_id) {
                $contacts[] = ['contact_id' => $contact_id, 'proxym_tuesday' => isset($post['proxym_tuesday'][$i])?'Yes':'No', 'ferium_xt_thursday' => isset($post['ferium_xt_thursday'][$i])?'Yes':'No', 'galact_saturday' => isset($post['galact_saturday'][$i])?'Yes':'No' ];
            }
            list($application, $domain) = explode("-", $formdata->partition);
            $token = DB::table('users')->select("access_token")->where("domain", $domain)->where("permissions", 'like', '%contact_create%')->orderBy('updated_at', 'desc')->skip(0)->take(1)->get();
            
            foreach($contacts as $contact) {
                $contactdata = [
                    'domain' => $domain,
                    'application' => $application,
                    'user_id' => $post['user_id'],
                    'hierarchy' => $post['hierarchy_id'],
                    'proxym_tuesday' => $contact['proxym_tuesday'],
                    'ferium_xt_thursday' => $contact['ferium_xt_thursday'],
                    'galact_saturday' => $contact['galact_saturday'],
                    'id' => $contact['contact_id'],
                ];
                $cont = LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token[0]->access_token);
            }
            return response()->json(['status' => 'success']);
        }

        //["rtm","telma_ln_ecme","zita_ecme"]
        if($formdata->form_id == '1721281521-a4a857d7-84d7-4e4c-9df3-4e9c9f999d64') {
            $contacts = [];
            foreach($post['contact_id'] as $i => $contact_id) {
                $contacts[] = ['contact_id' => $contact_id, 'zita_ecme' => isset($post['zita_ecme'][$i])?'Yes':'No', 'telma_ln_ecme' => isset($post['telma_ln_ecme'][$i])?'Yes':'No', 'rtm' => isset($post['rtm'][$i])?'Yes':'No' ];
            }
            list($application, $domain) = explode("-", $formdata->partition);
            $token = DB::table('users')->select("access_token")->where("domain", $domain)->where("permissions", 'like', '%contact_create%')->orderBy('updated_at', 'desc')->skip(0)->take(1)->get();
            $post['contact_id'] = [];
            $post['zita_ecme'] = [];
            $post['telma_ln_ecme'] = [];
            $post['rtm'] = [];
            foreach($contacts as $i => $contact) {
                $contactdata = [
                    'domain' => $domain,
                    'application' => $application,
                    'user_id' => $post['user_id'],
                    //'hierarchy' => $post['hierarchy_id'],
                    'zita_ecme' => $contact['zita_ecme'],
                    'telma_ln_ecme' => $contact['telma_ln_ecme'],
                    'rtm' => $contact['rtm'],
                    'id' => $contact['contact_id'],
                ];
                $cont = LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token[0]->access_token);
                $post['contact_id'][$i] = $contact['contact_id'];
                $post['zita_ecme'][$i] = $contact['zita_ecme'];
                $post['telma_ln_ecme'][$i] = $contact['telma_ln_ecme'];
                $post['rtm'][$i] = $contact['rtm'];
            }
            return response()->json(['status' => 'success']);
        }

        if($formdata->form_id == '1750240655-f1f14358-8e47-4583-975f-655d081db904') {
            // echo "
";
            // print_r($post);
            // exit;
            $contacts = [];
            foreach($post['contact_id'] as $i => $contact_id) {
                $contacts[] = ['contact_id' => $contact_id, 'consent_given_for_camp' => isset($post['obesity_screening_camp'][$i])?'Yes':'No'];
            }
            
            // return response()->json(['data' => $contacts]);
            
            list($application, $domain) = explode("-", $formdata->partition);
            $token = DB::table('users')->select("access_token")->where("domain", $domain)->where("permissions", 'like', '%contact_create%')->orderBy('updated_at', 'desc')->skip(0)->take(1)->get();
            $post['contact_id'] = [];
            $post['consent_given_for_camp'] = [];
            foreach($contacts as $i => $contact) {
                $contactdata = [
                    'domain' => $domain,
                    'application' => $application,
                    'user_id' => $post['user_id'],
                    'consent_given_for_camp' => $contact['consent_given_for_camp'],
                    'id' => $contact['contact_id'],
                ];
                $cont = LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token[0]->access_token);
            }
            return response()->json(['status' => 'success']);
        }

        if($formdata->form_id == '1716267411-74ef7199-6298-4bae-c2c-c069a405c864') {
            $contacts = [];
            foreach($post['contact_id'] as $i => $contact_id) {
                $contacts[] = ['contact_id' => $contact_id, 'c2c' => isset($post['c2c'][$i])?'Yes':'No' ];
            }

            list($application, $domain) = explode("-", $formdata->partition);
            $token = DB::table('users')->select("access_token")->where("domain", $domain)->where("permissions", 'like', '%contact_create%')->orderBy('updated_at', 'desc')->skip(0)->take(1)->get();
            
            foreach($contacts as $contact) {
                $contactdata = [
                    'domain' => $domain,
                    'application' => $application,
                    'user_id' => $post['user_id'],
                    'hierarchy' => $post['hierarchy_id'],
                    'c2c' => $contact['c2c'],
                    'id' => $contact['contact_id'],
                ];
                $cont = LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token[0]->access_token);
            }
            return response()->json(['status' => 'success']);
        }

        if($formdata->form_id == '1724905805-b20d0e50-0370-4b1b-8352-a16365cc624c') {
            $contacts = [];
            foreach($post['contact_id'] as $i => $contact_id) {
                if(isset($post['orofer_fcm_cme'][$i]) && $post['orofer_fcm_cme'][$i] ==  'Yes') {
                    $contacts[] = ['contact_id' => $contact_id, 'orofer_fcm_cme' => isset($post['orofer_fcm_cme'][$i])?'Yes':'No' ];
                }
            }

            list($application, $domain) = explode("-", $formdata->partition);
            $token = DB::table('users')->select("access_token")->where("domain", $domain)->where("permissions", 'like', '%contact_create%')->orderBy('updated_at', 'desc')->skip(0)->take(1)->get();
            
            foreach($contacts as $contact) {
                $contactdata = [
                    'domain' => $domain,
                    'application' => $application,
                    'user_id' => $post['user_id'],
                    'hierarchy' => $post['hierarchy_id'],
                    'orofer_fcm_cme' => $contact['orofer_fcm_cme'],
                    'id' => $contact['contact_id'],
                ];
                $cont = LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token[0]->access_token);
            }
            return response()->json(['status' => 'success']);
        }

        if($formdata->form_id == '1723015306-c8d90868-1c50-4820-ab96-474cdff8e543') {
            $contacts = [];
            foreach($post['contact_id'] as $i => $contact_id) {
                $contacts[] = ['contact_id' => $contact_id, 'glycoquic_f' => isset($post['glycoquic_f'][$i])?'Yes':'No' ];
            }

            list($application, $domain) = explode("-", $formdata->partition);
            $token = DB::table('users')->select("access_token")->where("domain", $domain)->where("permissions", 'like', '%contact_create%')->orderBy('updated_at', 'desc')->skip(0)->take(1)->get();
            
            foreach($contacts as $contact) {
                $contactdata = [
                    'domain' => $domain,
                    'application' => $application,
                    'user_id' => $post['user_id'],
                    'glycoquic_f' => $contact['glycoquic_f'],
                    'id' => $contact['contact_id'],
                ];
                $cont = LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token[0]->access_token);
            }
            return response()->json(['status' => 'success']);
        }

        if($formdata->form_id == '1713426268-c89f38eb-ec32-43ba-a81b-b690a8f90d6a') {
            $existing = DB::table('team3_nebyatra_doctors')->select("mobile_number", "doctor_name")->where('user_id', $formdata->user_id)->get();
            $existing_mobile = [];
            $existing_doctors = [];
            foreach($existing as $exi) {
                $existing_mobile[] = $exi->mobile_number;
                $existing_doctors[] = $exi->doctor_name;
            }
            if(is_array($post['doctor_name']) ) {
                $matched_phones = [];
                $matched_names = [];
                foreach($post['doctor_name'] as $dn) {
                    if(in_array($dn, $existing_doctors)) {
                        $matched_names[] = $dn;
                    }
                }
                foreach($post['mobile_number'] as $dn) {
                    if(in_array($dn, $existing_mobile)) {
                        $matched_phones[] = $dn;
                    }
                }
                if(sizeof($matched_names) > 0 || sizeof($matched_phones) > 0) {
                    $msg = 'Some Mobile numbers or Doctor names you entered already exists.';
                    if(sizeof($matched_names) > 0 ) {
                        $msg .= ' Duplicate doctor names are : '.implode(', ', $matched_names);
                    }
                    if(sizeof($matched_phones) > 0 ) {
                        $msg .= ' Duplicate mobile numbers are : '.implode(', ', $matched_phones);
                    }
                    return response()->json(['status' => 'failure', 'message' => $msg]);
                }
            }
        }
        
        if($formdata->form_id == '1724650115-d03fe369-7c66-478b-8e99-c9fd9dab9dc1') {
            $contacts = [];
            list($application, $domain) = explode("-", $formdata->partition);
            $contLen = isset($post['contact_id']) ? sizeof($post['contact_id']) : 0;
            $token = DB::table('users')->select("access_token")->where("domain", $domain)->where("permissions", 'like', '%contact_create%')->orderBy('updated_at', 'desc')->skip(0)->take(1)->get();
            if(isset($post['doctor_name'])) {
                foreach($post['doctor_name'] as $i => $doctor_name) {
                    $contactdata = [
                        'domain' => $domain,
                        'application' => $application,
                        'user_id' => $post['user_id'],
                        'name' => $doctor_name,
                        'allergy_care' => 'Yes',
                        'msl_code' => $post['doctor_msl'][$i],
                    ];
                    $cont = LambdaRequest::postrequest('contact', 'contact/create', $contactdata, $token[0]->access_token);
                    $post['contact_id'][$contLen] = $cont->data->item->id;
                    $post['msl_code'][$contLen] = $cont->data->item->msl_code;
                    $post['distributed_the_coupons'][$contLen] = isset($post['doctor_distributed'][$i]) ? $post['doctor_distributed'][$i] : '';
                    $contLen++;
                }
                unset($post['doctor_name']);
                unset($post['doctor_msl']);
                unset($post['doctor_distributed']);
            }
            Log::debug(print_r($post, true));
            //exit;
        }

        if($formdata->form_id == '1724855317-a89d683c-b91a-4a62-95c1-3edc589f6d30') {
            $brand_name=[];
            $company_name=[];
            $qty_cipla_brand=[];
            $competitor_brand=[];
            $qty_of_competitor_brand=[];
            $net_value=[];
            $scheme=[];
            $bb = '';
            foreach($post['brand_name'] as $i => $brand) {
                if($post['qty_of_competitor_brand'][$i] > 0 || $post['net_value'][$i] > 0) {
                    $brand_name[] = $brand;
                    $company_name[] = $post['company_name'][$i];
                    $qty_cipla_brand[] = ($bb != $brand) ? $post['qty_cipla_brand'][$i] : 0;
                    $competitor_brand[] = $post['competitor_brand'][$i];
                    $qty_of_competitor_brand[] = $post['qty_of_competitor_brand'][$i];
                    $net_value[] = $post['net_value'][$i];
                    $scheme[] = $post['scheme'][$i];
                    $bb = $brand;
                }
            }
            $post['brand_name'] = $brand_name;
            $post['company_name'] = $company_name;
            $post['qty_cipla_brand'] = $qty_cipla_brand;
            $post['competitor_brand'] = $competitor_brand;
            $post['qty_of_competitor_brand'] = $qty_of_competitor_brand;
            $post['net_value'] = $net_value;
            $post['scheme'] = $scheme;

            unset($post['brand_brand_name']);
            unset($post['brand_qty_cipla_brand']);
            $post['speciality'] = implode(',', $post['speciality']);
        }

        if($formdata->form_id == '1733208092-c845d632-06b3-44a7-8056-d652b4d323b2') {
            $contacts = [];
            foreach($post['contact_id'] as $i => $contact_id) {
                $contacts[] = ['contact_id' => $contact_id, 'gfb_dpi' => isset($post['gfb_dpi'][$i])?'Yes':'No' ];
            }

            list($application, $domain) = explode("-", $formdata->partition);
            $token = DB::table('users')->select("access_token")->where("domain", $domain)->where("permissions", 'like', '%contact_create%')->orderBy('updated_at', 'desc')->skip(0)->take(1)->get();
            
            foreach($contacts as $contact) {
                $contactdata = [
                    'domain' => $domain,
                    'application' => $application,
                    'user_id' => $post['user_id'],
                    'gfb_dpi' => $contact['gfb_dpi'],
                    'id' => $contact['contact_id'],
                ];
                $cont = LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token[0]->access_token);
            }
            return response()->json(['status' => 'success']);
        }

        if($formdata->form_id == '1733913729-781fd9c1-7921-45b8-8df4-9a5488e25e83') {
            $contacts = [];
            foreach($post['contact_id'] as $i => $contact_id) {
                $contacts[] = ['contact_id' => $contact_id, 'innospacer_dr' => isset($post['innospacer_dr'][$i])?'Yes':'No' ];
            }

            list($application, $domain) = explode("-", $formdata->partition);
            $token = DB::table('users')->select("access_token")->where("domain", $domain)->where("permissions", 'like', '%contact_create%')->orderBy('updated_at', 'desc')->skip(0)->take(1)->get();
            
            foreach($contacts as $contact) {
                $contactdata = [
                    'domain' => $domain,
                    'application' => $application,
                    'user_id' => $post['user_id'],
                    'innospacer_dr' => $contact['innospacer_dr'],
                    'id' => $contact['contact_id'],
                ];
                $cont = LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token[0]->access_token);
            }
            return response()->json(['status' => 'success']);
        }

        if($formdata->form_id == '1743150903-b86a4a1b-85b7-48f6-8f43-57ac709ae8a8') {
            $contacts = [];
            foreach($post['contact_id'] as $i => $contact_id) {
                $contacts[] = ['contact_id' => $contact_id, 'voltido_lhc' => isset($post['voltido_lhc'][$i])?'Yes':'No' ];
            }

            list($application, $domain) = explode("-", $formdata->partition);
            $token = DB::table('users')->select("access_token")->where("domain", $domain)->where("permissions", 'like', '%contact_create%')->orderBy('updated_at', 'desc')->skip(0)->take(1)->get();
            
            foreach($contacts as $contact) {
                $contactdata = [
                    'domain' => $domain,
                    'application' => $application,
                    'user_id' => $post['user_id'],
                    'voltido_lhc' => $contact['voltido_lhc'],
                    'id' => $contact['contact_id'],
                ];
                $cont = LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token[0]->access_token);
            }
            return response()->json(['status' => 'success']);
        }

        if($formdata->form_id == '1746001897-24df50bc-525b-4e7b-869b-0e7f245d4892') {
            $contacts = [];
            foreach($post['contact_id'] as $i => $contact_id) {
                if (isset($post['ardc_bf_competition_dr_list_check'][$i])) {
                    $contacts[] = $contact_id;
                    //$ardc_bf_competition[] = $post['ardc_bf_competition_dr_list_check'][$i];
                }
            }
            $post['contact_id'] = $contacts;
            // Log::debug(print_r($post, true));
            // Log::debug(json_encode( ['formdata' => $post, 'entity_id' => $post['form_id'], 'user_id' => $formdata->user_id, 'partition' => $formdata->partition ]));
            // echo "
";
            // print_r($post);
            // exit;
        }

        if($formdata->form_id == '1747894284-6839e2eb-810b-4b3d-84d4-9f0e74273e03') {
            $contacts = [];
            foreach($post['contact_id'] as $i => $contact_id) {
                if (isset($post['voltido_trio_15_dr_tagging'][$i])) {
                    $contacts[] = $contact_id;
                }
            }
            $post['contact_id'] = $contacts;
            // echo "
";
            // print_r($post);
            // exit;

        }

        if($formdata->form_id == '1745215404-0264587a-e7ce-4039-83c7-74d215e23785') {
            $contacts = [];
            foreach($post['contact_id'] as $i => $contact_id) {
                if (isset($post['smart_clinic'][$i])) {
                    $contacts[] = $contact_id;
                    //$ardc_bf_competition[] = $post['ardc_bf_competition_dr_list_check'][$i];
                }
            }
            $post['contact_id'] = $contacts;
            //return response()->json(['status' => 'success']);
        }

        if($formdata->form_id == '1749123523-2d5a05d5-5a4b-42be-90cd-c5d016c53222') {
            $contacts = [];
            foreach($post['contact_id'] as $i => $contact_id) {
                if (isset($post['ardc_bf_collaboration'][$i])) {
                    $contacts[] = $contact_id;
                }
            }
            $post['contact_id'] = $contacts;
        }

       

        // if($formdata->form_id == '1751877063-4f70951b-2d8a-45d7-904e-677fa469d30c') {
        //     $contacts = [];
        //     foreach($post['contact_id'] as $i => $contact_id) {
        //         if (isset($post['voltido_trio_patient'][$i])) {
        //             $contacts[] = $contact_id;
        //         }
        //     }
        //     $post['contact_id'] = $contacts;
        // }

        // if($formdata->form_id == '1751877063-4f70951b-2d8a-45d7-904e-677fa469d30c') {
        //     $contacts = [];
        //     foreach($post['contact_id'] as $i => $contact_id) {
        //         if (isset($post['voltido_trio_patient'][$i])) {
        //         $contacts[] = ['contact_id' => $contact_id, 'voltido_trio_patient' => isset($post['voltido_trio_patient'][$i])?'Yes':'No' ];
        //         }    
        //     }

        //     list($application, $domain) = explode("-", $formdata->partition);
        //     $token = DB::table('users')->select("access_token")->where("domain", $domain)->where("permissions", 'like', '%contact_create%')->orderBy('updated_at', 'desc')->skip(0)->take(1)->get();
            
        //     foreach($contacts as $contact) {
        //         $contactdata = [
        //             'domain' => $domain,
        //             'application' => $application,
        //             'user_id' => $post['user_id'],
        //             'voltido_trio_patient' => $contact['voltido_trio_patient'],
        //             'id' => $contact['contact_id'],
        //         ];
        //         $cont = LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token[0]->access_token);
        //     }
        //     // return response()->json(['status' => 'success']);
        // }

        if($formdata->form_id == '1751877063-4f70951b-2d8a-45d7-904e-677fa469d30c') {
            $contact_id = [];
            $voltido_trio_patient = [];
            $id = [];
            if (!empty($post['id']) && is_array($post['id'])) {
                foreach($post['id'] as $ci => $did) {
                    $id[] = $did;
                    $i = array_search($ci, $post['contact_id']);
                    if ($i !== false) {
                        $contact_id[] = $post['contact_id'][$i];
                        $voltido_trio_patient[] = $post['voltido_trio_patient'][$i] ?? 'No';
                    }
                }
            }

            foreach($post['voltido_trio_patient'] as $i => $ad) {
                if(!empty($ad) && !in_array($post['contact_id'][$i], $contact_id) ) {
                    $contact_id[] = $post['contact_id'][$i];
                    $voltido_trio_patient[] = $ad;
                }
            }
            if(sizeof($id) > 0) {
                $post['id'] = $id;
            }
            $post['contact_id'] = $contact_id;
            // $post['contact_name'] = $contact_name;
            $post['voltido_trio_patient'] = $voltido_trio_patient;
            Log::debug(print_r($post, true));
            //return response()->json(['status' => 'failure']);
        }


        if($formdata->form_id == '1751535971-9f06067c-3632-4126-830b-9f767650ae42') {
            $chemist_id = [];
            $chemist_name = [];
            $activity_done = [];
            $id = [];
            //Log::debug(print_r($post, true));
            if (!empty($post['id']) && is_array($post['id'])) {
                foreach($post['id'] as $ci => $did) {
                    $id[] = $did;
                    $i = array_search($ci, $post['chemist_id']);
                        if ($i !== false) {
                            $chemist_id[] = $post['chemist_id'][$i];
                            $chemist_name[] = $post['chemist_name'][$i];
                            $activity_done[] = $post['activity_done'][$i];
                        }
                    }
                }

            foreach($post['activity_done'] as $i => $ad) {
                if(!empty($ad) && !in_array($post['chemist_id'][$i], $chemist_id) ) {
                    $chemist_id[] = $post['chemist_id'][$i];
                    $chemist_name[] = $post['chemist_name'][$i];
                    $activity_done[] = $ad;
                }
            }
            $post['id'] = $id;
            $post['chemist_id'] = $chemist_id;
            $post['chemist_name'] = $chemist_name;
            $post['activity_done'] = $activity_done;
            // Log::debug(print_r($post, true));
            // return response()->json(['status' => 'failure']);
        }


        if(isset($formdata) && !empty($formdata) && $formdata->user_id != '') {
            $post = $this->processformdata($formdata->form_id, $post, $formdata->user_id, $formdata->partition);
            Log::debug(print_r($post, true));
            $finfo = LambdaRequest::postrequest('form', 'formentity/submitmultipleform', ['formdata' => $post, 'entity_id' => $post['form_id'], 'user_id' => $formdata->user_id, 'partition' => $formdata->partition ]);
            Log::debug(print_r($finfo, true));
            if($finfo->status == 'success') {
                return response()->json(['status' => 'success']);
            } else {
                return response()->json(['status' => 'failure']);
            }          
        } else {
            return response()->json(['status' => 'failure']);
        }


    }

    public function approvereject(Request $request) {
        $formdata = $request->session()->get('formdata');
        $post = $request->all();
        //$user = DB::table('users')->where('domain', str_replace('rapport-', '',$formdata->partition ) )->first();
        
        list($app, $domain) = explode('-', $formdata->partition);
        $user = DB::table('users')->select("access_token")->where('domain', $domain )->orderBy('updated_at', 'desc')->skip(0)->take(1)->get();
        Log::debug(print_r($formdata, true));

        $finfo = LambdaRequest::postrequest('form', 'formentity/approvereject', ['submission_id' => $post['id'], 'action' => $post['action'] ], $user[0]->access_token);
        Log::debug(print_r($user, true));
        Log::debug(print_r($finfo, true));
        Log::debug(print_r($post, true));
        return response()->json($post);
    }

    public function approverejectmultiple(Request $request) {
        $post = $request->all();
        foreach($post['ids'] as $id) {
            LambdaRequest::postrequest('form', 'formentity/approvereject', ['submission_id' => $id, 'action' => $post['action'] ], Auth::user()->access_token);
        }
        return response()->json($post);
    }

    public function allaprovers(Request $request) {
        $post = $request->all();
        $allapprovers = LambdaRequest::postrequest('form', 'formentity/allapprovers', ['submission_id' => $post['submission_id'], 'form_id' => $post['form_id'] ], Auth::user()->access_token);
        return response()->json($allapprovers->data->approvals);
    }

    protected function processformdata($form, $post, $user_id = 0, $partition = '' ) {
        switch($form) {
            case '1711609582-e93dba24-9c98-43e7-b97a-b22d64d9b9fc':
            case '1711609582-e93dba24-9c98-43e7-neb2-b22d64d9b9fc':
                list($application, $domain) = explode("-", $partition);
                $token = DB::table('users')->select("access_token")->where("domain", $domain)->where("permissions", 'like', '%contact_create%')->orderBy('updated_at', 'desc')->skip(0)->take(1)->get();
                $contactdata = [
                    'domain' => $domain,
                    'application' => $application,
                    'user_id' => $user_id,
                    'name' => $post['chemist_name'],
                    'current_business' => $post['current_business'],
                    'type' => 'chemist',
                    'category' => isset($post['category']) ? $post['category'] : '',
                    'msl_code' => strtotime("now").'-'.rand(1000,9999)
                ];
                if(isset($post['id'])) {
                    $contactdata['id'] = $post['contact_id'];
                    unset($post['contact_id']);
                    $contact = LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token[0]->access_token);
                } else {
                    $contact = LambdaRequest::postrequest('contact', 'contact/create', $contactdata, $token[0]->access_token);
                }
                $post['contact_id'] = $contact->data->item->id;
                break;
            case '1711947857-4fbd5d43-d176-4ec7-aff2-e4dec4b6e02a':
                list($application, $domain) = explode("-", $partition);
                $token = DB::table('users')->select("access_token")->where("domain", $domain)->where("permissions", 'like', '%contact_create%')->orderBy('updated_at', 'desc')->skip(0)->take(1)->get();
                $contactdata = [
                    'domain' => $domain,
                    'application' => $application,
                    'user_id' => $user_id,
                    'name' => $post['chemist_name'],
                    'current_business' => $post['current_business'],
                    'type' => 'chemist',
                    'doctor_name' => $post['doctor_name'],
                    'category' => $post['category'],
                    'doctor_msl_code' => $post['msl_code'],
                    'doctor_speciality' => $post['speciality'],
                    'msl_code' => strtotime("now").'-'.rand(1000,9999)
                ];
                if(isset($post['id'])) {
                    $contactdata['id'] = $post['contact_id'];
                    unset($post['contact_id']);
                    $contact = LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token[0]->access_token);
                } else {
                    $contact = LambdaRequest::postrequest('contact', 'contact/create', $contactdata, $token[0]->access_token);
                }
                $post['contact_id'] = $contact->data->item->id;
                break;
            case '1654748343-81b065ee-e05c-431c-a44d-706afc1c16f4':
                if($post['contact_id'] == 'other') {
                    $post['contact_id'] = '';
                }            
                break;
            case '1650365556-f06dde85-6138-4dae-9c23-5067e318c522':
            case '1660360290-f06dde85-6138-4dae-9c23-5067e318c522':
                $post[ $post['brand_name'].'-current' ] = $post['current_business_value'];
                $post[ $post['brand_name'].'-potential' ] = $post['potential_business_value'];
                break;
            case '1653655221-724ec5b4-fccb-4a88-bf25-cf894fa27a77':
                $brands = ['Hinex DM' => 'hinex-dm', 'Hinex HP' => 'hinex-hp', 'Hinex ST' => 'hinex-st', 'Hinex ST +' => 'hinex-st+'];
                foreach($post['brand'] as $i => $brand) {
                    foreach($brands as $bname => $bkey) {
                        if($bname == $brand)
                            $post[$bkey][$i] = $post['units'][$i];
                        else
                            $post[$bkey][$i] = 0;
                    }
                }
                break;
            case '1655958637-c41fb1b6-4ddc-42d3-aa2a-563c1cf5e4c9':
                Log::debug(print_r($post, true));
                if(array_key_exists('chemist_name', $post) ) {
                    $chemistformdata = [];
                    $chemistformdata['form_id'] = '1654747635-9d7133e4-a641-4865-aeed-021bb34d8960';
                    $chemistformdata['record_date'] = $post['record_date'];
                    $chemistformdata['chemist_name'] = $post['chemist_name'];
                    $chemistformdata['dapasach_units'] = $post['dapasach_strips'];
                    $chemistformdata['dapasach_m_units'] = $post['dapasach_m_strips'];
                    $chemistformdata['dapasach_s_units'] = $post['dapasach_s_strips'];
                    Log::debug(print_r($chemistformdata, true));
                    $finfo = LambdaRequest::postrequest('form', 'formentity/submitmultipleform', ['formdata' => $chemistformdata, 'entity_id' => $chemistformdata['form_id'], 'user_id' => $user_id, 'partition' => $partition ]);
                }
                
                $rxformdata = [];
                $rxformdata['form_id'] = '1657032612-8a539e63-fc5e-47c2-96f9-b4454cea7591';
                $rxformdata['record_date'] = $post['record_date'];
                $rxformdata['no_of_dapasach_rx'] = $post['no_of_dapasach_rx'];
                $rxformdata['no_of_dapasach_m_rx'] = $post['no_of_dapasach_m_rx'];
                $rxformdata['no_of_dapasach_s_rx'] = $post['no_of_dapasach_s_rx'];
                $rxformdata['dapasach_units_made_available'] = $post['dapasach_units_made_available'];
                $rxformdata['dapasach_m_units_made_available'] = $post['dapasach_m_units_made_available'];
                $rxformdata['dapasach_s_units_made_available'] = $post['dapasach_s_units_made_available'];
                Log::debug(print_r($rxformdata, true));
                $finfo = LambdaRequest::postrequest('form', 'formentity/submitform', ['formdata' => $rxformdata, 'entity_id' => $rxformdata['form_id'], 'user_id' => $user_id, 'partition' => $partition ]);

                unset($post['chemist_name']);
                unset($post['dapasach_units']);
                unset($post['dapasach_m_units']);
                unset($post['dapasach_s_units']);
                unset($post['no_of_dapasach_rx']);
                unset($post['no_of_dapasach_m_rx']);
                unset($post['no_of_dapasach_s_rx']);
                unset($post['dapasach_units_made_available']);
                unset($post['dapasach_m_units_made_available']);
                Log::debug(print_r($post, true));
                break;
            case '1659513453-1f5e2584-fb76-4075-b040-6sg6e34a5423':
                if($post['customer_type'] == 'Doctor') {
                    $post['doctor_count'] = 1;
                    $post['retailer_count'] = 0;
                } else {
                    $post['doctor_count'] = 0;
                    $post['retailer_count'] = 1;
                }
                break;
            case '1659513016-1f5e2584-fb76-4075-b040-a9a4e34a7458':
            case '1659538834-fb8bd30a-a719-4285-8d74-063462930c1d':
                if($post['customer_type'] == 'Doctor') {
                    $post['doctor_count'] = 1;
                    $post['retailer_count'] = 0;
                } else {
                    $post['doctor_count'] = 0;
                    $post['retailer_count'] = 1;
                }

                $prefix = '';
                if($post['brand_selected'] == 'DAPASACH FRANCHISE') {
                    $prefix = 'dapasach_';
                    if($post['customer_type'] == 'Retailer') {
                        $post[$prefix.'pob_dapasach'] = $post['pob_dapasach'];
                        $post[$prefix.'pob_dapasach_s'] = $post['pob_dapasach_s'];
                        $post[$prefix.'pob_dapasach_m'] = $post['pob_dapasach_m'];
                    }
                } else if($post['brand_selected'] == 'METOLAR FRANCHISE') {
                    $prefix = 'metolar_';
                    if($post['customer_type'] == 'Retailer') {
                        $post[$prefix.'pob_metolar_trio'] = $post['pob_metolar_trio'];
                        $post[$prefix.'pob_metolar_3d'] = $post['pob_metolar_3d'];
                    }
                }
                $post[$prefix.'doctor_count'] = $post['doctor_count'];
                $post[$prefix.'retailer_count'] = $post['retailer_count'];
                break;
            case '1663562771-bd3aeb6b-2495-4b82-9ce8-7ba159700a7a':
                $post[strtolower($post['brand']).'_count'] = 1;
                $post[strtolower($post['brand']).'_business_potential'] = $post['business_potential'];
                break;
            case '1663833303-3503e11a-ca91-4bb7-ac85-bc9bc36d9997':
                if($post['doctor_activity'] == 'Yes' || $post['rx_generated'] == 'Yes') {
                    $rxformdata = [];
                    $rxformdata['form_id'] = '1665645874-53e8b736-a061-4231-b209-f229083a883c';
                    $rxformdata['record_date'] = empty($post['rx_date']) ? $post['activity_rx_date'] : $post['rx_date'];
                    $rxformdata['contact_id'] = $post['contact_id'];
                    $rxformdata['no_of_dapasach_rx'] = ($post['rx_generated'] == 'Yes') ? $post['no_of_dapasach_rx'] : 0;
                    $rxformdata['no_of_dapasach_m_rx'] = ($post['rx_generated'] == 'Yes') ? $post['no_of_dapasach_m_rx'] : 0;
                    $rxformdata['no_of_dapasach_s_rx'] = ($post['rx_generated'] == 'Yes') ? $post['no_of_dapasach_s_rx'] : 0;
                    $rxformdata['doctor_activity'] = $post['doctor_activity'];
                    $rxformdata['activity_name'] = isset($post['activity_name']) ? $post['activity_name'] : '';
                    Log::debug(print_r($rxformdata, true));
                    $finfo = LambdaRequest::postrequest('form', 'formentity/submitform', ['formdata' => $rxformdata, 'entity_id' => $rxformdata['form_id'], 'user_id' => $user_id, 'partition' => $partition ]);
                }

                if($post['converted_count'] == 1) {
                    $rxformdata = [];
                    $rxformdata['form_id'] = '1665653958-93e66eae-f0ad-4792-ae91-87f9ae787380';
                    $rxformdata['record_date'] = $post['conversion_date'];
                    $rxformdata['contact_id'] = $post['contact_id'];
                    $rxformdata['converted_count'] = $post['converted_count'];
                    Log::debug(print_r($rxformdata, true));
                    $finfo = LambdaRequest::postrequest('form', 'formentity/submitform', ['formdata' => $rxformdata, 'entity_id' => $rxformdata['form_id'], 'user_id' => $user_id, 'partition' => $partition ]);
                }
                
                break;
            case '1669979078-e991fc27-e8c1-4120-9883-b42af09244d0':
                $post[strtolower($post['brand_name'])] = $post['no_of_rx'];
                break;
            case '1669979081-e991fc27-e8c1-4120-9883-b42af09244d3':
            case '1689236085-9aaa37ba-601b-4414-b1fc-a26e9cc722df':
                if(isset($post['execution_done']) && $post['execution_done'] == 'yes' && isset($post['activity_type'])) {
                    $post[$post['activity_type']] = 1;
                }
                break;

            case '1672032315-9b267137-4b81-425c-afb4-a4c0fa701372':
                if($post['powerof5'] == 'Yes') {
                    $post['powerof5_duolin_rx'] = $post['duolin_rx'];
                    $post['powerof5_glycohale_f_rx'] = $post['glycohale_f_rx'];
                    $post['powerof5_maxiflo_rx'] = $post['maxiflo_rx'];
                    $post['powerof5_maxiflo_sb_rx'] = $post['maxiflo_sb_rx'];
                    $post['powerof5_asthalin_rx'] = $post['asthalin_rx'];
                    $post['powerof5_glycohale_fb_rx'] = $post['glycohale_fb_rx'];
                }
                break;
            case '1675171879-850cf63f-864d-42e1-82e7-2a60e92712b6':
                $post['launched_count'] = [];
                foreach($post['contact_id'] as $i => $c) {
                    $post['launched_count'][] = $post['launched'][$i] == 'Yes' ? 1 : 0;
                }
                break;
            case '1672051617-b274ae94-8706-4f0f-8e65-6e4380f7c005':
            case '1673857541-fe4fef4b-6b1c-4326-96ec-f71634ee91db':
                if($post['is_hridayam_doctor'] == 'Yes') {
                    $rxformdata = $post;
                    $rxformdata['form_id'] = '1672051617-b274ae94-8704-4f0f-8e85-6e4380f7c4543';
                    LambdaRequest::postrequest('form', 'formentity/submitform', ['formdata' => $rxformdata, 'entity_id' => $rxformdata['form_id'], 'user_id' => $user_id, 'partition' => $partition ]);
                }
                break;
            case '1653655224-724ec5b3-fccb-4a88-bf28-cf894fa27a78':
                $contacts = [];
                $indamet_80_rx = [];
                $indamet_160_rx = [];
                $indamet_320_rx = [];
                $doctor_tagging = [];
                $campaign = [];
                foreach($post['contact_id'] as $i => $c) {
                    if($post['indamet_80_rx'][$i] > 0 || $post['indamet_160_rx'][$i] > 0 || $post['indamet_320_rx'][$i] > 0) {
                        $contacts[] = $c;
                        $indamet_80_rx[] = $post['indamet_80_rx'][$i];
                        $indamet_160_rx[] = $post['indamet_160_rx'][$i];
                        $indamet_320_rx[] = $post['indamet_320_rx'][$i];
                        $doctor_tagging[] = $post['doctor_tagging'][$i];
                        $campaign[] = $post['campaign'][$i];
                    }
                }
                $post['contact_id'] = $contacts;
                $post['indamet_80_rx'] = $indamet_80_rx;
                $post['indamet_160_rx'] = $indamet_160_rx;
                $post['indamet_320_rx'] = $indamet_320_rx;
                $post['doctor_tagging'] = $doctor_tagging;
                $post['campaign'] = $campaign;
                break;
            case '1691224392-9d29fc1f-23ae-4702-bc23-55ccdd85dab4':
                if(isset($post['execution_date'])) {
                    $first_post = $post;
                    foreach($post['contact_id'] as $k => $v) {
                        if($k == 0) {
                            $first_post['contact_id'] = $v;
                            $first_post['id'] = $post['id'][$k];
                            $first_post['speciality'] = $post['speciality'][$k];
                            $first_post['group_id'] = $post['group_id'][$k];
                            $first_post['no_of_paramedics'] = $post['no_of_paramedics'][$k];
                            $first_post['first_executed'] = 'yes';
                            $first_post['first_planned'] = 'yes';
                        } else {
                            $thispost = $post;
                            $thispost['contact_id'] = $v;
                            $thispost['id'] = $post['id'][$k];
                            $thispost['speciality'] = $post['speciality'][$k];
                            $thispost['group_id'] = $post['group_id'][$k];
                            $thispost['no_of_paramedics'] = $post['no_of_paramedics'][$k];
                            LambdaRequest::postrequest('form', 'formentity/submitform', ['formdata' => $thispost, 'entity_id' => $thispost['form_id'], 'user_id' => $user_id, 'partition' => $partition ]);
                        }
                    }
                    $post = $first_post;
                } else {
                    $first_post = $post;
                    $group_id = strtotime("now").'-'.rand(1000000,9999999);
                    foreach($post['contact_id'] as $k => $v) {
                        if($k == 0) {
                            $first_post['contact_id'] = $v;
                            $first_post['speciality'] = $post['speciality'][$k];
                            $first_post['group_id'] = $group_id;
                            $first_post['first_planned'] = 'yes';
                        } else {
                            $thispost = $post;
                            $thispost['contact_id'] = $v;
                            $thispost['speciality'] = $post['speciality'][$k];
                            $thispost['group_id'] = $group_id;
                            LambdaRequest::postrequest('form', 'formentity/submitform', ['formdata' => $thispost, 'entity_id' => $thispost['form_id'], 'user_id' => $user_id, 'partition' => $partition ]);
                        }
                    }
                    $post = $first_post;
                }
                break;
            case '1713426268-c89f38eb-ec32-43ba-a81b-b690a8f90d6a':
                if(is_array($post['doctor_name']) ) {
                    $execCount = sizeof($post['doctor_name']);
                    $planed = LambdaRequest::postrequest('form', 'formentity/getformdefination', ['form_id' => '1713425460-8bdf7394-01b5-48f3-8985-343b465dd685', 'user_id' => $user_id, 'partition' => $partition, 'id' => $post['plan_id'] ]);
                    $plandata = $planed->data->formdata;
                    Log::debug(print_r($plandata, true));
                    if(isset($plandata->execution_count)) {
                        $plandata->execution_count += $execCount;
                    } else {
                        $plandata->execution_count = $execCount;
                    }
                    $plandata->id = $post['plan_id'];
                    LambdaRequest::postrequest('form', 'formentity/submitform', ['formdata' => (array)$plandata, 'entity_id' => '1713425460-8bdf7394-01b5-48f3-8985-343b465dd685', 'user_id' => $user_id, 'partition' => $partition ]);
                    // $post['plan_id'] = [];
                    // foreach($post['doctor_name'] as $i => $dn) {
                    //     $post['plan_id'][] = $plandata->id;
                    //     $post['plan_date'][] = $plandata->record_date;
                    //     // DB::table('team3_nebyatra_doctors')->updateOrInsert(
                    //     //                         ['user_id' => $user_id, 'mobile_number' => $post['mobile_number'][$i] ],
                    //     //                         ['doctor_name' => $dn, 'email_id' => $post['email_id'][$i], 'speciality' => $post['speciality'][$i], 'location' => $post['location'][$i], 'district' => $post['district'][$i], 'state' => $post['state'][$i], 'date_added' => $post['record_date'][$i] ]
                    //     //                     );
                    // }

                }
                break;
        }

        return $post;
    }

    public function nebmitrahistory(Request $request) {
        $form_id = $request->input('form_id', '');
        $user_id = $request->input('user_id', '');
        $partition = $request->input('partition', '');
        $history = LambdaRequest::postrequest('form', 'formentity/getformhistory', ['form_id' => $form_id, 'user_id' => $user_id, 'partition' => $partition ]);
        return response()->json(['form' => $history->data->form, 'questions' => $history->data->questions, 'submissions' => $history->data->submissions, 'form_id' => $form_id]);
    }

    public function history(Request $request) {
        $formdata = $request->session()->get('formdata');
        Log::debug(print_r($formdata, true));
        $form_id = $request->input('form_id', $formdata->form_id);
        $formdata->form_id = $form_id;
        $request->session()->put('formdata', $formdata);
        //echo '
'; print_r($formdata); exit;
        $history = LambdaRequest::postrequest('form', 'formentity/getformhistory', ['form_id' => $form_id, 'user_id' => $formdata->user_id, 'partition' => $formdata->partition ]);
        //echo '
'; print_r($history); print_r($formdata); exit;
        //Log::debug(print_r($history, true));
        if($form_id == '1713426268-c89f38eb-ec32-43ba-a81b-b690a8f90d6a') {
            $plan_id = $request->input('plan_id', '');
            $submissions = [];
            foreach($history->data->submissions as $sub) {
                if(isset($sub->formdata->plan_id) && $sub->formdata->plan_id == $plan_id) {
                    $submissions[] = $sub;
                }
            }
            $data = ['form' => $history->data->form, 'questions' => $history->data->questions, 'submissions' => $submissions, 'formname' => $history->data->formname, 'form_id' => $form_id ];
        } else {
            $data = ['form' => $history->data->form, 'questions' => $history->data->questions, 'submissions' => $history->data->submissions, 'formname' => $history->data->formname, 'form_id' => $form_id ];
        }

        if($request->input('export', false)) {
            $exceldata = [];
            $exceldata[] = [$formdata->title];
            $exceldata[] = [''];
            $headers = ['Submission Date', 'Submitted By', 'Approval Status'];
            foreach($history->data->questions as $question) {
                $headers[] = $question->label;
            }
            $exceldata[] = $headers;
            foreach($history->data->submissions as $submission) {
                $row = [];
                $row[] = $submission->createdAt;
                $row[] = isset($submission->user_info->name) ? $submission->user_info->name : '';
                $row[] = isset($submission->workflow_status) ? $submission->workflow_status : '';
                foreach($history->data->questions as $q => $v) {
                    $row[] = isset($submission->formdata->{$q}) ? $submission->formdata->{$q} : '-';
                }
                $exceldata[] = $row;
            }
            return Excel::download(new InvoicesExport($exceldata), $formdata->title.'.xlsx');
        }

        if (\View::exists('form.'.$formdata->partition.'.'.$formdata->form_id.'-history')) {
            return view('form.'.$formdata->partition.'.'.$formdata->form_id.'-history')->with($data);
        } elseif (\View::exists('form.'.$formdata->form_id.'-history')) {
            return view('form.'.$formdata->form_id.'-history')->with($data);
        } else {
            return view('form.history')->with($data);
        }
        //return view('form.history')->with();
        //echo '
'; print_r($history); print_r($formdata); exit;
    }

    public function edit(Request $request) {
        $formdata = $request->session()->get('formdata');
        //Log::debug(print_r($formdata, true));
        $id = $request->input('id', false);
        //'user_id' => $formdata->user_id,
        $finfo = LambdaRequest::postrequest('form', 'formentity/getformdefination', ['form_id' => $formdata->form_id, 'partition' => $formdata->partition, 'id' => $id ]);
        $formdata->title = $finfo->data->formdata->title;
        //Log::debug(print_r($finfo->data->formdata, true));
        if (\View::exists('form.'.$formdata->partition.'.'.$formdata->form_id)) {
            return view('form.'.$formdata->partition.'.'.$formdata->form_id)->with(['questions' => $finfo->data->questions,'form_id' => $formdata->form_id, 'form' => $formdata, 'id' => $id, 'formdata' => $finfo->data->formdata ]);
        } elseif (\View::exists('form.'.$formdata->form_id)) {
            return view('form.'.$formdata->form_id)->with(['questions' => $finfo->data->questions,'form_id' => $formdata->form_id, 'form' => $formdata, 'id' => $id, 'formdata' => $finfo->data->formdata ]);
        } else {
            return view('form.common')->with(['questions' => $finfo->data->questions, 'form_id' => $formdata->form_id, 'form' => $formdata, 'id' => $id, 'formdata' => $finfo->data->formdata ]);
        }
    }

    protected function get_additional_info($formdata) {
        switch($formdata->form_id) {
            case '63c2ff17-a69c-4b47-af33-1d9909c608b6':
            case 'eaef2abf-f16b-414c-b6a5-df3fd2282b2e':
                $hierarchy = LambdaRequest::getrequest('ums', 'hierarchy/hierarchy_below_me', ['partition' => $formdata->partition, 'user_id' => $formdata->user_id ]);
                $team = [];
                foreach($hierarchy->data->hierarchies as $hie) {
                    if(isset($hie->owner_info->id)) {
                        $team[$hie->owner_info->id] = ['name' => $hie->owner_info->name, 'code' => $hie->owner_info->employee_code ];
                    }
                }
                return ['team' => $team];
            break;
            case '1653655221-724ec5b4-fccb-4a88-bf25-cf894fa27a77':
                
                return [];
            break;

            default:
                return [];
            break;
        }
    }

    public function getformfielddata(Request $request) {
        $post = $request->except('_token');
        $history = LambdaRequest::postrequest('form', 'formentity/getformhistory', ['form_id' => $post['form_id'], 'user_id' => $post['user_id'], 'partition' => $post['partition'] ]);
        $submission = [];
        foreach($history->data->submissions as $sub) {
            if($sub->formdata->record_date ==  strtotime($post['record_date']) ) {
                $submission = (array)$sub->formdata;
                $submission['submission_id'] = $sub->id;
            }
        }

        return response()->json(['submission' => $submission, 'submissions' => $history->data->submissions, 'record_date' => strtotime($post['record_date']) ]);
    }

    public function metricreport(Request $request) {
        $post = $request->input();
        Log::debug(print_r($post, true));
        $token = $request->header('Authorization');
        if($token != '') {
            $request->session()->put('metric_access_key', $token);
        } elseif(array_key_exists('authorization', $post)) {
            $token = $post['authorization'];
            $request->session()->put('metric_access_key', $token);
        } else {
            $token = $request->session()->get('metric_access_key');
        }
        // $post['charttype'] = isset($post['charttype']) ? $post['charttype'] : 'leaderboard'
        // $post['chart'] = isset($post['chart']) ? $post['chart'] : 'leaderboard'

        //Log::debug('Token is:' . $token);
        $download = (isset($post['download']) && $post['download'] == 1) ? 1 : 0;
        $email = (isset($post['email']) && $post['email'] == 1) ? 1 : 0;
        $s3 = (isset($post['s3']) && $post['s3'] == 1) ? 1 : 0;
        unset($post['download']);
        unset($post['email']);
        unset($post['s3']);

        $response = LambdaRequest::postrequest('metric', 'metric_report/view', $post, $token);
        //Log::debug(print_r($response, true));
        //echo '
'; print_r($response); print_r($post); exit;

        $breadcrumbs = [];
        if(isset($post['hid'])){
            if($request->session()->has('leaderboard_breadcrumbs')) {
                $breadcrumbs = $request->session()->get('leaderboard_breadcrumbs');
            }
            $breadcrumbs[$post['level']] = ['hid' => $post['hid'], 'username' => $post['username'], 'level' => $post['level'] ];
            $request->session()->put('leaderboard_breadcrumbs', $breadcrumbs);
            $breadcrumbs = array_filter($breadcrumbs, function($k) use($post) { return $k >= $post['level']; }, ARRAY_FILTER_USE_KEY);
            krsort($breadcrumbs);
        }

        
        if($download) {
            $exceldata = [];
            $exceldata[] = [$response->data->graph->name];
            $exceldata[] = ['Report: '.ucwords($response->data->graph->agg_type).' Report'];
            $exceldata[] = ['Type: '.ucwords($response->data->graph->type).' Metric'];
            foreach($response->data->periods as $v) {
                if($post['period'] == $v->value) {
                    $exceldata[] = ['Period: '.ucwords($v->label)];
                }
            }        
            $exceldata[] = [''];
            switch($response->data->post->type) {
                case 'leaderboard':
                    $exceldata[] = ["Rank", "User", "Designation", "Units", "Percent"];
                    foreach($response->data->graph->values as $val) {
                        $exceldata[] = [(string)$val->rank, (string)$val->user->name, $val->user->designation, (string)round($val->score, 2), (string)$response->data->graph->values[0]->rank != 0 ? ($response->data->graph->values[0]->rank == 1 ? ($response->data->graph->values[0]->score ? ceil(($val->score/$response->data->graph->values[0]->score)*100) : 0) : ($response->data->graph->values[1]->score ? ceil(($val->score/$response->data->graph->values[1]->score)*100) : 0 ) ) : 0 ];
                    }
                    break;
                case 'trend':
                    $headings = ['Periods'];
                    if($response->data->graph->type == 'grouped') {
                        foreach($response->data->graph->values as $met) {
                            $headings[] = $met->metric;
                        }
                        $exceldata[] = $headings;
                        foreach($response->data->graph->values[0]->stats as $i => $stat) {
                            $row = [$stat->x];
                            foreach($response->data->graph->values as $met) {
                                $row[] = isset($met->stats[$i])?$met->stats[$i]->y:0;
                            }
                            $exceldata[] = $row;
                        }
                    } else {
                        $headings[] = $response->data->graph->label;
                        $exceldata[] = $headings;
                        foreach($response->data->graph->values as $i => $val) {
                            $exceldata[] = [$val->x, $val->y];
                        }
                    }
                    break;
                case 'graphical':
                    if($response->data->graph->type == 'grouped') {
                        $exceldata[] = ['Metric Name', 'Units', 'Percent'];
                        $total = 0; 
                        foreach($response->data->graph->values as $val) {
                            $total = $total + $val->value;
                        }
                        foreach($response->data->graph->values as $val) {
                            $exceldata[] = [$val->label, $val->value, (string)round(($val->value/$total)*100, 2)];
                        }
                    }
                    break;
                case 'details':
                    if($response->data->graph->chart == 'tabular') {
                        $headers = ['User', 'Employee Code', 'Designation', 'Zone', 'Region', "Area", "Territory"];
                        foreach($response->data->graph->values->metrics as $metric) {
                            $headers[] = $metric->metric;
                        }
                        $exceldata[] = $headers;
                        foreach($response->data->graph->values->users as $user) {
                            $row = [];
                            $row[] = $user->name;
                            $row[] = $user->employee_code;
                            $row[] = $user->designation;
                            $row[] = isset($user->positions->Zone) ? $user->positions->Zone : '-';
                            $row[] = isset($user->positions->Region) ? $user->positions->Region : '-';
                            $row[] = isset($user->positions->Area) ? $user->positions->Area : '-';
                            $row[] = isset($user->positions->Territory) ? $user->positions->Territory : '-';
                            foreach($response->data->graph->values->metrics as $metric) {
                                $row[] = isset($metric->stats->{$user->id}) ? $metric->stats->{$user->id} : '-';
                            }
                            $exceldata[] = $row;
                        }
                    }
                    break;
                case 'contacts':
                    if($response->data->graph->chart == 'contacts') {
                        //echo '
'; print_r($response->data->graph->values); exit;

                        $headers = ['Doctor', 'MSL Code', 'User', 'Employee Code', 'Email', 'Designation', 'Manager 1 Name', 'Manager 1 Emp Code', 'Manager 1 Email', 'Manager 2 Name', 'Manager 2 Emp Code', 'Manager 2 Email',  'Zone', 'Region', "Area", "Territory"];
                        foreach($response->data->graph->values->metrics as $metric) {
                            $headers[] = $metric->metric;
                        }
                        $exceldata[] = $headers;
                        foreach($response->data->graph->values->contacts as $contact) {
                            $row = [];
                            $row[] = $contact->name;
                            $row[] = $contact->msl_code;

                            if(!isset($response->data->graph->values->users->{$contact->id})) {
                                continue;
                            }

                            $user = $response->data->graph->values->users->{$contact->id};

                            $row[] = $user->name;
                            $row[] = $user->employee_code;
                            $row[] = $user->email;
                            $row[] = $user->designation;

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

                            $row[] = isset($user->positions->Zone) ? $user->positions->Zone : '-';
                            $row[] = isset($user->positions->Region) ? $user->positions->Region : '-';
                            $row[] = isset($user->positions->Area) ? $user->positions->Area : '-';
                            $row[] = isset($user->positions->Territory) ? $user->positions->Territory : '-';

                            foreach($response->data->graph->values->metrics as $metric) {
                                $row[] = isset($metric->stats->{$contact->id}) ? $metric->stats->{$contact->id} : '-';
                            }
                            $exceldata[] = $row;
                        }
                    }
                break;
            }
            //echo '
'; print_r($exceldata); exit;
            $data = new \StdClass;
            $data->sender_name = 'Rapport Support';
            $data->sender_email = 'support@stratawiz.com';
            $data->subject = 'Attached Report';
            $data->body = '';

            $report = Excel::raw(new InvoicesExport($exceldata), 'Xlsx');
            $data->attachment = $report;
            $data->attachment_name = 'report.xlsx';

            //Mail::to( str_replace(Auth::user()->domain.'-','', Auth::user()->email) )->send(new ReportExcel($data));
            //Mail::to( 'ravigulhane1983@gmail.com' )->send(new ReportExcel($data));
            if($s3) {
                $filename = 'reports/'.strtotime("now").'-report.xlsx';
                $res = Excel::store(new InvoicesExport($exceldata), 'public/'.$filename);
                Log::debug(print_r($res, true));
                Log::debug('/storage/'.$filename);
                return response()->json(['sent' => 'yes', 'filename' => '/storage/'.$filename]);
            } else {
                Mail::to( $response->data->user->email )->send(new ReportExcel($data));
                return response()->json(['sent' => 'yes']);
            }
            
        } else {
            $colors = ['FECD00', '01C14B', 'FF8050', '4A5CD0', '707070'];
            $post = array_merge((array)$response->data->post,$post);
            if(isset($post['metrics']) ) {
                $post['metrics'] = explode(',', $post['metrics']);
            }
            return view('metricreport.appreport')->with(['periods' => $response->data->periods, 'charts' => $response->data->available_charts, 'graph' => $response->data->graph, 'post' => $post, 'colors' => $colors, 'breadcrumbs' => $breadcrumbs]);
        }
    }

    public function metriclist(Request $request) {
        $post = $request->input();
        $token = $request->header('Authorization');
        if($token != '') {
            $request->session()->put('metric_access_key', $token);
        } else {
            $token = $request->session()->get('metric_access_key');
        }
        $reports = LambdaRequest::getrequest('metric', 'metric_report/list', $post, $token);
        //echo '
'; print_r($reports); exit;
        //$reports = $this->getlambda('get', 'metric', 'metric_report', 'list');
        return view('metricreport.appreportlist')->with(['metrics' => $reports->data->metrics]);

    }

    public function preview(Request $request) {
        $data = $request->input('data');
        $finfo = LambdaRequest::postrequest('form', 'formentity/preview', ['data' => $data]);
        //echo '
'; print_r($finfo); exit;
        $formdata = $finfo->data->formdata;
        $formdata->user_info = $finfo->data->user_info;
        $formdata->link_type = 'form';
        $formdata->is_approval = 'yes';
        $formdata->title = $finfo->data->formdata->form_name;
        if (\View::exists('form.'.$formdata->form_id)) {
            return view('form.'.$formdata->form_id)->with(['questions' => $finfo->data->questions, 'form' => $formdata, 'id' => $finfo->data->formdata->submission_id, 'form_id' => $finfo->data->formdata->form_id ]);
        } else {
            return view('form.common')->with(['questions' => $finfo->data->questions, 'form' => $formdata, 'id' => $finfo->data->formdata->submission_id, 'form_id' => $finfo->data->formdata->form_id ]);
        }
    }

    protected function deliverpersonalization($formdata, $questions, $personalizations) {
        $additional_info = $this->get_additional_info($formdata);
        //echo '
'; print_r($formdata); print_r($questions); print_r($personalizations);  exit;
        $data = ['questions' => $questions, 'form' => $formdata, 'form_id' => $formdata->form_id, 'personalizations' => $personalizations ];
        if(sizeof($additional_info) > 0) {
            $data['additional'] = $additional_info;
        }
        if (\View::exists('form.'.$formdata->partition.'.personalization-'.$formdata->form_id)) {
            return view('form.'.$formdata->partition.'.personalization-'.$formdata->form_id)->with($data);
        } elseif (\View::exists('form.personalization-'.$formdata->form_id)) {
            return view('form.personalization-'.$formdata->form_id)->with($data);
        } else {
            return view('form.personalization')->with($data);
        }
    }

    public function submitpersonalized(Request $request) {
        $post = $request->except('_token');
        $files = $request->file();
        $images = [];
        foreach($files as $fname => $file) {
            $post[$fname] = $this->_uploadMediaLocal($request, $fname, 'public/personalized/'.$post['form_id'].'/'.$fname);
            $images[] = $fname;
        }
        if(isset($post['cropped'])) {
            foreach($post['cropped'] as $name => $cropp) {
                if(isset($cropp) && !empty($cropp)) {
                    $data = explode( ',', $cropp );
                    $image = base64_decode( $data[1] );
                    $filename = strtotime("now").'-'.Str::random(64).'.png';
                    Storage::disk('public')->put('personalized/'.$post['form_id'].'/'.$name.'/'.$filename, $image);
                    $post[$name] = '/storage/personalized/'.$post['form_id'].'/'.$name.'/'.$filename;
                    $post['cropped-'.$name] = $post[$name];
                }
                //$form_info['cropped-'.$name] = '/storage/personalized/'.$post['form_id'].'/'.$name.'/'.$filename;
            }
            unset($post['cropped']);
        }
        $post['images_fields'] = $images;
        $post['form_info'] = json_decode($post['form_info']);
        $request->session()->put('form_info', $post);

        return response()->json($post);
    }
    
    public function submitpersonalizedimages(Request $request) {
        $post = $request->except('_token');
        $formdata = $request->session()->get('formdata');
        $form_info = $request->session()->get('form_info');
        //echo '
'; print_r($post); print_r($form_info); echo '
'; exit; foreach($form_info['images_fields'] as $im ) { Log::debug(print_r($im, true)); $data = explode( ',', $post[$im] ); $image = base64_decode( $data[1] ); $filename = pathinfo($form_info[$im]); $filename = $filename['basename']; Storage::disk('public')->put('personalized/'.$post['form_id'].'/'.$im.'/cropped-'.$filename, $image); $form_info['cropped-'.$im] = str_replace($filename, 'cropped-'.$filename, $form_info[$im]); } $request->session()->put('form_info', $form_info); return redirect('/form/generatepersonalization'); } public function generatepersonalization(Request $request) { $post = $request->all(); $formdata = $request->session()->get('formdata'); $form_info = $request->session()->get('form_info'); //echo '
'; print_r($post); print_r($form_info); echo '
'; exit; $filename_prefix = 'combined'; if($form_info['form_id'] == '1739769123-c3c567f1-5d53-471b-bf69-5714c71e726e') { if($form_info['dr_name'] == 'other') { $filename_prefix = 'other'; } else { $token = DB::table('users')->select("access_token")->where("domain", 'vitalis1')->where("permissions", 'like', '%contact_get_one%')->orderBy('updated_at', 'desc')->skip(0)->take(1)->get(); $cont = LambdaRequest::getrequest('contact', 'contact/get_one', ['partition'=>'rapport-vitalis1', 'id'=>$form_info['dr_name'] ], $token[0]->access_token); $filename_prefix = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '_', $cont->data->item->name))); } switch($form_info['form_info']->id) { case '1739774514-c73f9f60-3c36-4c25-9a7b-bdd233be8bce': $form_info['dr_name'] = isset($cont->data->item->dia_beat_it_coupon_code) ? $cont->data->item->dia_beat_it_coupon_code : 'CIPDT15160'; break; case '1739774396-4ab417c8-180c-420f-b2c8-21cb14f27851': $form_info['dr_name'] = isset($cont->data->item->jaanch_diabetes_coupon_code) ? $cont->data->item->jaanch_diabetes_coupon_code : 'CIPJD15160'; break; case '1739772228-2d6ab664-ab17-4b08-ae2f-2e701c78ca74': $form_info['dr_name'] = isset($cont->data->item->healthy_heart_coupon_code) ? $cont->data->item->healthy_heart_coupon_code : 'CIPJH15160'; break; } //echo '
'; print_r($post); print_r($formdata); print_r($form_info); print_r($cont); echo '
'; exit; } $genareted_image = []; $pdf_images = []; foreach($form_info['form_info']->templates as $i => $template) { $temp = pathinfo($template); if(!file_exists(storage_path('app/public/personalized/'.$form_info['form_id'].'/template-'.$form_info['form_info']->id.'_'.$i.'.'.$temp['extension'] ))) { //Log::debug(print_r($form_info['form_info'], true)); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $template); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // good edit, thanks! curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); // also, this seems wise considering output is image. $data = curl_exec($ch); curl_close($ch); Storage::disk('public')->put('personalized/'.$form_info['form_id'].'/template-'.$form_info['form_info']->id.'_'.$i.'.'.$temp['extension'], $data); } $folder = storage_path('app/public/personalized/'.$form_info['form_id']); $templatename = 'template-'.$form_info['form_info']->id.'_'.$i.'.'.$temp['extension']; $outputImage = $this->retimage($folder.'/'.$templatename); $w = imagesx($outputImage); $h = imagesy($outputImage); //echo '
'; print_r(json_decode($form_info['form_info']->positions[$i])); echo '
'; exit; $positions = json_decode($form_info['form_info']->positions[$i]); $maskimages = []; foreach($positions as $pos) { if($pos->type == 'image' && isset($pos->fill) && $pos->fill == 'mask') { $maskimages[] = $pos; } } if(sizeof($maskimages) > 0) { $tempimage = imagecreatetruecolor($w, $h); } foreach($maskimages as $pos) { $image = storage_path( str_replace('/storage', 'app/public', $form_info['cropped-'.$pos->field_name] ) ); $photoimg = $this->retimage( $image ); $photosize = getimagesize( $image ); imagecopyresized($tempimage,$photoimg,$pos->x,$pos->y,0,0,$pos->width,$pos->height, $photosize[0], $photosize[1]); } if(sizeof($maskimages) > 0) { imagecopyresized($tempimage,$outputImage,0,0,0,0,$w,$h,$w,$h); $outputImage = $tempimage; } // if($form_info['form_id'] == '1743147283-6e501154-053c-4e99-bcfe-c7e3d432f704') { // // echo '
'; print_r(json_decode($form_info['form_info']->positions[$i])); exit;
            // }

            foreach(json_decode($form_info['form_info']->positions[$i]) as $pos) {
                switch($pos->type) {
                    case 'image':
                        // $image = storage_path( str_replace('/storage', 'app/public', $form_info['cropped-'.$pos->field_name] ) );
                        // $photoimg = $this->retimage( $image );
                        // $photosize = getimagesize( $image );
                        // if(isset($pos->fill) && $pos->fill == 'mask') {
                        //     // $w = imagesx($outputImage);
                        //     // $h = imagesy($outputImage);
                        //     // $tempimage = imagecreatetruecolor($w, $h);
                        //     // imagecopyresized($tempimage,$photoimg,$pos->x,$pos->y,0,0,$pos->width,$pos->height, $photosize[0], $photosize[1]);
                        //     // imagecopyresized($tempimage,$outputImage,0,0,0,0,$w,$h,$w,$h);
                        //     // $outputImage = $tempimage;
                        //     // //imagedestroy($tempimage);
                        // } else {
                        //     $image = storage_path( str_replace('/storage', 'app/public', $form_info['cropped-'.$pos->field_name] ) );
                        //     $photoimg = $this->retimage( $image );
                        //     $photosize = getimagesize( $image );
                        //     imagecopyresized($outputImage,$photoimg,$pos->x,$pos->y,0,0,$pos->width,$pos->height, $photosize[0], $photosize[1]);
                        // }
                        if(!(isset($pos->fill) && $pos->fill == 'mask')) {
                            $image = storage_path( str_replace('/storage', 'app/public', $form_info['cropped-'.$pos->field_name] ) );
                            $photoimg = $this->retimage( $image );
                            $photosize = getimagesize( $image );
                            imagecopyresized($outputImage,$photoimg,$pos->x,$pos->y,0,0,$pos->width,$pos->height, $photosize[0], $photosize[1]);
                        }
                        break;
                    case 'text':
                    case 'date':
                        if(isset($form_info['form_info']->createpdf) && isset($form_info['form_info']->createpdf[$i]) && $form_info['form_info']->createpdf[$i] == 'yes' && isset($form_info['form_info']->addlink) && $form_info['form_info']->addlink[$i] == 'yes' && $form_info['form_info']->linkfield[$i] == $pos->field_name) {
                            $linkvalue = $form_info[$pos->field_name];
                        } else if(isset($form_info[$pos->field_name])) {
                            $font = storage_path('app').'/fonts/'.$pos->font;
                            $pos->color = explode('-',$pos->color);
                            $white = imagecolorallocate($outputImage, $pos->color[0], $pos->color[1], $pos->color[2]);
                            $text = $form_info[$pos->field_name];
                            if(isset($pos->prefix) && !empty($pos->prefix)) {
                                $text = $pos->prefix . $text;
                            }
                            if($pos->type == 'date') {
                                $text = date($pos->format, strtotime($text));
                            }
                            if(isset($pos->suffix) && !empty($pos->suffix)) {
                                $text = $text . $pos->suffix;
                            }
                            if(isset($pos->align) && $pos->align == 'center') {
                                $box = imagettfbbox($pos->size, 0, $font, $text);
                                $pos->x = explode('-', $pos->x);
                                $pos->x = $pos->x[0] + (($pos->x[1] - $pos->x[0]) - $box[2])/2;
                            }
                            imagettftext($outputImage, $pos->size, 0, $pos->x, $pos->y, $white, $font, $text);

                            // if($form_info['form_id'] == '1743147283-6e501154-053c-4e99-bcfe-c7e3d432f704') { // 
                            //     echo '
'; print_r([$outputImage, $pos->size, 0, $pos->x, $pos->y, $white, $font, $text]); exit;
                            // }


                            //echo '
'; print_r([ $pos->color[0], $pos->color[1], $pos->color[2]]); echo '
'; exit; } break; case 'multiline': if(isset($form_info[$pos->field_name])) { $font = storage_path('app').'/fonts/'.$pos->font; $pos->color = explode('-',$pos->color); $white = imagecolorallocate($outputImage, $pos->color[0], $pos->color[1], $pos->color[2]); $text = $form_info[$pos->field_name]; $lines = wordwrap($text, $pos->linechars, "\n", true); $xPosition = $pos->x; $yPosition = $pos->y; foreach (explode("\n", $lines) as $line) { imagettftext($outputImage, $pos->size, 0, $xPosition, $yPosition, $white, $font, $line); $yPosition += $pos->linehieght; } } break; } } $filename = 'generated-'.strtotime("now").'_'.$i.'.png'; $genareted_image[] = $filename; if(isset($form_info['form_info']->createpdf[$i]) && $form_info['form_info']->createpdf[$i] == 'yes') { $pdf_images[] = $folder.'/'.$filename; } imagepng($outputImage, $folder.'/'.$filename); imagedestroy($outputImage); } //echo '
'; print_r($genareted_image); exit;
        
        $form_info['genareted_image'] = $genareted_image;
        $form_info['pdf_images'] = $pdf_images;

        if(isset($form_info['form_info']->createpdf) && count($form_info['form_info']->createpdf) > 0 && in_array('yes', $form_info['form_info']->createpdf) ) {
            //echo 'convert '.implode(' ', $form_info['pdf_images']).' -quality 100 '.$folder.'/'.'combined-'.strtotime("now").'.pdf'; exit;
            $pdffile = $filename_prefix.'-'.strtotime("now").'.pdf';
            if(count($form_info['pdf_images']) > 1) {
                exec('convert '.implode(' ', $form_info['pdf_images']).' -quality 100 '.$folder.'/'.$pdffile);
                $form_info['pdf_file'] = $pdffile;
            } else if(!isset($linkvalue)) {
                exec('convert '.implode(' ', $form_info['pdf_images']).' -quality 100 '.$folder.'/'.$pdffile);
                $form_info['pdf_file'] = $pdffile;
            } else {
                exec('php /home/ubuntu/createpdf/testpdf.php '.$w.' '.$h.' '.$form_info['pdf_images'][0].' '.$folder.'/'.$pdffile .' "'. $linkvalue.'"');
                Log::debug('php /home/ubuntu/createpdf/testpdf.php '.$w.' '.$h.' '.$form_info['pdf_images'][0].' '.$folder.'/'.$pdffile .' "'. $linkvalue.'"');
                //exec('convert '.implode(' ', $form_info['pdf_images']).' -quality 100 '.$folder.'/'.$pdffile);
                $form_info['pdf_file'] = $pdffile;
            }
        }
        $form_info['personalization_id'] = $form_info['form_info']->id;
        Log::debug(print_r($form_info, true));
        //echo '
'; print_r($form_info); echo '
'; exit; unset($form_info['form_info']); // $form_info['form_info']->positions = json_decode('[{"x":"100-279","y":"485","align":"center","size":20,"type":"text","font":"klavika-medium.ttf","color":"110-23-19","field_name":"event_date_date"},{"x":"100-279","y":"526","align":"center","size":22,"type":"text","font":"klavika-light.ttf","color":"110-23-19","field_name":"event_date_year"},{"x":"340-514","y":"485","align":"center","size":20,"type":"text","font":"klavika-medium.ttf","color":"110-23-19","field_name":"venue_line_3"},{"x":"584-767","y":"480","align":"center","size":18,"type":"text","font":"klavika-medium.ttf","color":"110-23-19","field_name":"venue_line_1"},{"x":"584-767","y":"508","align":"center","size":18,"type":"text","font":"klavika-medium.ttf","color":"110-23-19","field_name":"venue_line_2"},{"x":"584-767","y":"535","align":"center","size":18,"type":"text","font":"klavika-medium.ttf","color":"110-23-19","field_name":"venue_line_3"},{"x":"264-613","y":"910","align":"center","size":11,"type":"text","font":"gadugib.ttf","color":"0-0-0","field_name":"speaker_details_line_1"},{"x":"264-613","y":"930","align":"center","size":11,"type":"text","font":"gadugib.ttf","color":"0-0-0","field_name":"speaker_details_line_2"},{"x":"264-613","y":"950","align":"center","size":11,"type":"text","font":"gadugib.ttf","color":"0-0-0","field_name":"speaker_details_line_3"},{"x":"264-613","y":"970","align":"center","size":11,"type":"text","font":"gadugib.ttf","color":"0-0-0","field_name":"speaker_details_line_4"},{"x":362,"width":154,"y":658,"type":"image","fill":"mask","height":154,"field_name":"speaker_image"},{"x":"259-618","y":"873","align":"center","size":23,"type":"text","font":"klavika-medium.ttf","color":"255-255-255","field_name":"speaker_name"}]'); if(isset($formdata) && !empty($formdata) && $formdata->user_id != '') { $post = $this->processformdata($formdata->form_id, $post, $formdata->user_id, $formdata->partition); $finfo = LambdaRequest::postrequest('form', 'formentity/submitform', ['formdata' => $form_info, 'entity_id' => $formdata->form_id, 'user_id' => $formdata->user_id, 'partition' => $formdata->partition ]); } //return view('form.download')->with('image_url', 'personalized/'.$form_info['form_id'].'/'.$form_info['genareted_image']); $request->session()->put('form_info', $form_info); return redirect('/form/downloadpersonalization'); } public function downloadpersonalization(Request $request) { $form_info = $request->session()->get('form_info'); $formdata = $request->session()->get('formdata'); //Log::debug(print_r($form_info, true)); //Log::debug(print_r($formdata, true)); $folder = storage_path('app/public/personalized/'.$form_info['form_id']); $paths = []; if(isset($form_info['pdf_file'])) { $paths[] = $folder.'/'.$form_info['pdf_file']; } foreach($form_info['genareted_image'] as $image) { $paths[] = $folder.'/'.$image; } if($form_info['form_id'] == '1682181475-19f5d784-6fbb-4a6e-bf04-a448ff7c83fe') { switch($form_info['personalization_id']) { case '1682267328-bd38fe94-1b2e-47c1-a8bb-8ba361432cc7': $ppts[] = ["path" => '/ChestApprise/Home_Maintenance_Nebulization_Regional.pptx', "name" => 'Home_Maintenance_Nebulization_Regional.pptx' ]; $ppts[] = ["path" => '/ChestApprise/Nebulized_mucoactive_drugs_in_mucus_management_-_2023.pptx', "name" => 'Nebulized_mucoactive_drugs_in_mucus_management_-_2023.pptx' ]; break; case '1682267328-bd38fe95-1b2e-47c2-a8bb-8ba361432cc8': $ppts[] = ["path" => '/ChestConnect/Home_Maintenance_Nebulization_Regional.pptx', "name" => 'Home_Maintenance_Nebulization_Regional.pptx' ]; $ppts[] = ["path" => '/ChestConnect/Nb_Antibiotic_focusing_Tob.pptx', "name" => 'Nb_Antibiotic_focusing_Tob.pptx' ]; break; case '1682267328-bd38fe96-1b2e-47c3-a8bb-8ba361432cc9': $ppts[] = ["path" => '/EducatetoElevate/GINA_2022_Imp_of_ICS_in_asthma.pptx', "name" => 'GINA_2022_Imp_of_ICS_in_asthma.pptx' ]; $ppts[] = ["path" => '/EducatetoElevate/Nebulized_mucoactive_drugs_in_mucus_management_-_2023.pptx', "name" => 'Nebulized_mucoactive_drugs_in_mucus_management_-_2023.pptx' ]; break; case '1682267328-bd38fe97-1b2e-47c4-a8bb-8ba361432cc6': $ppts[] = ["path" => '/PediaConnect/GINA_2022_Pediatric_brief.pptx', "name" => 'GINA_2022_Pediatric_brief.pptx' ]; $ppts[] = ["path" => '/PediaConnect/Nebulized_mucoactive_drugs_in_mucus_management_-_2023.pptx', "name" => 'Nebulized_mucoactive_drugs_in_mucus_management_-_2023.pptx' ]; break; case '1682685456-f9dce443-bcee-462f-925e-ad148dad08f4': $ppts[] = ["path" => '/Assemble/Assemble_to_Adapt_ppt.pptx', "name" => 'Assemble_to_Adapt_ppt.pptx' ]; break; } foreach($ppts as $ppt) { $paths[] = $folder.'/'.$ppt['path']; } } if($request->input('action') == 'email') { // Create PHPMailer instance $provider = CredentialProvider::defaultProvider(); $gAWS_SES_client = SesClient::factory(array( 'version'=> 'latest', 'region' => 'ap-south-1', 'credentials' => $provider )); //$myArrayToAdresses = ["ravigulhane1983@gmail.com"]; Log::debug(print_r($request->all(), true) ); $myArrayToAdresses = [$request->input('email')]; $ppts = []; $ppthtml = ''; if($form_info['form_id'] == '1682181475-19f5d784-6fbb-4a6e-bf04-a448ff7c83fe') { foreach($ppts as $ppt) { $ppthtml .= ''.$ppt['name'].'
'; } } $myFromAdress = 'Rapport Support '; $mySubject = 'Generated Assets for Upcoming Event'; $myHTMLBody = '

Dear,

We hope this email finds you well. As part of our commitment to making our upcoming event a success, we are pleased to provide you with a few generated assets that we believe will be useful.

Attached to this email you will find:

  • Invitations: We have included a customized invitation that you can share with your attendees. It includes all the details of the event.
  • Thank You Letter: We have also attached a thank you letter that you can use to express your gratitude to attendees and sponsors after the event.
  • Presentation PPT: Lastly, we have included a presentation PowerPoint that you can use to promote the event or share with your attendees. below are the links to download the PPT.

' . $ppthtml . '

We believe that these assets will help you to promote the event more effectively and engage with your network more successfully. If you have any questions or concerns, please dont hesitate to reach out to your HO.

Thank you for your time and effort in organizing this event, and we look forward to working with you to make it a success.

Best regards,

'; $files = [ ["path" => $folder.'/'.$form_info['pdf_file'], "name" => $form_info['pdf_file'] ] ]; foreach($form_info['genareted_image'] as $image) { $files[] = ["path" => $folder.'/'.$image, "name" => $image ]; } // $zip = new \ZipArchive(); // $fileName = 'zipFile.zip'; // exec('rm ' . $folder.'/'.$fileName); // if ($zip->open($folder.'/'.$fileName, \ZipArchive::CREATE)== TRUE){ // //$files = File::files(public_path('myFiles')); // foreach ($files as $file){ // $zip->addFile($file['path'], $file['name']); // } // $zip->close(); // } $myStringToAddresses = implode(",", $myArrayToAdresses); $boundary = md5(time()); $html = $myHTMLBody; //$html .= ""; // Content-ID $text = $mySubject; $raw = ''; $raw .= "From:{$myFromAdress}\n"; $raw .= "To:{$myStringToAddresses}\n"; $raw .= "Subject:{$mySubject}\n"; $raw .= "MIME-Version: 1.0\n"; $raw .= "Content-Type: multipart/mixed; boundary=\"{$boundary}\"\n\n"; $raw .= "--{$boundary}\n"; $raw .= "Content-Type: multipart/alternative; boundary=\"sub_{$boundary}\"\n\n"; $raw .= "--sub_{$boundary}\n"; $raw .= "Content-Type: text/plain; charset=\"UTF-8\"\n"; $raw .= "\n"; $raw .= "{$text}\n"; $raw .= "\n"; $raw .= "--sub_{$boundary}\n"; $raw .= "Content-Type: text/html; charset=\"UTF-8\"\n"; $raw .= "Content-Disposition: inline\n"; $raw .= "\n"; $raw .= "{$html}\n"; $raw .= "\n"; $raw .= "--sub_{$boundary}--\n\n"; foreach ($files as $file) { $myFileMimeInfo = finfo_open(FILEINFO_MIME_TYPE); $myFileMimeType = finfo_file($myFileMimeInfo, $file['path']); $myFileName = basename($file['path']); $myDataAttachedFile = file_get_contents($file['path']); //$myDataAttachedFile = chunk_split(base64_encode($myDataAttachedFile)); $raw .= "--{$boundary}\n"; $raw .= "Content-Type:{$myFileMimeType}; name=\"{$file['name']}\"\n"; // name $raw .= "Content-Transfer-Encoding:base64\n"; $raw .= "Content-Disposition:attachment;filename=\"{$file['name']}\"\n"; // filename #$raw .= "Content-Disposition:inline;name={$file_name}\n"; $raw .= "Content-ID:<{$file['name']}>\n"; $raw .= "\n"; $raw .= base64_encode($myDataAttachedFile) . "\n"; $raw .= "\n"; } $raw .= "--{$boundary}--\n\n"; // $myStringToAddresses = implode(",", $myArrayToAdresses); // $mySeparator = md5(time()); // $mySeparator_multipart = md5($mySubject . time()); // $myMessage = ""; // $myMessage .= "MIME-Version: 1.0\n"; // $myMessage .= "To: ".$myStringToAddresses."\n"; // $myMessage .= "From:".$myFromAdress."\n"; // $myMessage .= "Subject:".$mySubject."\n"; // $myMessage .= "Content-Type: multipart/mixed; boundary=\"".$mySeparator_multipart."\"\n"; // $myMessage .= "\n--".$mySeparator_multipart."\n"; // $myMessage .= "Content-Type: multipart/alternative; boundary=\"".$mySeparator."\"\n"; // $myMessage .= "\n--".$mySeparator."\n"; // $myMessage .= "Content-Type: text/html; charset=\"UTF-8\"\n"; // $myMessage .= "\n".$myHTMLBody."\n"; // $myMessage .= "\n--".$mySeparator."--\n"; // $myFileName = basename($folder.'/'.$fileName); // $myDataAttachedFile = file_get_contents($folder.'/'.$fileName); // $myDataAttachedFile = chunk_split(base64_encode($myDataAttachedFile)); // $myFileMimeInfo = finfo_open(FILEINFO_MIME_TYPE); // $myFileMimeType = finfo_file($myFileMimeInfo, $folder.'/'.$fileName); // $myMessage .= "--".$mySeparator_multipart."\n"; // $myMessage .= "Content-Type: ".$myFileMimeType."; name=\"".$myFileName."\"\n"; // $myMessage .= "Content-Disposition: attachment; filename=\"".$myFileName."\"\n"; // $myMessage .= "Content-Transfer-Encoding: base64\n\n"; // $myMessage .= $myDataAttachedFile."\n"; // $myMessage .= "--".$mySeparator_multipart."--"; $myArraySES = [ 'Source' => $myFromAdress, 'Destinations' => $myArrayToAdresses, 'RawMessage' => [ 'Data' => $raw ] ]; //echo "\n
Trying to send mail via AAWS SES
\n"; try{ //$myResult = true; $myAPIResult = $gAWS_SES_client->sendRawEmail($myArraySES); Log::debug(print_r($myAPIResult, true)); return response()->json(['status' => 'success']); } catch (Exception $myObjError) { //An error happened and the email did not get sent $myErrorInfo = $myObjError->getMessage(); Log::debug(print_r($myErrorInfo, true)); return response()->json(['status' => 'failure']); } //return response()->json(['status' => 'success']); } else { //echo '
';print_r($form_info); exit;
            $res = ['folder' => 'personalized/'.$form_info['form_id'].'/', 'images' => $form_info['genareted_image'] ];
            $res['form_info'] = $form_info;
            if(isset($form_info['pdf_file'])) {
                $res['pdf_file'] = $form_info['pdf_file'];
            }
            if($form_info['form_id'] == '1682181475-19f5d784-6fbb-4a6e-bf04-a448ff7c83fe') {
                $encripted = base64_encode(json_encode($paths));
                $res['encripted'] = $encripted;
            }
            if (\View::exists('form.'.$formdata->partition.'.download-'.$formdata->form_id)) {
                return view('form.'.$formdata->partition.'.download-'.$formdata->form_id)->with($res);
            } else {
                return view('form.download')->with($res);
            }
        }
        //return view('form.download')->with($res);
    }

    public function downloadtempletepdf(Request $request) {
        $post = $request->all();
        $id = $post['id'];
        $formdata = $request->session()->get('formdata');
        $finfo = LambdaRequest::postrequest('form', 'formentity/getformdefination', ['form_id' => $formdata->form_id, 'user_id' => $formdata->user_id, 'partition' => $formdata->partition, 'id' => $id ]);
        //echo '
'; print_r($finfo); exit;
        foreach($finfo->data->personalizations as $pers) {
            if($pers->id == $finfo->data->formdata->personalization_id) {
                $personalisation = $pers;
            }
        }

        $genareted_image = [];
        $pdf_images = [];
        foreach($personalisation->templates as $i => $template) {
            $temp = pathinfo($template);
            if(!file_exists(storage_path('app/public/personalized/'.$formdata->form_id.'/template-'.$personalisation->id.'_'.$i.'.'.$temp['extension'] ))) {
                //Log::debug(print_r($form_info['form_info'], true));
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $template);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // good edit, thanks!
                curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); // also, this seems wise considering output is image.
                $data = curl_exec($ch);
                curl_close($ch);
                Storage::disk('public')->put('personalized/'.$formdata->form_id.'/template-'.$personalisation->id.'_'.$i.'.'.$temp['extension'], $data);
            }

            $folder = storage_path('app/public/personalized/'.$formdata->form_id);
            $templatename = 'template-'.$personalisation->id.'_'.$i.'.'.$temp['extension'];
            $outputImage = $this->retimage($folder.'/'.$templatename);
            $templatesize = getimagesize( $folder.'/'.$templatename );
            $pdfparams = ["width"=>$templatesize[0],"height"=>$templatesize[1]];

            //echo '
'; print_r($templatesize); echo '
'; exit; $positions = json_decode($personalisation->positions[$i]); $maskimages = []; foreach($positions as $pos) { if($pos->type == 'image' && isset($pos->fill) && $pos->fill == 'mask') { $maskimages[] = $pos; } } if(sizeof($maskimages) > 0) { $w = imagesx($outputImage); $h = imagesy($outputImage); $tempimage = imagecreatetruecolor($w, $h); } foreach($maskimages as $pos) { $image = storage_path( str_replace('/storage', 'app/public', $finfo->data->formdata->{$pos->field_name} ) ); $photoimg = $this->retimage( $image ); $photosize = getimagesize( $image ); imagecopyresized($tempimage,$photoimg,$pos->x,$pos->y,0,0,$pos->width,$pos->height, $photosize[0], $photosize[1]); } if(sizeof($maskimages) > 0) { imagecopyresized($tempimage,$outputImage,0,0,0,0,$w,$h,$w,$h); $outputImage = $tempimage; } foreach(json_decode($personalisation->positions[$i]) as $pos) { // if($pos->field_name == 'link') { // $pdfparams['link_params_x'] = $pos->x; // $pdfparams['link_params_y'] = $pos->y; // $pdfparams['link_params_url'] = $finfo->data->formdata->{$pos->field_name}; // continue; // } switch($pos->type) { case 'image': if(!(isset($pos->fill) && $pos->fill == 'mask')) { $image = storage_path( str_replace('/storage', 'app/public', $finfo->data->formdata->{$pos->field_name} ) ); $photoimg = $this->retimage( $image ); $photosize = getimagesize( $image ); imagecopyresized($outputImage,$photoimg,$pos->x,$pos->y,0,0,$pos->width,$pos->height, $photosize[0], $photosize[1]); } break; case 'text': case 'date': if(isset($finfo->data->formdata->{$pos->field_name})) { $font = storage_path('app').'/fonts/'.$pos->font; $pos->color = explode('-',$pos->color); $white = imagecolorallocate($outputImage, $pos->color[0], $pos->color[1], $pos->color[2]); $text = $finfo->data->formdata->{$pos->field_name}; if(isset($pos->prefix) && !empty($pos->prefix)) { $text = $pos->prefix . $text; } if($pos->type == 'date') { $text = date($pos->format, strtotime($text)); } if(isset($pos->suffix) && !empty($pos->suffix)) { $text = $text . $pos->suffix; } if(isset($pos->align) && $pos->align == 'center') { $box = imagettfbbox($pos->size, 0, $font, $text); $pos->x = explode('-', $pos->x); $pos->x = $pos->x[0] + (($pos->x[1] - $pos->x[0]) - $box[2])/2; } imagettftext($outputImage, $pos->size, 0, $pos->x, $pos->y, $white, $font, $text); } break; case 'multiline': if(isset($finfo->data->formdata->{$pos->field_name})) { $font = storage_path('app').'/fonts/'.$pos->font; $pos->color = explode('-',$pos->color); $white = imagecolorallocate($outputImage, $pos->color[0], $pos->color[1], $pos->color[2]); $text = $form_info[$pos->field_name]; $lines = wordwrap($text, $pos->linechars, "\n", true); $xPosition = $pos->x; $yPosition = $pos->y; foreach (explode("\n", $lines) as $line) { imagettftext($outputImage, $pos->size, 0, $xPosition, $yPosition, $white, $font, $line); $yPosition += $pos->linehieght; } } break; } } $filename = 'generated-'.strtotime("now").'_'.$i.'.png'; $genareted_image[] = $filename; imagepng($outputImage, $folder.'/'.$filename); imagedestroy($outputImage); $res = ['folder' => 'personalized/'.$formdata->form_id.'/', 'images' => $genareted_image, 'form_info' => (array)$finfo->data->formdata ]; if (\View::exists('form.'.$formdata->partition.'.download-'.$formdata->form_id)) { return view('form.'.$formdata->partition.'.download-'.$formdata->form_id)->with($res); } else { return view('form.download')->with($res); } } } public function downloadpersonalizationzip($files, Request $request) { $post = $request->input(); $files = json_decode(base64_decode($files)); $folder = storage_path('app/public/personalized'); $zip = new \ZipArchive(); $fileName = 'assets.zip'; exec('rm ' . $folder.'/'.$fileName); if ($zip->open($folder.'/'.$fileName, \ZipArchive::CREATE)== TRUE){ //$files = File::files(public_path('myFiles')); foreach ($files as $file){ $zip->addFile($file, basename($file)); } $zip->close(); } return response()->download($folder.'/'.$fileName); // echo '
'; print_r($files); exit;
    }

    protected function sanitizeForCSV($value) {
        $value = trim($value);
        if (preg_match('/^[=+\-@]/', $value)) {
            return "'".$value;
        }
        return $value;
    }

    public function downloaddata(Request $request) {
        $formdata = $request->session()->get('formdata');
        //$request->session()->put('finfo', $finfo);
        $post = $request->all();
        // Log::debug(print_r($formdata, true));
        // if(is_array($formdata)) {
        //     $formdata = (object)$formdata;
        // }
        
        $form_id = $request->input('form_id', $formdata->form_id);
        if(($form_id == '1718178830-d871301e-312b-4a60-9c68-15afa4ce6163' && (in_array('1655449173-a39a5017-8232-4d58-a253-90d06bc733d0', $formdata->roles) || in_array('1655449172-a39a5017-8232-4d58-a253-90d06bc733d0', $formdata->roles) || in_array('1655449171-a39a5017-8232-4d58-a253-90d06bc733d0', $formdata->roles) || in_array('1655449687-6ea4a5f3-4eb6-48b0-9bd5-2ddf08e44ef79', $formdata->roles) || in_array('1655449685-6ea4a5f3-4eb6-48b0-9bd5-2ddf08e44ef75', $formdata->roles) || in_array('1655449682-6ea4a5f3-4eb6-48b0-9bd5-2ddf08e44ef7', $formdata->roles) || in_array('1655449171-a39a5017-8232-4d58-a253-90d06bc733d0', $formdata->roles) || in_array('1655449172-a39a5017-8232-4d58-a253-90d06bc733d0', $formdata->roles) || in_array('1655449173-a39a5017-8232-4d58-a253-90d06bc733d0', $formdata->roles) || in_array('1655449174-a39a5017-8232-4d58-a253-90d06bc733d0', $formdata->roles) || in_array('1655449175-a39a5017-8232-4d58-a253-90d06bc733d0', $formdata->roles) || in_array('1655449176-a39a5017-8232-4d58-a253-90d06bc733d0', $formdata->roles) || in_array('1655449177-a39a5017-8232-4d58-a253-90d06bc733d0', $formdata->roles) || in_array('1655449178-a39a5017-8232-4d58-a253-90d06bc733d0', $formdata->roles) || in_array('1655449179-a39a5017-8232-4d58-a253-90d06bc733d0', $formdata->roles)  ) ) || 
        (($form_id == '1713425460-8bdf7394-01b5-48f3-8985-343b465dd685' || $form_id == '1713426268-c89f38eb-ec32-43ba-a81b-b690a8f90d6a') && (in_array('1655449175-a39a5017-8232-4d58-edm-90d06bc733d0', $formdata->roles) || in_array('1655445669-148e5dc2-3983-4ec6-bfho-a52c494a92132', $formdata->roles) || in_array('1655449179-a39a5017-8232-4d58-rbm-90d06bc733d0', $formdata->roles) ) ) ) {
            $finfo = $request->session()->get('finfo');
            $history = LambdaRequest::postrequest('form', 'formentity/getforminfo', ['finfo' => $finfo, 'limit' => 99999]);
            //echo '
'; print_r($finfo); exit;
        } else {
            $history = LambdaRequest::postrequest('form', 'formentity/getformhistory', ['form_id' => $form_id, 'user_id' => $formdata->user_id, 'partition' => $formdata->partition, 'team_report' => 1, 'json_file' => 1 ]);
            $history->data->submissions = json_decode(file_get_contents( $history->data->submission_json ), false);
            $history->data->submissions = $history->data->submissions->submissions;
        }
        //echo '
';
        Log::debug(print_r($history, true));
        $exceldata = [];
        $exceldata[] = [$formdata->title];
     
        $exceldata[] = [''];
        $headers = ['Submission Date', 'Submitted By', 'Employee Code', 'Approval Status'];
        foreach($history->data->questions as $question) {
            $headers[] = $question->label;
        }
        $exceldata[] = $headers;
        foreach($history->data->submissions as $submission) {
            $row = [];
            $row[] = isset($submission->createdAt) ? $submission->createdAt : '-'; //$submission->createdAt;
            $row[] = isset($submission->user_info->name) ? $submission->user_info->name : '';
            $row[] = isset($submission->user_info->employee_code) ? $submission->user_info->employee_code : '';
            $row[] = isset($submission->workflow_status) ? $submission->workflow_status : '';
            foreach($history->data->questions as $q => $v) {
                $row[] = isset($submission->formdata->{$q}) ? $this->sanitizeForCSV(htmlspecialchars($submission->formdata->{$q})) : '-';
            }
            $exceldata[] = $row;
        }


        if(isset($post['email']) && $post['email'] == 1) {
            $report = Excel::raw(new InvoicesExport($exceldata), 'Xlsx');
            $data = new \StdClass;
            $data->sender_name = 'Rapport Support';
            $data->sender_email = 'support@stratawiz.com';
            $data->subject = 'Attached Report';
            $data->body = '';
            $data->attachment = $report;
            $data->attachment_name = 'report.xlsx';

            Mail::to( $history->data->user_details->email )->send(new ReportExcel($data));
            
            response()->json(['status' => 'success']); 
        } else {
            return Excel::download(new InvoicesExport($exceldata), $formdata->title.'.xlsx');
        }

        

        //echo $report;
        // Excel::create($formdata->title, function($excel) {
        //     $excel->sheet('Form Data', function($sheet) {
        //         $sheet->fromArray($exceldata);
        //     });
        // });


        // Excel::create(new InvoicesExport($exceldata), 'public/'.$filename)->download('xlsx');

        // $report = Excel::raw(new InvoicesExport($exceldata), 'Xlsx');
        // $data->attachment = $report;
        // $data->attachment_name = 'report.xlsx';

        // //Mail::to( str_replace(Auth::user()->domain.'-','', Auth::user()->email) )->send(new ReportExcel($data));
        // //Mail::to( 'ravigulhane1983@gmail.com' )->send(new ReportExcel($data));
        // if($s3) {
        //     $filename = 'reports/'.strtotime("now").'-report.xlsx';
        //     $res = Excel::store(new InvoicesExport($exceldata), 'public/'.$filename);
        //     Log::debug(print_r($res, true));
        //     Log::debug('/storage/'.$filename);
        //     return response()->json(['sent' => 'yes', 'filename' => '/storage/'.$filename]);
        // } else {
        //     Mail::to( $response->data->user->email )->send(new ReportExcel($data));
        //     return response()->json(['sent' => 'yes']);
        // }



        // echo '
'; print_r($history); print_r($formdata); exit;

        // $form_id = $request->input('form_id', '');
        // echo $form_id; exit;
    }

    protected function retimage($image) {
        $size = getimagesize($image);
        switch ($size['mime']) {
            case 'image/jpeg':
                $photoimg = imagecreatefromjpeg($image);
                break;
            case 'image/png':
                $photoimg = imagecreatefrompng($image);
                break;
            case 'image/jpeg':
                $photoimg = imagecreatefrompng($image);
                break;
            default:
                # code...
                break;
        }
        return $photoimg;
    }

    public function getdoctorlist(Request $request) {
        $response = LambdaRequest::getrequest('contact', 'contact/get_my_contacts', ['hierarchy' => $request->input('hierarchy', ''), 'partition' => $request->input('partition', '') ]);
        $docs = [];
        foreach($response->data->items as $item) {
            $docs[] = ['value' => $item->id, 'display' => $item->name, 'contact' => $item];  
        }
        return response()->json($docs);
    }

    public function surveyhandle($finfo, Request $request) {
        $request->session()->put('finfo', $finfo);
        $finfo = LambdaRequest::postrequest('form', 'survey/getforminfo', ['finfo' => $finfo]);
        // echo '
'; print_r($finfo); exit;
        $request->session()->put('formdata', $finfo->data->formdata);
        if($finfo->status == 'success' && $finfo->data->formdata->link_type == 'form') {
            //return $this->deliverform($finfo->data->formdata, $finfo->data->questions);
            $formdata = $finfo->data->formdata;
            $questions = $finfo->data->questions;
            $data = ['questions' => $questions, 'form' => $formdata, 'form_id' => $formdata->form_id, 'id' => false];
            if (\View::exists('srvey.'.$formdata->partition.'.'.$formdata->form_id)) {
                return view('srvey.'.$formdata->partition.'.'.$formdata->form_id)->with($data);
            } elseif (\View::exists('form.'.$formdata->form_id)) {
                return view('srvey.'.$formdata->form_id)->with($data);
            } else {
                // return $data;
                return view('srvey.common')->with($data);
            }

        } elseif($finfo->status == 'success' && $finfo->data->formdata->link_type == 'list') {
            //echo '
'; print_r($finfo->data); exit;
            if (\View::exists('survey.list-'.$finfo->data->formdata->form_id)) {
                return view('srvey.list-'.$finfo->data->formdata->form_id)->with(['questions' => $finfo->data->questions, 'submissions' => $finfo->data->submissions, 'formname' => $finfo->data->formdata->title, 'form_id' => $finfo->data->formdata->form_id, 'lastkey' => $finfo->data->lastkey ]);
            } else {
                return view('srvey.list')->with(['questions' => $finfo->data->questions, 'submissions' => $finfo->data->submissions, 'formname' => $finfo->data->formdata->title, 'form_id' => $finfo->data->formdata->form_id, 'lastkey' => $finfo->data->lastkey ]);
            }
        }
    }

    public function ajaxsurveysubmit(Request $request) {
        $post = $request->except('_token');
        $files = $request->file();
        foreach($files as $fname => $file) {
            $post[$fname] = $this->_uploadMedia($request, $fname, 'form/'.$post['form_id'].'/'.$fname);
        }
        if(isset($post['id']) && $post['id']=='') unset($post['id']);
        $formdata = $request->session()->get('formdata');
        if(isset($post['user_id']) && $post['user_id'] != '') {
            $formdata->user_id = $post['user_id'];
        }
        if(isset($formdata) && !empty($formdata) && $formdata->user_id != '') {
            $post = $this->processformdata($formdata->form_id, $post, $formdata->user_id, $formdata->partition);
            $finfo = LambdaRequest::postrequest('form', 'survey/submitform', ['formdata' => $post, 'entity_id' => $formdata->form_id, 'user_id' => $formdata->user_id, 'partition' => $formdata->partition ]);

            if($formdata->form_id == '1674212914-9f377f34-4762-4b40-team3-8b282d183332') {
                unset($post['form_id']);
                Log::debug(print_r($post, true));
                //echo '
'; print_r($post); exit;
                $handler = curl_init();
                curl_setopt($handler, CURLOPT_URL, "https://gnpdoctor.buildrapport.co/neblogisticsave/ciplatodoctor");
                curl_setopt($handler, CURLOPT_POSTFIELDS, http_build_query($post));
                curl_setopt($handler, CURLOPT_POST, 1);
                curl_setopt($handler, CURLOPT_RETURNTRANSFER, true);
                $response = curl_exec($handler);
                Log::debug(print_r($response, true));
            }
            if($formdata->form_id == '1711710347-b4f08442-60dc-4a4c-a9c7-a759d95c5cad') {
                unset($post['form_id']);
                Log::debug(print_r($post, true));
                $handler = curl_init();
                curl_setopt($handler, CURLOPT_URL, "https://gnpdoctor.buildrapport.co/neblogisticsave/faultynebulizer");
                curl_setopt($handler, CURLOPT_POSTFIELDS, http_build_query($post));
                curl_setopt($handler, CURLOPT_POST, 1);
                curl_setopt($handler, CURLOPT_RETURNTRANSFER, true);
                $response = curl_exec($handler);
                Log::debug(print_r($response, true));
            }
            
            if($finfo->status == 'success') {
                return response()->json(['status' => 'success']);
            } else {
                return response()->json(['status' => 'failure']);
            }          
        } else {
            return response()->json(['status' => 'failure']);
        }
    }

    public function quizhandle($finfo, Request $request) {
        $request->session()->put('finfo', $finfo);
        $finfo = LambdaRequest::postrequest('form', 'quiz/getforminfo', ['finfo' => $finfo]);
        //echo '
'; print_r($finfo); exit;
        $request->session()->put('formdata', $finfo->data->formdata);
        if($finfo->status == 'success' && $finfo->data->formdata->link_type == 'form') {
            //return $this->deliverform($finfo->data->formdata, $finfo->data->questions);
            $formdata = $finfo->data->formdata;
            $questions = $finfo->data->questions;
            $quiztype = isset($formdata->quiz_type) ? $formdata->quiz_type : 'quiz';

            $data = ['questions' => $questions, 'form' => $formdata, 'form_id' => $formdata->form_id, 'id' => false];
            if (\View::exists($quiztype.'.'.$formdata->partition.'.'.$formdata->form_id)) {
                return view($quiztype.'.'.$formdata->partition.'.'.$formdata->form_id)->with($data);
            } elseif (\View::exists($quiztype.'.'.$formdata->form_id)) {
                return view($quiztype.'.'.$formdata->form_id)->with($data);
            } else {
                // return $data;
                return view($quiztype.'.common')->with($data);
            }

        } elseif($finfo->status == 'success' && $finfo->data->formdata->link_type == 'list') {
            //echo '
'; print_r($finfo->data); exit;
            if (\View::exists('quiz.list-'.$finfo->data->formdata->form_id)) {
                return view('quiz.list-'.$finfo->data->formdata->form_id)->with(['questions' => $finfo->data->questions, 'submissions' => $finfo->data->submissions, 'formname' => $finfo->data->formdata->title, 'form_id' => $finfo->data->formdata->form_id, 'lastkey' => $finfo->data->lastkey ]);
            } else {
                return view('quiz.list')->with(['questions' => $finfo->data->questions, 'submissions' => $finfo->data->submissions, 'formname' => $finfo->data->formdata->title, 'form_id' => $finfo->data->formdata->form_id, 'lastkey' => $finfo->data->lastkey ]);
            }
        }
    }

    public function ajaxquizsubmit(Request $request) {
        $post = $request->except('_token');
        $formdata = $request->session()->get('formdata');
        //print_r($formdata); exit;


        if(isset($post['user_id']) && $post['user_id'] != '') {
            $formdata->user_id = $post['user_id'];
        }
        if(isset($formdata) && !empty($formdata) && $formdata->user_id != '') {
            //echo '
'; print_r(['formdata' => $post, 'entity_id' => $formdata->form_id, 'user_id' => $formdata->user_id, 'partition' => $formdata->partition ]); exit;
            $finfo = LambdaRequest::postrequest('form', 'quiz/submitform', ['formdata' => $post, 'entity_id' => $formdata->form_id, 'user_id' => $formdata->user_id, 'partition' => $formdata->partition ]);
            //echo '
'; print_r($finfo); exit;
            if($finfo->status == 'success') {
                return response()->json(['status' => 'success', 'submission' => $finfo->data->submission, 'answers' => $finfo->data->answers]);
            } else {
                return response()->json(['status' => 'failure']);
            }          
        } else {
            return response()->json(['status' => 'failure']);
        }
    }

    public function zipmultiple(Request $request) {
        $files = $request->input('files', []);
        $response = LambdaRequest::postrequest('form', 'formentity/zipmultiple', ['files' => $files], '');
        //Log::debug(print_r($response, true));
        return response()->json($response->data);
    }

    public function competitioncontest(Request $request) {
        $token = $request->header('Authorization');
        if($token != '') {
            $request->session()->put('metric_access_key', $token);
        } else {
            $token = $request->session()->get('metric_access_key');
        }

        $page = $request->input('page', 'scores');
        switch($page) {
            case 'scores':
                $response = LambdaRequest::getrequest('competition', 'contest/list', ['scores' => 'yes'], $token);
                return view('competition.appcontest', ['title' => 'Live Scores', 'scores' => $response->data->items, 'page' => $page]);
                break;
            case 'schedule':
                $response = LambdaRequest::getrequest('competition', 'contest/list', [], $token);
                return view('competition.appcontest', ['title' => 'Schedule', 'schedules' => $response->data->items, 'page' => $page]);
                break;
            case 'table':
                $response = LambdaRequest::getrequest('ums', 'team/list', [], $token);
                return view('competition.appcontest', ['title' => 'Points Table', 'teams' => $response->data->items, 'page' => $page]);
                break;
        }
    }

    public function iframeupload(Request $request) {
        return view('form.iframeupload');
    }

    public function allsubmissions(Request $request) {
        $post = $request->all();
        $user = Auth::user();
        $filters = $post;
        unset($filters['partition']);
        unset($filters['form_id']);
        unset($filters['download']);
        //print_r(['partition' => $post['partition'], 'form_id'=>$post['form_id'], 'filters' => json_encode($filters) ]); exit;
        $history = LambdaRequest::signedrequest('post', 'form', 'formentity/getallsubmissions', ['partition' => $post['partition'], 'form_id'=>$post['form_id'], 'filters' => json_encode($filters) ], 120);
        if(isset($post['download'])) {
            $exceldata = [];
            $headers = ['User Name','User Email','User Phone', 'Submitted On'];
            foreach($history->data->questions as $que) {
                $headers[] = $que->question;
            }
            $exceldata[] = $headers;
            $submissions = json_decode(file_get_contents( $history->data->submission_json ), false);
            //echo '
'; print_r($submissions); exit;
            foreach($submissions as $sub) {
                $subs = [$sub->submitted_by, $sub->user_email, $sub->user_phone, $sub->submitted_on];
                foreach($history->data->questions as $que) {
                    $subs[] = $sub->{$que->code};
                }
                $exceldata[] = $subs;
            }
            $report = Excel::raw(new InvoicesExport($exceldata), 'Xlsx');
            $filename = 'reports/'.$post['form_id'].'-report.xlsx';
            $res = Excel::store(new InvoicesExport($exceldata), 'public/'.$filename);
            $headers = array( 'Content-Type: application/excel', );
            return Response::download(storage_path('app/public')."/".$filename, $post['form_id'].'-report.xlsx', $headers);            
        } else {
            //echo '
'; print_r((array)$history->data); exit;
            if (\View::exists('form.'.$post['partition'].'.'.$post['form_id'].'-allsubmissions')) {
                return view('form.'.$post['partition'].'.'.$post['form_id'].'-allsubmissions')->with((array)$history->data);
            } elseif (\View::exists('form.'.$post['form_id'].'-allsubmissions')) {
                return view('form.'.$post['form_id'].'-allsubmissions')->with((array)$history->data);
            } else {
                return view('form.allsubmissions')->with((array)$history->data);
            }
        }
    }

    public function fullworkflow(Request $request) {
        $post = $request->all();
        $user = Auth::user();
        $history = LambdaRequest::signedrequest('post', 'form', 'formentity/getallsubmissions', ['form_id' => $post['form_id'], 'approver' => Auth::user()->user_id, 'partition' => $post['partition']], 120);
        //echo '
'; print_r($history); exit;
        if(isset($post['download'])) {
            $exceldata = [];
            $headers = ['User Name','User Email','User Phone', 'Submitted On'];
            foreach($history->data->questions as $que) {
                $headers[] = $que->question;
            }
            $exceldata[] = $headers;
            $submissions = json_decode(file_get_contents( $history->data->submission_json ), false);
            foreach($submissions as $sub) {
                $subs = [$sub->submitted_by, $sub->user_email, $sub->user_phone, $sub->submitted_on];
                foreach($history->data->questions as $que) {
                    $subs[] = $sub->{$que->code};
                }
                $exceldata[] = $subs;
            }
            $report = Excel::raw(new InvoicesExport($exceldata), 'Xlsx');
            $filename = 'reports/'.$post['form_id'].'-report.xlsx';
            $res = Excel::store(new InvoicesExport($exceldata), 'public/'.$filename);
            $headers = array( 'Content-Type: application/excel', );
            return Response::download(storage_path('app/public')."/".$filename, $post['form_id'].'-report.xlsx', $headers);            
        } else {
            //echo '
'; print_r((array)$history->data); exit;
            if (\View::exists('form.'.$post['partition'].'.'.$post['form_id'].'-fullworkflow')) {
                return view('form.'.$post['partition'].'.'.$post['form_id'].'-fullworkflow')->with((array)$history->data);
            } elseif (\View::exists('form.'.$post['form_id'].'-fullworkflow')) {
                return view('form.'.$post['form_id'].'-fullworkflow')->with((array)$history->data);
            } else {
                return view('form.fullworkflow')->with((array)$history->data);
            }
        }
    }

    public function uploadchunk(Request $request) {
        $path = '';
        $name = 'chunk_video';
        $folder = 'chunk_video';
        try {
            if( $request->file($name) ) {
                $path = $request->file($name)->store($folder);
                $path = '/'.str_replace('public', 'storage', $path);
            }
        } catch (AwsException $e) {
            Log::debug($e->getMessage());
        }
        return response()->json(['status' => 'success', 'filepath' => $path ]);
        return $path;
    }

    public function respidoctorsearch(Request $request) {
        $search = $request->input('q', '');
        $user_id = $request->input('user_id', '');
        $doctors = DB::table('copd_respi_clinic_others_tagg')
        ->select("id","name","msl_code","speciality","legacy_code")
        ->where('user_id', $user_id)
        ->where(function ($query) use ($search) {
            $query->where('name', 'like', '%'.$search.'%')
                ->orWhere('email', 'like', '%'.$search.'%')
                ->orWhere('msl_code', 'like', '%'.$search.'%')
                ->orWhere('speciality', 'like', '%'.$search.'%')
                ->orWhere('legacy_code', 'like', '%'.$search.'%');
        })->get();
        return response()->json(['doctors' => $doctors]);
    }

    public function addrespidoctor(Request $request) {
        $id = $request->input('id', '');
        $partition = $request->input('partition', '');
        $user_id = $request->input('user_id', '');
        list($application, $domain) = explode("-", $partition);
        $token = DB::table('users')->select("access_token")->where("domain", $domain)->where("permissions", 'like', '%contact_create%')->orderBy('updated_at', 'desc')->skip(0)->take(1)->get();
        $doctor = DB::table('copd_respi_clinic_others_tagg')->where('id', $id)->first();
        $contactdata = [
            'domain' => $domain,
            'application' => $application,
            'user_id' => $user_id,
            'name' => $doctor->name,
            'email' => $doctor->email,
            'phone' => $doctor->phone,
            'msl_code' => $doctor->msl_code,
            'speciality' => $doctor->speciality,
            'legacy_code' => $doctor->legacy_code,
            'respi_clinic_dr' => 'Yes',
        ];
        $cont = LambdaRequest::postrequest('contact', 'contact/create', $contactdata, $token[0]->access_token);
        
        return response()->json(['contact' => $cont->data->item]);
    }

    public function getidrivedoctowisedownload(Request $request) {
        $post = $request->all();
        $token = $request->header('Authorization', false);
        if($token) {
            $response = LambdaRequest::postrequest('rcpa', 'reports/doctorwise_download', $post, $token);
            return Response::json($response);
        } else {
            return Response::json(['error' => 'Unauthorized']);
        }
        
    }

    public function nebmitraverification(Request $request) {
        $user = Auth::user();
        $post = ['partition' => 'rapport-'.$user->domain, 'form_id' => '1718178830-d871301e-312b-4a60-nebmitra-15afa4ce6163'];
        $history = LambdaRequest::signedrequest('post', 'form', 'formentity/getallsubmissions', ['form_id' => $post['form_id'], 'partition' => $post['partition']], 120);

        if (\View::exists('form.'.$post['partition'].'.'.$post['form_id'].'-allsubmissions')) {
            return view('form.'.$post['partition'].'.'.$post['form_id'].'-allsubmissions')->with((array)$history->data);
        } elseif (\View::exists('form.'.$post['form_id'].'-allsubmissions')) {
            return view('form.'.$post['form_id'].'-allsubmissions')->with((array)$history->data);
        } else {
            return view('form.allsubmissions')->with((array)$history->data);
        }

        //echo '
'; print_r($history); exit;
    }

    public function ajaxdoctortagging(Request $request) {
        $post = $request->except('_token');
        list($application, $domain) = explode("-", $post['partition']);
        $token = DB::table('users')->select("access_token")->where("domain", $domain)->where("permissions", 'like', '%contact_create%')->orderBy('updated_at', 'desc')->skip(0)->take(1)->get();
        $contactdata = $post;
        $contactdata['domain'] = $domain; 
        $contactdata['application'] = $application;
        unset($contactdata['partition']);
        $cont = LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token[0]->access_token);
        Log::debug(print_r($contactdata, true));
        return response()->json(['status' => 'success']);
    }
}