_service = 'form'; $this->_module = 'formaction'; $this->_viewname = 'formaction'; $this->_title = 'Quick Actions'; $this->_base_url = '/formaction'; } protected function sessionAttr($data, $key, $default = null) { if (is_object($data) && isset($data->{$key})) { return $data->{$key}; } if (is_array($data) && array_key_exists($key, $data)) { return $data[$key]; } return $default; } protected function sessionFlag($data, $key) { $value = $this->sessionAttr($data, $key, false); return $value === true || $value === 1 || $value === '1' || $value === 'true'; } 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 ($formdata->form_id == '1731413373-65062594-7136-45b2-a846-b34be9afe3b9') {
        //     // For debug: print $data
        //     echo '
' . print_r($data, true) . '
'; exit; // } // $pid = $formdata->partition; // $fid = $formdata->form_id; // $base = '/var/www/rapport/resources/views/form'; // if (is_file("$base/$pid/$fid.blade.php")) { // return view("form.$pid.$fid", $data); // } elseif (is_file("$base/$fid.blade.php")) { // return view("form.$fid", $data); // } // elseif(isset($formdata->form_type) && $formdata->form_type == 'enrollment_form'){ // return view('form.common-enrollmentform', $data); // } // elseif(isset($formdata->form_type) && $formdata->form_type == 'plan_vs_execution'){ // return view('form.common-planexecution', $data); // } // else { // return view('form.common', $data); // } 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); } elseif(isset($formdata->form_type) && $formdata->form_type == 'enrollment_form'){ return view('form.common-enrollmentform', $data); } elseif(isset($formdata->form_type) && $formdata->form_type == 'plan_vs_execution'){ return view('form.common-planexecution', $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->status) || $finfo->status !== 'success' || !isset($finfo->data)) {
            return redirect('/formaction/consolelist')->withError('Unable to load form. Please try again.');
        }

        $formdata = null;
        if (isset($finfo->data->formdata)) {
            $formdata = $finfo->data->formdata;
        } elseif (isset($finfo->data->form)) {
            $formdata = $finfo->data->form;
            $finfo->data->formdata = $formdata;
        }

        if (!$formdata) {
            return redirect('/formaction/consolelist')->withError('Form data not found.');
        }

        if (isset($finfo->data->users) && sizeof($finfo->data->users) > 0) {
            $formdata->users = $finfo->data->users;
            $formdata->manager_can_submit = true;
        }

        $request->session()->put('formdata', $formdata);

        if ($formdata->link_type == 'form' && isset($finfo->data->personalizations) && sizeof($finfo->data->personalizations) > 0) {
            return $this->deliverpersonalization($formdata, $finfo->data->questions, $finfo->data->personalizations);
        } elseif ($formdata->link_type == 'form') {
            return $this->deliverform($formdata, $finfo->data->questions);
        } elseif ($formdata->link_type == 'list') {
            $form = $finfo->data->form ?? $formdata;
            $showPositions = $form->show_positions ?? $form->show_position ?? 'no';
            $positionColumns = $this->getAvailablePositionColumns($finfo->data->submissions ?? [], $showPositions);
            $userAttrs = $this->userAttributeCodes($form);
            $userAttrLabels = $this->resolveUserAttributeLabels($userAttrs);
            $listViewData = [
                'questions' => $finfo->data->questions,
                'submissions' => $finfo->data->submissions,
                'formname' => $formdata->title,
                'form_id' => $formdata->form_id,
                'lastkey' => $finfo->data->lastkey,
                'formdata' => $formdata,
                'form' => $form,
                'positionColumns' => $positionColumns,
                'userAttrs' => $userAttrs,
                'userAttrLabels' => $userAttrLabels,
            ];
            if (\View::exists('form.'.$formdata->partition.'.list-'.$formdata->form_id)) {
                return view('form.'.$formdata->partition.'.list-'.$formdata->form_id)->with($listViewData);
            } elseif (\View::exists('form.list-'.$formdata->form_id)) {
                return view('form.list-'.$formdata->form_id)->with($listViewData);
            } elseif (\View::exists('form.'.$formdata->partition.'.list')) {
                return view('form.'.$formdata->partition.'.list')->with($listViewData);
            } else {
                return view('form.list')->with($listViewData);
            }
        }
        return redirect('/formaction/consolelist')->withError('Unable to load form. Please try again.');
    }

    public function loadmore(Request $request) {
        //$finfo = $request->session()->get('finfo');
        //echo $finfo; exit;
        $lastkey = $request->input('lastkey', '');
        $partition = (string) ($request->input('partition') ?? '');
        $alldata = $request->input('alldata', 0);
        $user_id = (string) ($request->input('user_id') ?? '');
        $form_id = (string) ($request->input('form_id') ?? '');
        $team_report = $request->input('team_report', 0);

        $serviceParams = ['lastkey' => $lastkey, 'partition' => $partition, 'form_id' => $form_id];
        if ($user_id !== '') {
            $serviceParams['user_id'] = $user_id;
        }
        if($alldata == 1) {
            $serviceParams['alldata'] = 1;
        } else if($team_report == 1) {
            $serviceParams['team_report'] = 1;
        }
        $startdate = trim((string) ($request->input('startdate') ?? ''));
        $enddate = trim((string) ($request->input('enddate') ?? ''));
        if ($startdate !== '' && $enddate !== '') {
            $serviceParams['date_range'] = [$startdate, $enddate];
        }

        $keyword = trim((string) $request->input('keyword', ''));
        if ($keyword !== '') {
            $serviceParams['keyword'] = $keyword;
        }

        $submission_status = $request->input('submission_status', '');
        if ($submission_status !== '' && $submission_status !== null) {
            $serviceParams['filters'] = json_encode([
                'formdata.submission_status' => $submission_status,
            ]);
        }

        $originalFormId = $form_id;

        $aliasForms = [
            '1771861147-eb801858-8520-45e9-aa5c-239b6bacdf98' 
                => '1750914801-153443b9-94d0-4dcb-b3f3-4fa11588a0a9'
        ];

        if (isset($aliasForms[$form_id])) {
            $form_id = $aliasForms[$form_id];
        }

        $serviceParams['form_id'] = $form_id;

        if ($form_id == '1750914801-153443b9-94d0-4dcb-b3f3-4fa11588a0a9') {
            $serviceParams['sort'] = ['created_date' => -1];
        }
        
        //print_r(json_encode($serviceParams)); exit;
        $finfo = LambdaRequest::postrequest('form', 'formentity/getformhistory', $serviceParams);
        // Log::debug(print_r(['to test view'], true));

        // Log::debug(print_r($finfo, true));

        //return response()->json(['finfo' => $finfo]);
        // print_r($finfo); exit;
        if (!is_object($finfo) || !isset($finfo->data) || !is_object($finfo->data)) {
            Log::error('loadmore: invalid getformhistory response', ['params' => $serviceParams, 'response' => $finfo]);
            return response()->json(['rows' => [], 'lastkey' => false, 'error' => 'Unable to load submissions.'], 500);
        }

        $formdata = $finfo->data->form ?? $finfo->data->formdata ?? null;
        if (!$formdata || !isset($finfo->status) || $finfo->status !== 'success') {
            Log::error('loadmore: form missing from getformhistory', [
                'params' => $serviceParams,
                'status' => $finfo->status ?? null,
                'message' => $finfo->message ?? null,
            ]);
            return response()->json(['rows' => [], 'lastkey' => false, 'error' => 'Unable to load submissions.'], 500);
        }

        $jsonRows = [];
        $submissions = $finfo->data->submissions ?? [];
        $questions = $finfo->data->questions ?? [];

        if ($form_id == '1750914801-153443b9-94d0-4dcb-b3f3-4fa11588a0a9') {
            $submissionIds = [];
            foreach ($submissions as $submission) {
                if (isset($submission->id)) {
                    $submissionIds[] = $submission->id;
                }
            }
            $nebStatuses = [];
            $nebRecordIds = [];
            if (!empty($submissionIds)) {
                $nebRows = \DB::table('neblogistic')
                    ->whereIn('submission_id', $submissionIds)
                    ->get(['submission_id', 'status', 'id']);
                foreach ($nebRows as $row) {
                    $nebStatuses[$row->submission_id] = $row->status;
                    $nebRecordIds[$row->submission_id] = $row->id;
                }
            }
            foreach ($submissions as &$submission) {
                if (isset($nebStatuses[$submission->id])) {
                    $submission->neblogistic_status = $nebStatuses[$submission->id];
                }
                if (isset($nebRecordIds[$submission->id])) {
                    $submission->record_id = $nebRecordIds[$submission->id];
                }
            }
            unset($submission);
        }

        //print_r($finfo->data->submissions);exit;
        $sessionForm = $request->session()->get('formdata');
        $canDeleteByPermission = $request->input('delete_submission') == 1
            || $this->sessionFlag($sessionForm, 'delete_submission');
        $userAttrs = $this->userAttributeCodes($formdata);
        foreach($submissions as $submission) {
            if (!isset($submission->user_info->name)) continue;
            $row = [
                "date" => date("d M Y", strtotime($submission->updatedAt)),
                "name" => $submission->user_info->name,
                "designation" => $submission->user_info->designation ?? "",
                "employee_code" => $submission->user_info->employee_code ?? "",
                "submission_id" => $submission->id,
                "actions" => []
            ];
            foreach ($userAttrs as $attr) {
                $row[$attr] = $this->userAttributeValue($submission->user_info ?? null, $attr);
            }

            // workflow status
            if (isset($formdata->workflow) && $formdata->workflow == 'yes') {
                $row["workflow_status"] = ucfirst($submission->workflow_status ?? "");
                $row["workflow_next_approver"] = $submission->workflow_next_approver ?? "";
            }

            // answers for all questions (put on top level!)
            foreach($questions as $code => $question) {
                if ($question->type == 'hidden') continue;
                if ($question->type == 'multitextbox') {
                    foreach ($question->options as $k => $v) {
                        $row[$k] = isset($submission->formdata->{$k}) 
                            ? (is_array($submission->formdata->{$k}) 
                                ? implode(', ', $submission->formdata->{$k}) 
                                : $submission->formdata->{$k}) 
                            : '';
                    }
                } else if ($question->type == 'file') {
                    $row[$code . '_file'] = isset($submission->formdata->{$code}) 
                        ? (is_array($submission->formdata->{$code}) 
                            ? implode(', ', $submission->formdata->{$code}) 
                            : $submission->formdata->{$code}) 
                        : '';
                } else {
                    $row[$code] = isset($submission->formdata->{$code}) 
                        ? (is_array($submission->formdata->{$code}) 
                            ? implode(', ', $submission->formdata->{$code}) 
                            : $submission->formdata->{$code}) 
                        : '';
                }
            }

            if (isset($formdata->workflow) && $formdata->workflow == 'yes') {
                $row['workflow_action_date'] = $this->formatWorkflowActionDate($submission);
                $row['approval_history'] = $this->formatApprovalHistory($submission);
            }

            // show positions (legacy: show_position) — null-safe; blades only render available columns
            $showPositions = $formdata->show_positions ?? $formdata->show_position ?? 'no';
            if ($showPositions == 'yes') {
                foreach (['territory', 'area', 'region', 'zone'] as $positionField) {
                    $row[$positionField] = $submission->{$positionField} ?? '';
                }
            }

            // show L1/L2 manager details
            if (isset($formdata->show_manager_details) && $formdata->show_manager_details == 'yes') {
                $row['manager1_name'] = $submission->manager1_name ?? '';
                $row['manager1_code'] = $submission->manager1_code ?? '';
                $row['manager2_name'] = $submission->manager2_name ?? '';
                $row['manager2_code'] = $submission->manager2_code ?? '';
            }

            // actions
            if(isset($formdata->approver_can_edit) && $formdata->approver_can_edit == 'yes') {
                $row['actions'][] = 'edit';
            }
            $canDeleteByUser = isset($formdata->allow_delete_by_user) && $formdata->allow_delete_by_user == 'yes';
            if($canDeleteByUser || $canDeleteByPermission) {
                $row['actions'][] = 'delete';
            }
            if (isset($submission->actions) && in_array('edit', $submission->actions)) $row['actions'][] = 'edit';
            if (
                isset($formdata->workflow) && 
                $formdata->workflow == 'yes' && 
                $submission->workflow_status == 'unapproved'
            ) {
                $row['actions'][] = 'approve';
                $row['actions'][] = 'reject';
            }

            if ($form_id == '1750914801-153443b9-94d0-4dcb-b3f3-4fa11588a0a9') {
                if(isset($submission->formdata->status) && $submission->formdata->status == 'Requested') {
                    $row['actions'][] = 'approve';
                    $row['actions'][] = 'reject';
                }
                $row['neblogistic_status'] = $submission->formdata->status;
                $row['record_id'] = $submission->formdata->record_id ?? '-';
            }

            // Target forms: always expose approval status for list UI (downloadpersonalization list)
            $targetFormIds = [
                '1781004538-88671587-3b81-403b-af63-fdbfae8a965e', // rapport-team2
                '1782118020-9c6160bf-f07c-465e-9ea1-e8ff0c0b89dd', // rapport-titans
            ];
            $resolvedFormIds = array_filter([
                (string) $form_id,
                (string) ($originalFormId ?? ''),
                (string) (is_object($formdata) ? ($formdata->id ?? '') : ''),
                (string) (is_object($formdata) ? ($formdata->form_id ?? '') : ''),
            ]);
            $isTargetForm = count(array_intersect($targetFormIds, $resolvedFormIds)) > 0;

            if ($isTargetForm) {
                $workflowStatus = $submission->workflow_status
                    ?? (is_object($submission->formdata) ? ($submission->formdata->workflow_status ?? '') : '');
                $row['workflow_status'] = ucfirst(trim((string) $workflowStatus));
                $row['workflow_next_approver'] = $submission->workflow_next_approver ?? ($row['workflow_next_approver'] ?? '');
            }
            $jsonRows[] = $row;
        }

        // Prefer API pagination cursor (false when no more pages)
        $nextLastkey = false;
        if (isset($finfo->data->lastkey)) {
            $nextLastkey = $finfo->data->lastkey;
        }
        return response()->json(['rows' => $jsonRows, 'lastkey' => $nextLastkey]);

        
        // 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]); } /** * Demographic columns present on at least one submission (Territory/Area/Region/Zone). * When show positions is on but there are no submissions yet, keep all four until data arrives. */ private function getAvailablePositionColumns($submissions, $showPositions): array { $order = ['territory', 'area', 'region', 'zone']; if ($showPositions !== 'yes') { return []; } if (empty($submissions)) { return $order; } $found = []; foreach ($submissions as $submission) { foreach ($order as $field) { if (isset($submission->{$field})) { $found[$field] = true; } } } return array_values(array_filter($order, function ($field) use ($found) { return isset($found[$field]); })); } private function formatWorkflowActionDate($submission) { if (!empty($submission->formdata->workflow_action_date) && !is_array($submission->formdata->workflow_action_date)) { return (string) $submission->formdata->workflow_action_date; } $latest = $this->latestApprovalEntry($submission); $dateVal = !empty($latest['action_date']) ? $latest['action_date'] : ($submission->workflow_action_date ?? null); if (empty($dateVal)) { return ''; } try { return date('d M Y h:i A', strtotime($dateVal)); } catch (\Exception $e) { return (string) $dateVal; } } private function formatApprovalHistory($submission) { if (!empty($submission->formdata->approval_history) && !is_array($submission->formdata->approval_history)) { return (string) $submission->formdata->approval_history; } $latest = $this->latestApprovalEntry($submission); if (empty($latest)) { return ''; } $line = []; if (!empty($latest['action_status'])) { $line[] = $latest['action_status']; } if (!empty($latest['user_name'])) { $line[] = $latest['user_name']; } if (!empty($latest['reason'])) { $line[] = $latest['reason']; } return implode(' - ', $line); } private function latestApprovalEntry($submission) { $history = $submission->approval_history ?? null; if (empty($history) || !is_array($history)) { return []; } $entry = reset($history); return (array) $entry; } 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));
        $canDeleteByPermission = $this->sessionFlag($formdata, 'delete_submission');
        $canDeleteByUser = $this->sessionAttr($formdata, 'allow_delete_by_user') == 'yes';
        if(!$canDeleteByPermission && !$canDeleteByUser) {
            return response()->json(['success' => false, 'message' => 'Unauthorized'], 403);
        }
        $id = $request->input('id', false);
        $form_id = $request->input('form_id', false);
        $partition = $this->sessionAttr($formdata, 'partition');
        if (!$partition) {
            return response()->json(['success' => false, 'message' => 'Unauthorized'], 403);
        }
        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();
        //print_r(['form_id' => $form_id, 'id' => $id ]); exit;
        LambdaRequest::getrequest('form', 'formentity/deletesubmission', ['form_id' => $form_id, 'id' => $id ], $token[0]->access_token);
        return response()->json(['success' => true, 'message' => 'Successfully Deleted !!!']);
    }
    
    public function submit(Request $request) {
        echo '

Something looks wrong. Try again!!!

'; exit; $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) { //return response()->json(['status' => 'error']); $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 == '1655458544-00d0e7c9-c60e-410e-ada7-8e0fef8e6ac4' && isset($post['planning']) && $post['planning'] == 'yes' ) { $plan_date = $post['plan_date'] ?? null; $today = new \DateTime('today'); $currentDay = (int) $today->format('d'); if ($currentDay >= 1 && $currentDay <= 31) { $nextMonthStart = (clone $today)->modify('first day of next month')->format('Y-m-d'); $nextMonthEnd = (clone $today)->modify('last day of next month')->format('Y-m-d'); if (empty($plan_date)) { return response()->json([ 'status' => 'error', 'message' => 'Plan date is required.' ], 200); } $planDateObj = \DateTime::createFromFormat('Y-m-d', $plan_date); if (!$planDateObj || $planDateObj->format('Y-m-d') !== $plan_date) { return response()->json([ 'status' => 'error', 'message' => 'Invalid plan date.' ], 200); } // if ($plan_date < $nextMonthStart || $plan_date > $nextMonthEnd) { // return response()->json([ // 'status' => 'error', // 'message' => "Plan date must be between $nextMonthStart and $nextMonthEnd." // ], 200); // } } else { if (!empty($plan_date)) { return response()->json([ 'status' => 'error', 'message' => 'Plan date can only be selected from 20th to 25th.' ], 200); } } } if($formdata->form_id == '1750312866-ea213e07-7786-4e99-9e1b-3bb8784ee219') { // gennovadc center/hospital enrollment $inputs = $request->input(); list($application, $domain) = explode("-", $formdata->partition); // OLD: Use Formhelper to get all previous form data entries for this user // $previousEntries = \App\Helpers\Formhelper::getMultiformData($formdata->partition, $formdata->form_id, $formdata->user_id); $exists = false; $input_hospital_name = isset($inputs['dialysis_centre_hospital_name']) ? trim($inputs['dialysis_centre_hospital_name']) : ''; // $input_center_type = isset($post['center_type']) ? trim($post['center_type']) : ''; $normalize = function ($s) { $s = is_string($s) ? $s : ''; $s = mb_strtolower(trim($s)); $s = preg_replace('/\s+/', ' ', $s); // Remove punctuation/special chars so "A-B" matches "A B" $s = preg_replace('/[^a-z0-9 ]/i', '', $s); $s = preg_replace('/\s+/', ' ', $s); return trim($s); }; $input_norm = $normalize($input_hospital_name); if ($input_norm === '') { return response()->json([ 'status' => 'error', 'message' => 'Hospital name is required.', 'description' => 'Please enter the dialysis centre / hospital name' ]); } // NEW: compare against all existing contacts for this hierarchy and their hospital_name/name. $hierarchyId = $inputs['hierarchy_id'] ?? ($formdata->hierarchy_id ?? $formdata->hierarchy ?? ''); if (!empty($hierarchyId)) { $contactsResp = LambdaRequest::getrequest('contact', 'contact/get_my_contacts', [ 'hierarchy' => $hierarchyId, 'partition' => $formdata->partition, //'type' => 'center', 'fields' => 'id,name,hospital_name,type' ]); // return response()->json([ // 'status' => 'error', // 'message' => 'Hospital name is required.', // 'description' => 'Please enter the dialysis centre / hospital name', // 'previous_hospital_names' => $contactsResp->data->items // ]); if (isset($contactsResp->data) && isset($contactsResp->data->items) && is_array($contactsResp->data->items)) { foreach ($contactsResp->data->items as $c) { $entry_hospital_name = ''; if (isset($c->hospital_name) && $c->hospital_name !== null) { $entry_hospital_name = trim($c->hospital_name); } elseif (isset($c->name) && $c->name !== null) { $entry_hospital_name = trim($c->name); } $entry_norm = $normalize($entry_hospital_name); $similarPct = 0; if ($entry_norm !== '' && $input_norm !== '') { similar_text($entry_norm, $input_norm, $similarPct); } $isSame = strcasecmp($entry_hospital_name, $input_hospital_name) === 0 || ($entry_norm !== '' && $entry_norm === $input_norm) || ($similarPct >= 90); if ($isSame) { Log::debug(print_r(['Center enrol form: duplicate contact'], true)); Log::debug(print_r(['existing' => $entry_hospital_name, 'input' => $input_hospital_name, 'similarPct' => $similarPct], true)); $exists = true; break; } } } } if(!$exists) { $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' => $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'], 'type' => 'center' ]; $cont = LambdaRequest::postrequest('contact', 'contact/create', $contactdata, $token[0]->access_token); $post['contact_id'] = isset($cont->data->item->id) ? $cont->data->item->id : null; //return response()->json(['status' => 'success']); } else { return response()->json([ 'status' => 'error', 'message' => 'The Hospital you are trying to add already exists in the system.', 'description' => 'Please check the added hospital list or change the name' ]); } //exit; } // if($formdata->form_id == '1755701060-46f95f9d-f30b-41fe-9e0e-6ede3b612ef2') { // vegus center/hospital enrollment // $inputs = $request->input(); // list($application, $domain) = explode("-", $formdata->partition); // // Use Formhelper to get all previous form data entries for this user // $previousEntries = \App\Helpers\Formhelper::getMultiformData($formdata->partition, $formdata->form_id, $formdata->user_id); // $exists = false; // $input_account_name = isset($inputs['enter_account_name']) ? trim($inputs['enter_account_name']) : ''; // $input_place_branch = isset($post['place_branch']) ? trim($post['place_branch']) : ''; // if(isset($previousEntries->data) && isset($previousEntries->data->submissions) && is_array($previousEntries->data->submissions)) { // foreach($previousEntries->data->submissions as $submission) { // $formdata_entry = isset($submission->formdata) ? $submission->formdata : null; // $entry_account_name = isset($formdata_entry->enter_account_name) ? trim($formdata_entry->enter_account_name) : ''; // $entry_place_branch = isset($formdata_entry->place_branch) ? trim($formdata_entry->place_branch) : ''; // if ( // strcasecmp($entry_account_name, $input_account_name) === 0 && // strcasecmp($entry_place_branch, $input_place_branch) === 0 // ) { // $exists = true; // break; // } // } // } // if(!$exists) { // $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' => $post['user_id'], // 'name' => $post['enter_account_name'], // 'msl_code' => 'HOS_' . strtotime("now").rand(0,99), // 'center_place' => $post['enter_account_name'], // 'center_name' => $post['place_branch'], // 'type' => 'center' // ]; // $cont = LambdaRequest::postrequest('contact', 'contact/create', $contactdata, $token[0]->access_token); // $post['contact_id'] = isset($cont->data->item->id) ? $cont->data->item->id : null; // //return response()->json(['status' => 'success']); // } else { // return response()->json([ // 'status' => 'error', // 'message' => 'The Hospital you are trying to add already exists in the system.', // 'description' => 'Please check the added hospital list or change the name' // ]); // } // //exit; // } if($formdata->form_id == '1755701060-46f95f9d-f30b-41fe-9e0e-6ede3b612ef2') { // 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['enter_account_name'], 'search' => '{"type":"center"}', 'start' => 0, 'length' => 10000], $token[0]->access_token); Log::debug(print_r($conts, true)); // return response()->json(['status' => $conts]); $exists = false; if (isset($conts->data->count) && $conts->data->count > 0 && isset($conts->data->items) && is_array($conts->data->items)) { foreach ($conts->data->items as $item) { // return response()->json(['status' => 'inside']); if ( isset($item->center_name, $item->center_place, $inputs['enter_account_name'], $inputs['place_branch']) && strcasecmp(trim($item->center_name), trim($inputs['enter_account_name'])) === 0 && strcasecmp(trim($item->center_place), trim($inputs['place_branch'])) === 0 ) { $exists = true; } } } // return response()->json(['status' => $exists]); Log::debug(print_r($exists, true)); if(!$exists) { $contactdata = [ 'domain' => $domain, 'application' => $application, 'user_id' => $post['user_id'], 'name' => $post['enter_account_name'], 'msl_code' => 'HOS_' . strtotime("now").rand(0,99), 'center_name' => $post['enter_account_name'], 'center_place' => $post['place_branch'], 'type' => 'center' ]; $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 == '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 == '1775640000-71402a87-56be-48ae-93c9-a77a2cf25693') { 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['name_of_chemist'], 'type' => 'chemist', 'msl_code' => strtotime("now").'-'.rand(1000,9999), 'user_id' => $post['user_id'], ]; $cont = LambdaRequest::postrequest('contact', 'contact/create', $contactdata, $token[0]->access_token); Log::debug(print_r(['createcontactcampaigntagging'], true)); Log::debug(print_r($post, true)); // return response()->json(['status' => 'success', 'data'=> $cont]); } if($formdata->form_id == '1713351143-9afc68f4-653f-491a-9e0e-a27d61ed1e07' && isset($post['contact_id']) && !empty($post['contact_id'])) { 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'], 'area' => $post['area'], 'speciality' => $post['speciality'], 'venue_clinic_address' => $post['venue_clinic_address'], 'id' => $post['contact_id'], ]; $cont = LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token[0]->access_token); } // Zenova - Glipiq & Sitazit Tracker Copy if($formdata->form_id == '1788239728-6f7f3c27-c5dc-4e6e-a042-aefd5681af3a' && isset($post['contact_id']) && !empty($post['contact_id'])) { 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'], 'id' => $post['contact_id'], ]; $contactAttributes = [ 'sankalp_lead_received_penvial', 'sankalp_lead_enrolled_penvial', 'pmos_dr', 'qbs_dr', 'adboard_dr', 'fb_live_dr', 'ecme_dr', 'rtm_dr', ]; foreach ($contactAttributes as $attr) { if (isset($post[$attr]) && $post[$attr] !== '') { $contactdata[$attr] = $post[$attr]; } } if (count($contactdata) > 4) { LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token[0]->access_token); } } // if($formdata->form_id == '1758800833-00e44f7c-1857-4109-8ad4-2789d49a78fa') { // 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(); // for ($i = 1; $i <= 5; $i++) { // if (!empty($post["contact_id_$i"])) { // $contactdata = [ // 'domain' => $domain, // 'application' => $application, // 'user_id' => $post['user_id'], // 'ndc_enrollment' => 'Yes', // 'id' => $post["contact_id_$i"], // ]; // $cont = LambdaRequest::postrequest( // 'contact', // 'contact/update', // $contactdata, // $token[0]->access_token // ); // Log::info("NDCFORM"); // Log::info("Updated contact_id_$i", $contactdata); // } // } // Log::info("NDCFORMFORMDATA"); // Log::info(print_r($post, true)); // $contactdata = [ // 'domain' => $domain, // 'application' => $application, // 'user_id' => $post['user_id'], // 'ndc_enrollment' => 'Yes', // 'id' => $post['contact_id'], // ]; // $cont = LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token[0]->access_token); // } if($formdata->form_id == '1767873454-9be29731-6989-43b8-9066-a8e70edac695') { $post['upload_photo'] = $post['image_with_location']; } if ($formdata->form_id == '1768200130-7e002780-2e64-4472-ba6a-2f93ef37804b') { list($application, $domain) = explode("-", $formdata->partition); Log::info('Power of 5 form triggered', [ 'form_id' => $formdata->form_id, 'user_id' => $post['user_id'] ?? null, 'domain' => $domain ]); $token = DB::table('users') ->select("access_token", "user_id") ->where("domain", $domain) ->where("permissions", 'like', '%contact_update%') ->orderBy('updated_at', 'desc') ->first(); if (!$token) { Log::warning('Power of 5 contact update skipped - token not found', [ 'domain' => $domain ]); return; } $brandMap = [ 'voltido_trio' => 'power_of_5_voltido_trio', 'voltido' => 'power_of_5_voltido', 'duolin' => 'power_of_5_duolin', ]; foreach ($brandMap as $brand => $powerField) { for ($i = 1; $i <= 5; $i++) { $doctorKey = "doctor_{$i}_{$brand}"; $potentialKey = "dr_potential_{$i}_{$brand}"; if (!empty($post[$doctorKey])) { $contactData = [ 'domain' => $domain, 'application' => $application, 'user_id' => $post['user_id'], 'id' => $post[$doctorKey], // CONTACT ID $powerField => 'Yes', ]; // Add numeric doctor potential if present if (isset($post[$potentialKey]) && is_numeric($post[$potentialKey])) { $contactData['power_of_5_dr_potential'] = (int) $post[$potentialKey]; } Log::info('Updating Power of 5 contact', [ 'contact_id' => $post[$doctorKey], 'brand' => $brand, 'attributes' => $contactData ]); LambdaRequest::postrequest( 'contact', 'contact/update', $contactData, $token->access_token ); } } } Log::info('Power of 5 contact update completed', [ 'form_id' => $formdata->form_id ]); } if($formdata->form_id == '1757055046-ba0eff4e-0d4a-4e90-b190-c59f12ef6edd') { // 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'], 'emvasrin_conversion_doctor' => 'Yes', 'id' => $post['contact_id'], ]; $cont = LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token[0]->access_token); // } } if($formdata->form_id == '1770113055-b65a4310-83e0-49ad-ad98-6a226beb2bc3') { 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'], 'glycohale_power_punch' => 'Yes', 'dr_potential_for_glycohale' => $post['dr_potential_for_glycohale_in_units'], 'id' => $post['doctor_name'], ]; $cont = LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token[0]->access_token); if($post['doctor_name'] != $post['og_contact_id']) { $removeoldcontactdata = [ 'domain' => $domain, 'application' => $application, 'user_id' => $post['user_id'], 'glycohale_power_punch' => '', 'dr_potential_for_glycohale' => '', 'id' => $post['og_contact_id'], ]; LambdaRequest::postrequest('contact', 'contact/update', $removeoldcontactdata, $token[0]->access_token); } } // if($formdata->form_id == '1758180234-37c6fb8c-7d13-4647-8aaa-1d67fc51ea57') { // $contacts = []; // foreach ($post as $key => $value) { // if (strpos($key, 'contact_id_') === 0) { // $contacts[] = [ // 'contact_id' => $value, // 'tenectase_super_50' => 'Yes' // ]; // } // } // 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(); // $msg = ["test cont"]; // Log::debug(print_r($msg, true)); // Log::debug(print_r($contacts, true)); // foreach($contacts as $contact) { // $contactdata = [ // 'domain' => $domain, // 'application' => $application, // 'user_id' => $post['user_id'], // 'tenectase_super_50' => $contact['tenectase_super_50'], // 'id' => $contact['contact_id'], // ]; // $cont = LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token[0]->access_token); // } // // return response()->json(['status' => 'success']); // } 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 == '1775980892-f0346e7e-e9e5-4f85-9924-beb91fcb8fda') { // $contacts = []; // // collect contacts from doctor_name_1 to doctor_name_20 // for ($i = 1; $i <= 20; $i++) { // if (!empty($post['doctor_name_' . $i])) { // $contacts[] = [ // 'contact_id' => $post['doctor_name_' . $i], // 'po5_novel_meeting' => 'Yes' // ]; // } // } // 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') // ->first(); // foreach ($contacts as $contact) { // $contactdata = [ // 'domain' => $domain, // 'application' => $application, // 'user_id' => $post['user_id'], // 'po5_novel_meeting' => $contact['po5_novel_meeting'], // 'id' => $contact['contact_id'], // ]; // $cont = LambdaRequest::postrequest( // 'contact', // 'contact/update', // $contactdata, // $token->access_token // ); // } // } if ($formdata->form_id == '1775984811-b4153c49-48d9-4295-b075-b83b2e913bae') { // Collect doctor_name_ values into array $current_doctors = []; for ($i = 1; $i <= 45; $i++) { $key = 'doctor_name_' . $i; if (!empty($post[$key])) { $current_doctors[] = $post[$key]; } } // Get the list of existing_doctors from the $post data, default to empty array if not set $existing_doctors = isset($post['existing_doctors']) && is_array($post['existing_doctors']) ? $post['existing_doctors'] : []; // Split partition to get application/domain 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') ->first(); // For doctors present in inputs but not in existing_doctors, update po5_ace_meeting => 'Yes' foreach ($current_doctors as $doctor_id) { if (!in_array($doctor_id, $existing_doctors)) { $contactdata = [ 'domain' => $domain, 'application' => $application, 'user_id' => $post['user_id'], 'po5_ace_meeting' => 'Yes', 'id' => $doctor_id, ]; $cont = LambdaRequest::postrequest( 'contact', 'contact/update', $contactdata, $token->access_token ); } } // For doctors present in existing_doctors but not in inputs, update po5_ace_meeting => 'No' foreach ($existing_doctors as $doctor_id) { if (!in_array($doctor_id, $current_doctors)) { $contactdata = [ 'domain' => $domain, 'application' => $application, 'user_id' => $post['user_id'], 'po5_ace_meeting' => 'No', 'id' => $doctor_id, ]; $cont = LambdaRequest::postrequest( 'contact', 'contact/update', $contactdata, $token->access_token ); } } return response()->json(['status' => 'success']); } 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']); // } // } // } // Get all variables starting with actual_, compare actual_ and non-actual keys in formdata, // update if actual_ value is greater, then replace the values in non actual with actuals. // Also, change the total value with the given multipliers. // Define the mapping of actual_ field (brand) to its fixed value (multipliers) $actualBrandMultipliers = [ 'budecort-respules-0' => 19.37, 'budecort-respules-1m' => 21.39, 'budesal-05-respules' => 37.96, 'budesal-1-respules-2' => 48.69, 'duolin-3-respule' => 19.59, 'duolin-ld-respules' => 14.54, 'levolin-31-resp' => 4.66, 'levolin-063-mg-respules' => 5.62, 'levolin-125mg-resp' => 6.52, 'glycohale_2_ml_respules' => 40, 'asthalin_inhaler' => 129, 'foracort_1_respules' => 77.82, 'foracort_05_respules' => 62.95, 'asthalin_respules' => 6, 'hyperneb_3_respules' => 18.81, 'hyperneb_7_respules' => 23.76 ]; if (isset($post) && is_array($post)) { $actualTotalValue = 0; foreach ($post as $key => $value) { if (strpos($key, 'actual_') === 0) { $nonActualKey = substr($key, 7); // Remove 'actual_' prefix if (isset($post[$nonActualKey])) { $actualValue = $value; $nonActualValue = $post[$nonActualKey]; // Try to compare as numbers if both are numeric, else as strings if (is_numeric($actualValue) && is_numeric($nonActualValue)) { if ($actualValue > $nonActualValue) { $post[$nonActualKey] = $actualValue; } } else { if ($actualValue > $nonActualValue) { $post[$nonActualKey] = $actualValue; } } } // Calculate total value using multipliers // The key for multipliers is the nonActualKey (without 'actual_') // Try both dash and underscore variants for compatibility $brandKey = str_replace('_', '-', $nonActualKey); if (isset($actualBrandMultipliers[$brandKey]) && is_numeric($value)) { $actualTotalValue += floatval($value) * $actualBrandMultipliers[$brandKey]; } elseif (isset($actualBrandMultipliers[$nonActualKey]) && is_numeric($value)) { $actualTotalValue += floatval($value) * $actualBrandMultipliers[$nonActualKey]; } } } // Set the total value in the post array $post['actual_total_value'] = $actualTotalValue; } 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'))] ); } Log::debug(print_r(['daily call reporting'], true)); Log::debug(print_r($post, true)); } 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') {

            $id = DB::table('team3_nebmitra_doctors')
            ->insertGetId([
                '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']
            ]);

            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['doctor_name'],
                'type' => 'nebmitra_doctor',
                'user_id' => $post['user_id'],
                'msl_code' => 'NEBMITRA_DOCTOR_'.$id,
                'phone' => $post['mobile_number'],
                'speciality'=> $post['speciality']
            ];
            $cont = LambdaRequest::postrequest('contact', 'contact/create', $contactdata, $token[0]->access_token);
            $contactid = $cont->data->item->id;
            $positioncode = $cont->data->item->position;


            DB::table('team3_nebmitra_doctors')
            ->where('id', $id)
            ->update([
                'contact_id' => $contactid,
                'position_code' => $positioncode
                ]);

            Log::debug(print_r(['Add Doctor'], true));
            Log::debug(print_r($contactid, true));
            Log::debug(print_r($post, true));
            Log::debug(print_r($contactdata, true));
            Log::debug(print_r($cont, true));
            Log::debug(print_r(['Add Doctor End'], true));
            


           
            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;

            // Check if user is blocked from submitting a new NAP request

            // Find Employee Code (emp_id). Try from $post['emp_id'] else fallback to users table
            $employeeCode = isset($post['emp_id']) ? $post['emp_id'] : null;

            if (!$employeeCode) {
                // fallback to database if not provided in post
                $user = DB::table('users')->where('id', $userid)->select('emp_employee_code')->first();
                if ($user && isset($user->emp_employee_code)) {
                    $employeeCode = $user->emp_employee_code;
                }
            }

            if ($employeeCode) {
                try {
                    $client = new \GuzzleHttp\Client(['timeout' => 5]);
                    $response = $client->request(
                        'GET',
                        'https://nap.easyspacebooking.com/APi/GetStatusToBlockOrNotByEmployeeCode/' . urlencode($employeeCode)
                    );

                    if ($response->getStatusCode() == 200) {
                        $body = $response->getBody()->getContents();
                        $decoded = json_decode($body, true);
                        if (
                            is_array($decoded) &&
                            isset($decoded[0]['blocked']) &&
                            (strtolower($decoded[0]['blocked']) === 'yes' || strtolower($decoded[0]['blocked']) === 'Yes')
                        ) {
                            return response()->json([
                                'status' => 'failure',
                                'message' => 'You are not allowed to raise a new NAP request at this time.',
                                'allemployeerequest' => $decoded[0]['employeeRequests'] ?? [],
                                'redirect_url' => 'https://nap.easyspacebooking.com/login'
                            ]);
                        }
                    }
                } catch (\Exception $e) {
                    // Handle connection error/timeout gracefully -- allow request to go through but log it
                    \Log::error('Failed to check NAP employee block status: '.$e->getMessage());
                }
            }

            $checkOnly = ($post['GetStatusToBlockOrNotByEmployeeCode'] ?? '') === 'yes';
            if ($checkOnly) {
                return response()->json([
                    'status' => 'success',
                    'message' => 'Allowed to raise a new NAP'
                ]);
            }

            $phones = [ '8421945842',
                        '9000892659',
                        '8008779049',
                        '7032574882',
                        '7030704045',
                        '7768035567',
                        '7870676113',
                        '9075980409',
                        '7340757423',
                        '9618462184',
                        '8779775797',
                        '6376339978',
                        '8696055451',
                        '9314703936',
                        '8888938111',
                        '9911998649',
                        '9410012233',
                        '8538008054',
                        '8263028860',
                        '9672969490',
                        '8652235956',
                        '8472950515',
                        '9911948062',
                        '9501190932',
                        '9629950027',
                        '8327766946',
                        '8657627212',
                        '9845902285',
                        '6290511698',
                        '9041378580',
                        '8308305091',
                        '7890285582',
                        '9769591901',
                        '6200175050',
                        '8970552629',
                        '9826045047',
                        '7897876200',
                        '9935134301',
                        '7859940470',
                        '9760643464',
                        '9412203271',
                        '8378849883',
                        '7738304013',
                        '8052797812',
                        '9760272717',
                        '9993030333',
                        '6307416235',
                        '8294408339',
                        '9666020326',
                        '9053671619',
                        '7290824495',
                        '9966766429',
                        '7302029208',
                        '9013122209',
                        '7298146436',
                        '7277188700',
                        '7252992389',
                        '8847572201',
                        '9966608912',
                        '9634001221',
                        '8674986750',
                        '8607881639',
                        '9004727456',
                        '8381032649',
                        '8960616876',
                        '8197107405',
                        '8309880262',
                        '9794665474',
                        '8421740313',
                        '8008860018',
                        '8806790970',
                        '6364684207',
                        '9677108693',
                        '7002144047',
                        '8016909549',
                        '7631371518',
                        '9348246006',
                        '7407241239',
                        '6392524873',
                        '9582947428',
                        '8617493069',
                        '8888788495',
                        '7004674891',
                        '9746549327',
                        '9828862783',
                        '9048594337',
                        '7014596144',
                        '9737753331',
                        '9555198050',
                        '7076128076',
                        '9992397044',
                        '7028327217',
                        '8080290405',
                        '8750750105',
                        '8904853033',
                        '7250490304',
                        '9977662759',
                        '7622082442',
                        '8076931066',
                        '9671493943',
                        '7904321338',
                        '7501263431',
                        '8248970627',
                        '7307822995',
                        '9538903351',
                        '9053520567',
                        '8374383446',
                        '7905790492',
                        '9536772915',
                        '9729510980',
                        '7220964201',
                        '9634718751',
                        '9896834406',
                        '9313840546',
                        '9598253590',
                        '7797726019',
                        '8005518332',
                        '9058957223',
                        '7979042997',
                        '7973489844',
                        '8756917442',
                        '8630780338',
                        '6290711165',
                        '8587860178',
                        '9651307306',
                        '8965065006',
                        '7229906004',
                        '9037647675',
                        '9585383624',
                        '7991157767',
                        '8699208918',
                        '7309224964',
                        '7979752450',
                        '9566190755',
                        '9587363627',
                        '7090128805',
                        '9716631844',
                        '8506991361',
                        '9473259442',
                        '7906855218',
                        '8318084449',
                        '7704819693',
                        '9019707803',
                        '9101358383',
                        '8925627274',
                        '7077754242',
                        '8171299347',
                        '9405177300',
                        '9655966259',
                        '8960443680',
                        '7028233936',
                        '9806888287',
                        '9699403523',
                        '8145540478',
                        '9836347718',
                        '8813888420',
                        '9595095808',
                        '8371979105',
                        '9004000435',
                        '9178524087',
                        '8240267199',
                        '8423583627',
                        '8421755705',
                        '7004479560',
                        '7415829565',
                        '8888944063',
                        '8896906317',
                        '9746803521',
                        '9522335613',
                        '9583969143',
                        '7063221313',
                        '9944463033',
                        '8655627158',
                        '9842147374',
                        '9382461957',
                        '8486053727',
                        '9639946146',
                        '9953816844',
                        '8157077248',
                        '8095474388',
                        '9662697286',
                        '7840912866',
                        '9514451845',
                        '9660345955',
                        '9496985241',
                        '9080120340',
                        '8239732331',
                        '7021337703',
                        '9113836269',
                        '7384707306',
                        '8299253789',
                        '9087903939',
                        '8652273223',
                        '9775718145',
                        '9594559800',
                        '7767896172',
                        '7003369286',
                        '8005654625',
                        '9413955437',
                        '7000725948',
                        '8279874706',
                        '7982581777',
                        '8076111592',
                        '8847248458',
                        '9033449985',
                        '7017137299',
                        '9789986909',
                        '7380952976',
                        '8891484678',
                        '9535735175',
                        '9832430781',
                        '9875470983',
                        '8329759793',
                        '9920453826',
                        '9624567368',
                        '8126665817',
                        '7000491483',
                        '9021519181',
                        '9795321488',
                        '9088022337',
                        '9658739242',
                        '7092795596',
                        '7488193052',
                        '9846632814',
                        '9080416659',
                        '7795138744',
                        '8779719568',
                        '7776827867',
                        '9767404085',
                        '9541114937',
                        '8017126419',
                        '7503373003',
                        '8000869063',
                        '7318842710',
                        '9998124492',
                        '8132801931',
                        '09820203584',
                        '9987572072',
                        '8356075939',
                        '9550003895',
                        '9962004269',
                        '9810641170',
                        '8010825581',
                        '8141236956',
                        '7200354700',
                        '8056041788',
                        '9355530688',
                        '8482054822',
                        '9885354942',
                        '7503990327',
                        '9941335128',
                        '9466380012',
                        '8143009103',
                        '7837001323',
                        '8434054530',
                        '8085858738',
                        '8008664455',
                        '9973652511',
                        '9418682658',
                        '7018343435',
                        '9920860404',
                        '9944547105',
                        '9809292176',
                        '9825400186',
                        '8128319876',
                        '9946387732',
                        '9700406175',
                        '9468167200',
                        '9166657637',
                        '9982642468',
                        '9034369071',
                        '7742087441',
                        '7742498652',
                        '9314029090',
                        '8858550557',
                        '9576541254',
                        '8085979182',
                        '9419249722',
                        '9041474450',
                        '7508082288',
                        '9622230924',
                        '9032333315',
                        '8328682011',
                        '8770602224',
                        '9872256786',
                        '9097467935',
                        '9774340277',
                        '9550767670',
                        '9861101279',
                        '9791275020',
                        '9774079640',
                        '9082447690',
                        '8286575884',
                        '9679886985',
                        '8477079231',
                        '8777367007',
                        '8086297134',
                        '7003365322',
                        '8818852337',
                        '8186055757',
                        '8191039708',
                        '9839845136',
                        '9718171641',
                        '9890349943',
                        '7719862608',
                        '9515059501',
                        '9655366620',
                        '6205412970',
                        '8287231348',
                        '8708192375',
                        '9908592404',
                        '7618939534',
                        '7876847631',
                        '8340168340',
                        '7010530488',
                        '8847610592',
                        '9262967213',
                        '9873667487',
                        '8670974585',
                        '9048271597',
                        '8077465559',
                        '8553139355',
                        '9462028174',
                        '9699841178',
                        '9949841295',
                        '9872901229',
                        '9656219600',
                        '8401080867',
                        '8420013036',
                        '9579419422',
                        '9600928645',
                        '9472415666',
                        '8088885317',
                        '9395954735',
                        '9063720822',
                        '9691475140',
                        '9573856146',
                        '8380081552',
                        '9015573860',
                        '9972769001',
                        '9693315050',
                        '9952062780',
                        '9891769472',
                        '9785982687',
                        '9339450549',
                        '9648458555',
                        '9640105000',
                        '8089787903',
                        '9939806494',
                        '9635661566',
                        '9730160448',
                        '9876422416',
                        '9874578654',
                        '7797701092',
                        '9719468661',
                        '8093342373',
                        '7377662443',
                        '9926126127',
                        '9872560733',
                        '9852986547',
                        '8219984042',
                        '9175040431',
                        '7795503438',
                        '9480998844',
                        '7483007322',
                        '9901603928',
                        '9926803798',
                        '8050927190',
                        '7828406974',
                        '8050039355',
                        '9685599786',
                        '9719640365',
                        '9654812803',
                        '9161500268',
                        '9919568629',
                        '9026276455',
                        '9415930958',
                        '7037231333',
                        '9450436055',
                        '8958166596',
                        '9760129367',
                        '9927958548',
                        '8971019143',
                        '9559846039',
                        '9457818136',
                        '9882483470',
                        '9935770990',
                        '6387029263',
                        '9874318019',
                        '8981800987',
                        '8240380412',
                        '7890573180',
                        '8016133222',
                        '8334823000',
                        '8617262894',
                        '7003367637',
                        '9886488776',
                        '8820999179',
                        '9836722750',
                        '9832277243',
                        '7439481795',
                        '9735164362',
                        '9800839771',
                        '8670669017',
                        '8293107261',
                        '9746324554',
                        '9941777544',
                        '9540100261',
                        '9995469377',
                        '9597693787',
                        '8695022229',
                        '9499049784',
                        '8093809386',
                        '7003759296',
                        '7303490852',
                        '7594091275',
                        '9867868397',
                        '9975243832',
                        '9359944353',
                        '9026949796',
                        '9793036317',
                        '7875627905',
                        '9514464462',
                        '8553211267',
                        '8805227340',
                        '9821342238',
                        '8192951909',
                        '9969367572',
                        '9257129317',
                        '7620916520',
                        '9867757714',
                        '9011952139',
                        '7696414546',
                        '9111850712',
                        '8889023428',
                        '8880250892',
                        '9982663634',
                        '8250031245',
                        '8507016122',
                        '9265670383',
                        '9108112857',
                        '7016416965',
                        '6392011531',
                        '9610430003',
                        '7908162017',
                        '9398560524',
                        '8116202772',
                        '7002193351',
                        '7306805383',
                        '8208832433',
                        '7014923077',
                        '9961402290',
                        '9805911715',
                        '7984360141',
                        '7016543331',
                        '8349905877',
                        '9721448227',
                        '9948750393',
                        '9626580728',
                        '7455812183',
                        '8885171431',
                        '9264213090',
                        '9884117179',
                        '6206197771',
                        '8887792156',
                        '7905907826',
                        '8126399711',
                        '9953309348',
                        '9621038474',
                        '9919955975',
                        '7975931440',
                        '9492098621',
                        '9994081506',
                        '8073273799',
                        '9036852625',
                        '7874339667',
                        '7034024478',
                        '7001556678',
                        '7705025488',
                        '8969014609',
                        '7440329896',
                        '8780794198',
                        '8420665650',
                        '8486990332',
                        '7061408391',
                        '7076115650',
                        '7505741072',
                        '9735863983',
                        '8248337205',
                        '9966629117',
                        '9747213722',
                        '8810297905',
                        '7405934624',
                        '8141238763',
                        '7744816904',
                        '6000136164',
                        '7908774247',
                        '8015136776',
                        '9566966952',
                        '9874809209',
                        '9885855533',
                        '9633497568',
                        '7697936563',
                        '7838899239',
                        '8838408187',
                        '8356868018',
                        '9723449000',
                        '9536499995',
                        '9398806564',
                        '8958003440',
                        '9952539978',
                        '9870691792',
                        '8750231554',
                        '8939071097',
                        '7667925407',
                        '7003086498',
                        '8826080497',
                        '7665392360',
                        '8754778275',
                        '7032013503',
                        '9552293291',
                        '7566350865',
                        '8848120731',
                        '6305292452',
                        '9502001878',
                        '7619236114',
                        '9988844507',
                        '8958194140',
                        '9284065436',
                        '7240683183',
                        '9450746126',
                        '8983870700',
                        '9064894769',
                        '8794415179',
                        '7002971012',
                        '7977497087',
                        '9821355537',
                        '9909002343',
                        '9035044939',
                        '9948431590',
                        '8688126146',
                        '8904212889',
                        '9674722001',
                        '7523966114',
                        '8667643434',
                        '8754569868',
                        '9860479851',
                        '7800927756',
                        '9730149927',
                        '9095818919',
                        '9890977536',
                        '9963378042',
                        '8921360239',
                        '8458939361',
                        '7097955620',
                        '9001513193',
                        '6305568729',
                        '8887802664',
                        '7021327858',
                        '9599673312',
                        '8714384316',
                        '6239746149',
                        '7675981689',
                        '8467953899',
                        '7010516982',
                        '9582335571',
                        '9585350253',
                        '9877683527',
                        '8354848633',
                        '9917112434',
                        '8939364289',
                        '9633690301',
                        '9832624557',
                        '8208493432',
                        '8906752192',
                        '8299430126',
                        '9947677581',
                        '9496359351',
                        '9678333735',
                        '9948387127',
                        '8340781363',
                        '9632464212',
                        '9922088202',
                        '8630506388',
                        '7977649195',
                        '9885990901',
                        '9164946431',
                        '8459300374',
                        '9618922242',
                        '8888453552',
                        '8077718701',
                        '7980332616',
                        '7018199698',
                        '8077038387',
                        '8375903858',
                        '8973109001',
                        '9959007143',
                        '9642496117',
                        '7800002526',
                        '8487008787',
                        '7636900180',
                        '8870594951',
                        '8793730177',
                        '8886212140',
                        '7388994598',
                        '9599493252',
                        '9037334503',
                        '9700700421',
                        '6303491114',
                        '7849957305',
                        '9833943913',
                        '9723288097',
                        '8383099506',
                        '9658235967',
                        '9041178993',
                        '8879283716',
                        '9171252502',
                        '6304940285',
                        '7306776675',
                        '8867421597',
                        '9990081934',
                        '8240535486',
                        '8445044123',
                        '7907232781',
                        '7776877778',
                        '7028489655',
                        '9064515180',
                        '8668658991',
                        '9944851287',
                        '7905453356',
                        '8657283214',
                        '8760996262',
                        '9824358582',
                        '8269782660',
                        '9768438442',
                        '7676045709',
                        '6393242250',
                        '9021987882',
                        '7906183255',
                        '8423812124',
                        '9410000483',
                        '7034500045',
                        '9557774589',
                        '7868086318',
                        '8217764225',
                        '7003270432',
                        '8867595962',
                        '9523634393',
                        '7403841470',
                        '9877562987',
                        '8682060674',
                        '7892965240',
                        '9001803347',
                        '9669420322',
                        '8956720336',
                        '9505832483',
                        '6398534110',
                        '9902480821',
                        '7080474852',
                        '7988345700',
                        '9330565653',
                        '9404435883',
                        '7075575727',
                        '9747929455',
                        '7997203036',
                        '9888366635',
                        '9647672408',
                        '9973681562',
                        '8961976825',
                        '7679458335',
                        '6291666829',
                        '9705348229',
                        '9131329719',
                        '8095432641',
                        '9169719573',
                        '9748355862',
                        '7440842607',
                        '8272937828',
                        '9996336288',
                        '7568049696',
                        '9025849189',
                        '7402534841',
                        '8617880984',
                        '9038951952',
                        '8250126328',
                        '7904013371',
                        '9538543796',
                        '8668118465',
                        '6900739816',
                        '8970767977',
                        '9809731645',
                        '9832103576',
                        '9575359595',
                        '8278675602',
                        '9337830679',
                        '7407323519',
                        '7418887589',
                        '9003857783',
                        '7676660066',
                        '7338512943',
                        '9765757541',
                        '9001492309',
                        '9043185326',
                        '9567268965',
                        '6361194582',
                        '8700865923',
                        '9566288568',
                        '9360646104',
                        '9791133954',
                        '9629719173',
                        '9027226167',
                        '9808785323',
                        '9962961285',
                        '9907871323',
                        '9970765020',
                        '9650334728',
                        '9315476514',
                        '9836800970',
                        '9614956019',
                        '9839759494',
                        '9212259813',
                        '8149178974',
                        '9703500500',
                        '9414981024',
                        '8860882278',
                        '9988053040',
                        '9874548111',
                        '9452962043',
                        '8950574767',
                        '8208555096',
                        '8805336112',
                        '7588737149',
                        '7030434020',
                        '8181819623',
                        '9549777724',
                        '9699341614',
                        '9140460418',
                        '9167661174',
                        '9922790006',
                        '9022973386',
                        '9890411087',
                        '9167558464',
                        '9890960642',
                        '9028145939',
                        '8169317066',
                        '7506422204',
                        '9096356761',
                        '9764135172',
                        '8007900346',
                        '9545853555',
                        '9922227345',
                        '9403631120',
                        '8669131724',
                        '7735443803',
                        '8562820821',
                        '9770979718',
                        '7014962289',
                        '7610955614',
                        '9614048131',
                        '9640515091',
                        '9892222097',
                        '8108208177',
                        '8431515458',
                        '8758731437',
                        '9666676815',
                        '8910751763',
                        '7799662128',
                        '8592091984',
                        '7756828674',
                        '8129567643',
                        '9010489802',
                        '9060483484',
                        '7208389859',
                        '9567345680',
                        '9897919115',
                        '7207431737',
                        '8530163305',
                        '6352174122',
                        '8128397725',
                        '9992471515',
                        '7020906089',
                        '9302338707',
                        '9753960165',
                        '7007788718',
                        '9399349862',
                        '7704992299',
                        '9039079009',
                        '9340815828',
                        '9518181926',
                        '9936004438',
                        '9414473725',
                        '9026125181',
                        '9616118555',
                        '8979765444',
                        '7306189611',
                        '7972975733',
                        '8535048686',
                        '8528372521',
                        '9695930887',
                        '9149049954',
                        '7908006933',
                        '9482745888',
                        '9113822913',
                        '9045247005',
                        '9494499118',
                        '8870773427',
                        '9559411120',
                        '9506247941',
                        '9640928818',
                        '9541795614',
                        '8886395997',
                        '7396921382',
                        '9981935840',
                        '9396693955',
                        '9769644394',
                        '9075791986',
                        '9413317455',
                        '8840269788',
                        '9558505287',
                        '9398887816',
                        '8983288567',
                        '9621464020',
                        '8001413247',
                        '8802745497',
                        '7812930885',
                        '7012796647',
                        '7990115254',
                        '7607707869',
                        '8178102659',
                        '7248819219',
                        '9585643537',
                        '7001449161',
                        '9832524021',
                        '9010921582',
                        '6394920110',
                        '7276095151',
                        '7062432668',
                        '7980107636',
                        '7479846938',
                        '9746172252',
                        '7060373234',
                        '8476021231',
                        '9452263764',
                        '9080803744',
                        '9642424261',
                        '9526611096',
                        '8627059425',
                        '7979817807',
                        '9050487963',
                        '7018254315',
                        '8010876614',
                        '7877144449',
                        '8688168377',
                        '8788954452',
                        '8955382352',
                        '7063465747',
                        '9304727982',
                        '9915969563',
                        '9034251321',
                        '9056126155',
                        '9886074446',
                        '9692028866',
                        '9505397386',
                        '9634767337',
                        '8210375661',
                        '8429109473',
                        '7355706341',
                        '7979079968',
                        '8874763727',
                        '8210627962',
                        '7838534042',
                        '9542225186',
                        '7003894656',
                        '8755205383',
                        '7976325031',
                        '9310288433',
                        '8955243224',
                        '7004330447',
                        '7002509366',
                        '9925935935',
                        '8714040802',
                        '7793930633',
                        '8597712070',
                        '6280640797',
                        '9624836623',
                        '9619701043',
                        '8299215575',
                        '7985040853',
                        '9092173090',
                        '9648695630',
                        '8074454659',
                        '9875393746',
                        '9544584244',
                        '7267868551',
                        '7977860373',
                        '9592432529',
                        '7027235063',
                        '8807420485',
                        '6001071916',
                        '6207600652',
                        '9043689287',
                        '8851984232',
                        '6381085378',
                        '9846479424',
                        '9880702083',
                        '9654732405',
                        '9895875868',
                        '9401976660',
                        '9461935414',
                        '7275364975',
                        '9614832170',
                        '9366112550',
                        '8940341476',
                        '8711081472',
                        '6397459328',
                        '6397784699',
                        '6300026966',
                        '9167338615',
                        '7976166841',
                        '9000573151',
                        '8420946659',
                        '7737679906',
                        '6381083830',
                        '8979280034',
                        '7000339296',
                        '7904718617',
                        '7295850800',
                        '7008775158',
                        '9922981499',
                        '9048263351',
                        '8171913291',
                        '9950183470',
                        '9687170872',
                        '8754401697',
                        '8600182807',
                        '9989440777',
                        '8005901702',
                        '9862676055',
                        '7980017832',
                        '8200217355',
                        '9908324195',
                        '8879414089',
                        '9677161561',
                        '9025030704',
                        '8006808666',
                        '9587107699',
                        '9503663703',
                        '8428986985',
                        '9767530894',
                        '9029842043',
                        '9579007288',
                        '9021165357',
                        '9819180971',
                        '8149498096',
                        '8433874997',
                        '8605694169',
                        '9096363506',
                        '7622926961',
                        '9747157152',
                        '9787978393',
                        '7027020028',
                        '9550658545',
                        '8094701130',
                        '9830290500',
                        '9542258518',
                        '9745660007',
                        '9836859442',
                        '9952799586',
                        '9988962290',
                        '9569391607',
                        '9032831088',
                        '9893004511',
                        '9472866778',
                        '9550232263',
                        '9966800822',
                        '9728005852',
                        '7383954136',
                        '9865243319',
                        '9687613204',
                        '8921745621',
                        '8907278030',
                        '8930339900',
                        '8386960732',
                        '9887086978',
                        '9509256387',
                        '9671205424',
                        '7988518181',
                        '8930843243',
                        '7014872949',
                        '9828871618',
                        '9496352747',
                        '9746408260',
                        '9828407135',
                        '9785848631',
                        '9847702926',
                        '9034510415',
                        '9829396369',
                        '8860600410',
                        '9437110192',
                        '9948482356',
                        '8002656217',
                        '9149664188',
                        '9592576620',
                        '9030555545',
                        '7099032169',
                        '8006541104',
                        '9160197008',
                        '7795227901',
                        '8102289002',
                        '6200650772',
                        '9771493669',
                        '9835132454',
                        '9835403338',
                        '9304737212',
                        '8928027023',
                        '8658951488',
                        '8250091475',
                        '9033766086',
                        '9666759960',
                        '9561503171',
                        '9644696766',
                        '8770502354',
                        '9652765992',
                        '9647498197',
                        '7869824675',
                        '7660041918',
                        '8105993055',
                        '7356761447',
                        '8527490789',
                        '8081519797',
                        '9960021285',
                        '7600030178',
                        '9727860250',
                        '7001736147',
                        '9039767217',
                        '7283082999',
                        '9131081095',
                        '8778567551',
                        '9101589276',
                        '9420453887',
                        '9618841697',
                        '9483954031',
                        '8218387881',
                        '8958820987',
                        '8507459005',
                        '9759805881',
                        '6302183691',
                        '7007883807',
                        '8077120541',
                        '9674560523',
                        '8011964522',
                        '9561133711',
                        '8010506658',
                        '7021292123',
                        '7008764820',
                        '9917608264',
                        '9045766404',
                        '9417555152',
                        '8495849567',
                        '8086760121',
                        '8075814131',
                        '9390378902',
                        '8089986900',
                        '6281718782',
                        '8087962908',
                        '7657042534',
                        '7005011082',
                        '9881558869',
                        '9011974294',
                        '9284644473',
                        '9096086900',
                        '9167411656',
                        '9156072283',
                        '8090658735',
                        '8777524829',
                        '9946603073',
                        '8209330963',
                        '9846951958',
                        '9750280966',
                        '9088070810',
                        '7900289545',
                        '7309628265',
                        '9996957519',
                        '9910908093',
                        '9049343940',
                        '8888414743',
                        '8927715618',
                        '9805872210',
                        '9717435050',
                        '7906094663',
                        '8860899061',
                        '9744135078',
                        '7908093164',
                        '9408806683',
                        '9744143754',
                        '8248413679',
                        '8139976403',
                        '9977253732',
                        '8095849809',
                        '9893466798',
                        '9964545629',
                        '9980461490',
                        '9900408786',
                        '9450995413',
                        '7017570898',
                        '9611067664',
                        '9259278539',
                        '9871434113',
                        '9335644607',
                        '9639100024',
                        '9548745628',
                        '9839313176',
                        '9580311678',
                        '9557391517',
                        '9760923143',
                        '9882349772',
                        '9564466276',
                        '8017466077',
                        '9007062481',
                        '8902702572',
                        '9674135546',
                        '8101202772',
                        '9735204070',
                        '9830717041',
                        '9600836262',
                        '7797654995',
                        '7405520205',
                        '9727763213',
                        '8485999993',
                        '9048124645',
                        '8130657810',
                        '8273934527',
                        '7558032075',
                        '9958738352',
                        '7898521787',
                        '7904905648',
                        '8374126579',
                        '9958909985',
                        '7610904555',
                        '8910061729',
                        '8178681748',
                        '6394863039',
                        '9920887656',
                        '8527902454',
                        '9732738685',
                        '9909985521',
                        '9370859498',
                        '9028668634',
                        '9033860658',
                        '8770323274',
                        '9930567144',
                        '9082268736',
                        '8976551131',
                        '9014856686',
                        '6238137430',
                        '9101545247',
                        '8433051619',
                        '9977178016',
                        '8096722771',
                        '9677364643',
                        '8086421953',
                        '6306589183',
                        '7034274176',
                        '9491979611',
                        '8123600475',
                        '8951504351',
                        '8957267280',
                        '8825106765',
                        '6207508554',
                        '6309648839',
                        '9719222649',
                        '8653879722',
                        '6290710227',
                        '9497271169',
                        '9995291433',
                        '9553134110',
                        '8219123743',
                        '9136542808',
                        '8075322595',
                        '7483665078',
                        '9782467192',
                        '7976014593',
                        '9116431001',
                        '7789016694',
                        '9338494643',
                        '8883644050',
                        '8087450012',
                        '9100532974',
                        '9694574147',
                        '7878363829',
                        '8605597556',
                        '9998562246',
                        '9900279666',
                        '7906483387',
                        '9666554332',
                        '8896666618',
                        '6265322278',
                        '9612857445',
                        '8910412093',
                        '8329794030',
                        '8850167946',
                        '9985399477',
                        '7339820298',
                        '9814607014',
                        '6284332613',
                        '9084986118',
                        '7903945556',
                        '9929951242',
                        '8446525756',
                        '7338340197',
                        '7903506185',
                        '8219750478',
                        '9495343065',
                        '9073530126',
                        '9007115646',
                        '9123993468',
                        '9182765354',
                        '9046211802',
                        '8056646214',
                        '9149085080',
                        '8907366701',
                        '9983744434',
                        '9610005506',
                        '9679853087',
                        '9306721599',
                        '8840129908',
                        '6295265681',
                        '8904442532',
                        '7002187201',
                        '7218072880',
                        '8709362274',
                        '8897470642',
                        '8801628494',
                        '7989674607',
                        '8267872011',
                        '7034858457',
                        '8094576213',
                        '8140630034',
                        '8441025895',
                        '9112346462',
                        '9902999510',
                        '9847243784',
                        '8555931496',
                        '7005586522',
                        '7008143636',
                        '8898333752',
                        '8795699001',
                        '9890938681',
                        '6385785603',
                        '8867766041',
                        '9533590940',
                        '8360201450',
                        '8148733961',
                        '8328184495',
                        '9960131969',
                        '9739403599',
                        '6309583275',
                        '8617351089',
                        '9082548253',
                        '8600469637',
                        '8837481903',
                        '9831595712',
                        '8153993008',
                        '8348892246',
                        '9892800013',
                        '8972128018',
                        '9599126582',
                        '7789822506',
                        '7226982676',
                        '7032111672',
                        '8876144162',
                        '9747321950',
                        '7776973504',
                        '7897413610',
                        '7907101198',
                        '7022536498',
                        '8555091483',
                        '9061627592',
                        '7001041613',
                        '7869468392',
                        '9400908189',
                        '9673747159',
                        '8097265809',
                        '8357902126',
                        '7908097419',
                        '8310663569',
                        '6282538604',
                        '8975617221',
                        '9875488750',
                        '9555823738',
                        '9000026626',
                        '9743398905',
                        '8240320711',
                        '9767342584',
                        '9827982557',
                        '8949063332',
                        '8233322501',
                        '6296401096',
                        '9633303531',
                        '8638890157',
                        '7013733024',
                        '9766147636',
                        '7980840839',
                        '8157896980',
                        '9875631019',
                        '9704858962',
                        '7702037691',
                        '7001646289',
                        '8375859667',
                        '9176009182',
                        '9676061724',
                        '8393827313',
                        '9952812337',
                        '8088049383',
                        '9479711700',
                        '9528466050',
                        '9081389117',
                        '8930063785',
                        '8983544466',
                        '8087961156',
                        '7675981455',
                        '6290208027',
                        '9366586976',
                        '7905363313',
                        '9034911604',
                        '9985009357',
                        '7736762050',
                        '8271473951',
                        '8407952157',
                        '8348935863',
                        '8667593193',
                        '9573541933',
                        '9833969602',
                        '9865418935',
                        '9874392262',
                        '7769898899',
                        '9050282341',
                        '9325807443',
                        '8308383984',
                        '9103796510',
                        '8194931513',
                        '9986479141',
                        '9839525935',
                        '8007679737',
                        '8699805380',
                        '7987212014',
                        '6397716512',
                        '8309296170',
                        '7447850229',
                        '8551831231',
                        '9774643539',
                        '9574357925',
                        '8507619783',
                        '7838368078',
                        '7620532517',
                        '9908690619',
                        '09045983548',
                        '7908186006',
                        '9440671289',
                        '9703690009',
                        '8975628554',
                        '9766863925',
                        '9664538805',
                        '9022778439',
                        '9146176753',
                        '8732810252',
                        '9806615150',
                        '9948535296',
                        '9830076114',
                        '8271271150',
                        '7797792827',
                        '7871747141',
                        '7009780835',
                        '9140998956',
                        '8102122665',
                        '9963264290',
                        '8197393296',
                        '9638151459',
                        '9163939565',
                        '9704455609',
                        '7219075817',
                        '9746813390',
                        '9761412141',
                        '9730114338',
                        '8250344587',
                        '7890462526',
                        '9745573496',
                        '9163676334',
                        '8617474311',
                        '6290172383',
                        '9656671935',
                        '9759873479',
                        '8910171624',
                        '7982021820',
                        '8400849837',
                        '7819845309',
                        '7799181721',
                        '9082996602',
                        '9626136675',
                        '9561414044',
                        '9694954262',
                        '8813056005',
                        '8605525125',
                        '6305322316',
                        '9773125848',
                        '9566520394',
                        '9526151289',
                        '9579200025',
                        '8600565050',
                        '9398440593',
                        '9067429975',
                        '8946037189',
                        '7074434879',
                        '9552054441',
                        '9064012400',
                        '8135846584',
                        '9381156638',
                        '8825914545',
                        '8688855044',
                        '9149075576',
                        '9704701483',
                        '9612557943',
                        '8348860179',
                        '9897261655',
                        '9079882534',
                        '6003389732',
                        '7003092683',
                        '7798073728',
                        '8296873237',
                        '8108063232',
                        '9779740303',
                        '8480919201',
                        '9529937259',
                        '9052852844',
                        '9642036389',
                        '9041849910',
                        '9559224460',
                        '9600359303',
                        '9970033329',
                        '9600048792',
                        '8112266045',
                        '9911495528',
                        '9884148081',
                        '8149704229',
                        '9988880675',
                        '9258489644',
                        '9560227350',
                        '9959793800',
                        '9810760599',
                        '8948694982',
                        '8052122122',
                        '8607311122',
                        '8003037756',
                        '9874131064',
                        '9337839881',
                        '9896109189',
                        '9782432401',
                        '9823197867',
                        '9793447799',
                        '9702060880',
                        '9991221729',
                        '9372312313',
                        '8909246046',
                        '6375876835',
                        '9713099787',
                        '8879321480',
                        '9168114777',
                        '9270488943',
                        '8087460058',
                        '8108868915',
                        '8976260486',
                        '8976160347',
                        '8888216204',
                        '9665788319',
                        '9766352123',
                        '9503455203',
                        '9664564315',
                        '8240340242',
                        '7875498111',
                        '7019515154',
                        '8008937395',
                        '8492939989',
                        '9546433401',
                        '8101016865',
                        '9931489011',
                        '7509387121',
                        '8469974455',
                        '9746929637',
                        '9168544894',
                        '9058376360',
                        '6204964439',
                        '8619272564',
                        '8931049149',
                        '8250446990',
                        '9767126731',
                        '9981677410',
                        '8962880672',
                        '9353912172',
                        '8460779885',
                        '9033047443',
                        '8866522301',
                        '9604245480',
                        '7053170006',
                        '7275480470',
                        '8077772160',
                        '8307694959',
                        '09539915918',
                        '9209090809',
                        '7385496567',
                        '9840633455',
                        '7389948860',
                        '8126690599',
                        '9259777657',
                        '6204010995',
                        '8335954921',
                        '9528193003',
                        '7200683143',
                        '7895073846',
                        '9525072978',
                        '6280498362',
                        '9113124970',
                        '7508424566',
                        '8171135576',
                        '8208192896',
                        '8484080796',
                        '8918273485',
                        '8409804848',
                        '7776895393',
                        '9130374945',
                        '9948990706',
                        '7980300193',
                        '8075870687',
                        '7012408141',
                        '7219382502',
                        '8778236976',
                        '8879260899',
                        '9874167662',
                        '7076945890',
                        '9538023171',
                        '9562795927',
                        '7904407399',
                        '8919290298',
                        '8074493453',
                        '7978327471',
                        '9319377778',
                        '7904721840',
                        '9163072171',
                        '9326146523',
                        '6261606434',
                        '9816615018',
                        '9655866222',
                        '7980109507',
                        '9039528405',
                        '9350081891',
                        '9310120236',
                        '9061755523',
                        '8562999395',
                        '8957819902',
                        '9722650013',
                        '9998397809',
                        '6207202833',
                        '8345052839',
                        '8050720442',
                        '6291846260',
                        '7357023699',
                        '8847632771',
                        '8882136125',
                        '8054220874',
                        '8299215257',
                        '6280377030',
                        '9919099975',
                        '8945073414',
                        '7000875384',
                        '7709413216',
                        '7079889035',
                        '8847494946',
                        '9855460645',
                        '7291019799',
                        '9148482833',
                        '8449395959',
                        '7985247050',
                        '9835634626',
                        '9500552759',
                        '7524845579',
                        '7355014764',
                        '8876404206',
                        '7247012411',
                        '8439524278',
                        '9494808816',
                        '9718610496',
                        '9562557837',
                        '9790901619',
                        '7240121202',
                        '8850166641',
                        '9982215284',
                        '9304470043',
                        '9971060662',
                        '8948906743',
                        '9260986298',
                        '9871895629',
                        '8871525878',
                        '7021702913',
                        '9924685700',
                        '8224046977',
                        '7000161759',
                        '8876261814',
                        '9567706731',
                        '8304046266',
                        '9641229055',
                        '9673183396',
                        '7008850441',
                        '9821530846',
                        '8686751537',
                        '9064976268',
                        '9217001400',
                        '9632372636',
                        '7560907207',
                        '9607280074',
                        '8417929654',
                        '8145039233',
                        '8891714144',
                        '8950236866',
                        '8871314731',
                        '8898780547',
                        '9848732721',
                        '7276764260',
                        '8051527787',
                        '7204807040',
                        '8360772974',
                        '7042972214',
                        '9569126908',
                        '9348434989',
                        '7738324879',
                        '7005308963',
                        '8617593093',
                        '9091798311',
                        '8698985879',
                        '7899540486',
                        '9022433523',
                        '7906677642',
                        '8630321313',
                        '9163727872',
                        '9728668629',
                        '9641150740',
                        '9628075574',
                        '8318026457',
                        '8709847845',
                        '7488982774',
                        '7065194546',
                        '9524122720',
                        '7629972287',
                        '6290911987',
                        '9101040497',
                        '8667267055',
                        '9306567376',
                        '9996737091',
                        '9793439111',
                        '8759469477',
                        '7709882230',
                        '9067975062',
                        '9977940038',
                        '6301619597',
                        '9744996816',
                        '9764039372',
                        '7447615173',
                        '7651813511',
                        '9058194703',
                        '9527476022',
                        '9994201879',
                        '9848872786',
                        '7794948619',
                        '9179480007',
                        '9539544337',
                        '8698094589',
                        '8623954025',
                        '7013537447',
                        '8238981651',
                        '9137630751',
                        '9047905005',
                        '9995924380',
                        '9890525312',
                        '9029985477',
                        '7304595659',
                        '9930923726',
                        '9701641051',
                        '8200789760',
                        '7418145851',
                        '9526596165',
                        '9841192092',
                        '9804599249',
                        '9812432100',
                        '9582210058',
                        '9884235323',
                        '9660902085',
                        '9662675611',
                        '9879361172',
                        '9773501855',
                        '9435831263',
                        '9386059364',
                        '9040238636',
                        '8709696090',
                        '7764041375',
                        '9774044692',
                        '9746663469',
                        '7306955523',
                        '9843109972',
                        '9840777813',
                        '9846830400',
                        '9727703613',
                        '9962448986',
                        '7275137639',
                        '9645340340',
                        '9414126224',
                        '9991170800',
                        '9995344966',
                        '9896972369',
                        '9255150440',
                        '8432075242',
                        '7736884613',
                        '8955497967',
                        '9050000414',
                        '7742848684',
                        '8290956700',
                        '9929431555',
                        '9896696956',
                        '9818861015',
                        '9728132062',
                        '9136068772',
                        '9652375738',
                        '9703787005',
                        '7837046161',
                        '8901118989',
                        '9177452515',
                        '9060202023',
                        '7677776585',
                        '9304103788',
                        '9507975441',
                        '9583317339',
                        '8099414272',
                        '9797632861',
                        '8168513746',
                        '9911604401',
                        '7696765595',
                        '9853932323',
                        '7903391880',
                        '9620686814',
                        '8689921672',
                        '6294365499',
                        '6305419541',
                        '8957075620',
                        '8891479990',
                        '8830057494',
                        '8401956526',
                        '6388012297',
                        '9745372726',
                        '9790853548',
                        '8446904544',
                        '7708990404',
                        '6296051535',
                        '8868028786',
                        '9832932143',
                        '9423065961',
                        '7339475636',
                        '9503612123',
                        '7893838771',
                        '9970716189',
                        '9064286830',
                        '9899308804',
                        '6394265286',
                        '7488665905',
                        '8420287789',
                        '9838659983',
                        '7907307207',
                        '7850826443',
                        '8530780535',
                        '8757081969',
                        '8619596362',
                        '7558881743',
                        '8158078272',
                        '8240310206',
                        '7657822306',
                        '7510360503',
                        '9219549754',
                        '8528896635',
                        '8105867279',
                        '7558841918',
                        '8790201267',
                        '8369082341',
                        '7906902456',
                        '8140401680',
                        '9895459007',
                        '6295892352',
                        '8197552964',
                        '9663348498',
                        '0996228256',
                        '8374047422',
                        '9247160175',
                        '8317684650',
                        '9715559785',
                        '9819542460',
                        '9922671500',
                        '9820842305',
                        '9552838148',
                        '9860676064',
                        '9720396490',
                        '7878772602',
                        '9845029845',
                        '8086604551',
                        '9805088166',
                        '8887600437',
                        '7702276112',
                        '9034514291',
                        '9048944090',
                        '7373227823',
                        '9310051004',
                        '9010603660',
                        '9918447755',
                        '8874029000',
                        '9582545464',
                        '9542929396',
                        '9014339587',
                        '9987770667',
                        '9143713504',
                        '8978271414',
                        '9961100813',
                        '9690228471',
                        '7017020359',
                        '9890796160',
                        '9009114859',
                        '9977069599',
                        '9439344440',
                        '7010775034',
                        '8821818332',
                        '9538446437',
                        '7828961732',
                        '8618312204',
                        '9886545328',
                        '9761000310',
                        '9599915166',
                        '9919115451',
                        '7838457878',
                        '8310076813',
                        '8105205456',
                        '8840363438',
                        '9838046820',
                        '8892394294',
                        '9008466347',
                        '8197948108',
                        '9410259566',
                        '9805566490',
                        '7248850568',
                        '9459812034',
                        '9540614815',
                        '9062481852',
                        '9038260059',
                        '9940091889',
                        '7908977085',
                        '9674870982',
                        '8777280802',
                        '9735214928',
                        '9038482675',
                        '8697415688',
                        '9593555888',
                        '9749081047',
                        '8511000195',
                        '8124124934',
                        '9544547253',
                        '9510817563',
                        '9746215250',
                        '9971597414',
                        '9718075948',
                        '9655425273',
                        '9791926467',
                        '9847568319',
                        '9033789448',
                        '9843972820',
                        '8547061183',
                        '8130301464',
                        '9582371312',
                        '9033229315',
                        '9648868486',
                        '9760329061',
                        '9727701451',
                        '9095614647',
                        '8821906880',
                        '7304629850',
                        '8410411963',
                        '9071602884',
                        '8447353965',
                        '9706534622',
                        '7001309930',
                        '7040529110',
                        '7644976352',
                        '7086015308',
                        '7838464772',
                        '7266930428',
                        '9960651678',
                        '8347378070',
                        '8097248143',
                        '7084719186',
                        '6201085614',
                        '8910961355',
                        '8460605262',
                        '9606247232',
                        '8108508396',
                        '9995906238',
                        '8918343540',
                        '8667460270',
                        '9108825964',
                        '9901237114',
                        '8156963981',
                        '7798942869',
                        '7974672617',
                        '7739503368',
                        '8436159348',
                        '9998242326',
                        '8227828648',
                        '9942246653',
                        '6280242151',
                        '9500608032',
                        '8637526787',
                        '9567959720',
                        '7989665830',
                        '9686843150',
                        '9966986825',
                        '9917223395',
                        '9720500499',
                        '7011786352',
                        '9649923129',
                        '8409683430',
                        '8494962702',
                        '9909666651',
                        '9337374893',
                        '9140009519',
                        '8439297768',
                        '7985097364',
                        '7015344232',
                        '8374450453',
                        '9884306214',
                        '9552001814',
                        '7876348004',
                        '9878789392',
                        '7060804831',
                        '9045452004',
                        '8595226160',
                        '7678020992',
                        '9444401144',
                        '8699558955',
                        '9706579784',
                        '8000471070',
                        '9833458158',
                        '8754639514',
                        '7907583819',
                        '6382384654',
                        '9635573358',
                        '9170695546',
                        '7569770067',
                        '9123574131',
                        '8910862049',
                        '8802608330',
                        '8262990100',
                        '7039299163',
                        '7059158526',
                        '9095034149',
                        '8087561123',
                        '7829932459',
                        '7276315402',
                        '6371648818',
                        '9875592114',
                        '8697175538',
                        '8507540239',
                        '9864197424',
                        '7583944458',
                        '9568544788',
                        '7306795834',
                        '9743032644',
                        '8006590105',
                        '8924859875',
                        '9789923892',
                        '9946676563',
                        '9306974171',
                        '9519950713',
                        '7352731818',
                        '7062967259',
                        '9887570636',
                        '9733812727',
                        '8890264221',
                        '7358624342',
                        '7373262518',
                        '8369307235',
                        '8369660448',
                        '9588889817',
                        '8356805467',
                        '7379819160',
                        '8050899313',
                        '7259638615',
                        '8083665049',
                        '8501828833',
                        '9899863896',
                        '9943094456',
                        '7987008134',
                        '6289772788',
                        '8981469755',
                        '9100561156',
                        '8698248325',
                        '7997017157',
                        '7013865699',
                        '8200070885',
                        '9635673296',
                        '9792398639',
                        '8910908911',
                        '9116226638',
                        '7774841114',
                        '8573979155',
                        '8172988614',
                        '8917245952',
                        '6351190793',
                        '8668333478',
                        '9358858740',
                        '9042589754',
                        '9850310386',
                        '8853797912',
                        '9579299112',
                        '7032949490',
                        '9653360573',
                        '8287733242',
                        '6260348267',
                        '9539382793',
                        '8176086239',
                        '6382222476',
                        '7654006282',
                        '8302800177',
                        '9974799654',
                        '9838968737',
                        '9128549692',
                        '9977068640',
                        '9631426384',
                        '8446946881',
                        '8838784522',
                        '8103577276',
                        '7972097083',
                        '9647449885',
                        '8793290506',
                        '8157888576',
                        '9496356689',
                        '9960696979',
                        '7905850981',
                        '8777517023',
                        '8271806464',
                        '9743258395',
                        '8094228344',
                        '9455214605',
                        '9175432084',
                        '7992212694',
                        '9958645069',
                        '6386514886',
                        '9004089917',
                        '8197223798',
                        '9092752067',
                        '7080837140',
                        '8421831103',
                        '7976926807',
                        '9624915713',
                        '9772050449',
                        '7093684824',
                        '9786699971',
                        '9768409845',
                        '9966691576',
                        '8008517366',
                        '8319396339',
                        '9659736361',
                        '8908189754',
                        '8965945604',
                        '7980929349',
                        '7418872095',
                        '9168794280',
                        '9552645120',
                        '9310629228',
                        '9038594116',
                        '9618266033',
                        '7978260985',
                        '7411582409',
                        '9080387230',
                        '9912485239',
                        '7745086082',
                        '9897448819',
                        '7004475810',
                        '7028600360',
                        '9895089448',
                        '9999182422',
                        '9075783600',
                        '9160806600',
                        '7800004484',
                        '8943053600',
                        '7508686935',
                        '8698111295',
                        '8687386325',
                        '9066601772',
                        '7975490107',
                        '7903020800',
                        '9923993106',
                        '8087391926',
                        '9846166862',
                        '8137024767',
                        '7738776711',
                        '9322357726',
                        '9454294989',
                        '8433488980',
                        '6232132995',
                        '9961869566',
                        '9573710035',
                        '7717602307',
                        '8451932699',
                        '9453257310',
                        '9811042216',
                        '6295427103',
                        '8381841030',
                        '8149452504',
                        '9009989800',
                        '8536905812',
                        '9985037472',
                        '8826339365',
                        '9866205297',
                        '8484935178',
                        '8949381379',
                        '8459888609',
                        '9205079808',
                        '8609312900',
                        '7547806542',
                        '7908089209',
                        '7043824737',
                        '8286842581',
                        '9841809656',
                        '9559595915',
                        '7044941482',
                        '8759084059',
                        '8089799613',
                        '9140921468',
                        '8898293702',
                        '8800305712',
                        '7011828349',
                        '7397896005',
                        '9733019231',
                        '7218836355',
                        '9659495513',
                        '9654683006',
                        '8581909934',
                        '9666188358',
                        '9972400536',
                        '9874515322',
                        '7567415207',
                        '7893843558',
                        '8147033146',
                        '9188073380',
                        '9966672936',
                        '9663522018',
                        '9500849318',
                        '8297112636',
                        '7506041783',
                        '9686436264',
                        '9108530998',
                        '8837823832',
                        '9164797575',
                        '8806923152',
                        '9072498393',
                        '9056237688',
                        '7001921722',
                        '9539800776',
                        '8700196282',
                        '8502882280',
                        '8872573476',
                        '9328666296',
                        '8454081937',
                        '7795820776',
                        '8870963878',
                        '9113645571',
                        '8652211935',
                        '8129248847',
                        '9391507721',
                        '9808157505',
                        '7975029929',
                        '9340003189',
                        '7799172476',
                        '8087465198',
                        '9904466286',
                        '9686833007',
                        '9760875632',
                        '9712331801',
                        '9764006774',
                        '9823533622',
                        '9845706746',
                        '9960573612',
                        '9585415498',
                        '9564777763',
                        '9771458230',
                        '9891839406',
                        '9906092123',
                        '9838592375',
                        '9884586162',
                        '9838667999',
                        '9688293144',
                        '9022459849',
                        '8889486669',
                        '9909011597',
                        '9491194423',
                        '8054324553',
                        '9551262025',
                        '8528427779',
                        '7666291915',
                        '7506264492',
                        '8668218715',
                        '8087790008',
                        '9930037272',
                        '7276490972',
                        '9619071754',
                        '9011311346',
                        '9511711974',
                        '7083234339',
                        '8380868343',
                        '9867196552',
                        '7057719517',
                        '9833436281',
                        '8976309804',
                        '9769702961',
                        '9730449171',
                        '9970598520',
                        '7003460090',
                        '9014356679',
                        '9447483112',
                        '9773017800',
                        '7730874227',
                        '7218792465',
                        '8460106221',
                        '8345963763',
                        '8356970882',
                        '9826497437',
                        '7278684861',
                        '8892452599',
                        '6291955244',
                        '9707743464',
                        '8698711480',
                        '7448412234',
                        '7449630226',
                        '8884562391',
                        '8870832568',
                        '7803911121',
                        '7017116220',
                        '9760834169',
                        '9719027296',
                        '8109350410',
                        '8013727363',
                        '7060725446',
                        '8223915954',
                        '7200782884',
                        '9981697978',
                        '9891146517',
                        '9123401808',
                        '9989996039',
                        '8954426965',
                        '8906708824',
                        '9918424849',
                        '7828566513',
                        '9046857474',
                        '7305606249',
                        '9428784993',
                        '8309889858',
                        '9159927933',
                        '9009446108',
                        '9720460847',
                        '7040370301',
                        '8100352236',
                        '8889169858',
                        '9403845143',
                        '8760067799',
                        '9977779113',
                        '9749465628',
                        '8847829760',
                        '8094084184',
                        '8053482497',
                        '9812570443',
                        '8770072194',
                        '9584552945',
                        '9815725044',
                        '7394921020',
                        '9442934325',
                        '7777949222',
                        '9919690084',
                        '9982323023',
                        '7009891082',
                        '7398423424',
                        '9792236984',
                        '9146230202',
                        '8600864590',
                        '9821694115',
                        '8335961142',
                        '9576997887',
                        '9685892153',
                        '9664866767',
                        '9829272704',
                        '7002056359',
                        '7690852513',
                        '9100787190',
                        '9310043702',
                        '7278601577',
                        '8709164819',
                        '8607688322',
                        '8885619234',
                        '8708997223',
                        '8013880346',
                        '8085592142',
                        '8210743898',
                        '9457461509',
                        '9462545171',
                        '9518822958',
                        '7340230985',
                        '7250143525',
                        '8969677261',
                        '9540773779',
                        '9877156329',
                        '9310632048',
                        '7277465123',
                        '8143271134',
                        '7068483904',
                        '8503005716',
                        '6398579013',
                        '8395845239',
                        '8580721559',
                        '7007492764',
                        '7986752856',
                        '9560944962',
                        '9953754624',
                        '7737838363',
                        '8813099145',
                        '9656295018',
                        '9993890332',
                        '9779948655',
                        '9639367267',
                        '9595970514',
                        '9059825085',
                        '9737218389',
                        '9372807682',
                        '6380327358',
                        '7907219993',
                        '7001722366',
                        '7045282085',
                        '6290445635',
                        '6290990070',
                        '7508482992',
                        '9752848856',
                        '8906690091',
                        '9123910956',
                        '8924032911',
                        '9358567744',
                        '8879243598',
                        '7306314842',
                        '9446176077',
                        '9450634383',
                        '9745071801',
                        '9994058578',
                        '9109685600',
                        '7076094261',
                        '9550463403',
                        '9348052028',
                        '9345854788',
                        '7076877343',
                        '9597849302',
                        '9744914132',
                        '8700457993',
                        '9140100631',
                        '8882082392',
                        '8425007642',
                        '9759380722',
                        '6380290782',
                        '8097168717',
                        '9494670441',
                        '8511122408',
                        '9677119581',
                        '9101452773',
                        '9052567775',
                        '9149202011',
                        '8949087779',
                        '6001627314',
                        '8329752082',
                        '9897799920',
                        '9539828799',
                        '8013904947',
                        '8146617935',
                        '9832401998',
                        '7458083524',
                        '8015358545',
                        '9058906501',
                        '9585955028',
                        '7002638623',
                        '9027390854',
                        '9606504948',
                        '6289226464',
                        '9388386658',
                        '6909685303',
                        '9359139536',
                        '6381316690',
                        '7696609597',
                        '6282226910',
                        '9601788236',
                        '9560434001',
                        '9551276932',
                        '8600923904',
                        '9804263951',
                        '8296290772',
                        '7409871178',
                        '7020650869',
                        '8801210008',
                        '7387721586',
                        '7015536482',
                        '9420886423',
                        '9017787800',
                        '7984106109',
                        '9420837551',
                        '9822112710',
                        '9922296340',
                        '9619031403',
                        '8331896989',
                        '9830190649',
                        '9032906837',
                        '9979759681',
                        '9548499995',
                        '9732013332',
                        '9050135959',
                        '9991453634',
                        '9550340401',
                        '9888283427',
                        '8804742010',
                        '9866982273',
                        '9778981314',
                        '9954807329',
                        '9796229000',
                        '9814638240',
                        '9041955855',
                        '9966449544',
                        '9789939298',
                        '9953331401',
                        '9727772834',
                        '9095271820',
                        '8866236967',
                        '8826386801',
                        '9982478161',
                        '8901378151',
                        '8594023454',
                        '9846507514',
                        '9729379699',
                        '9983313576',
                        '8955066527',
                        '7801048061',
                        '9783929200',
                        '9908224315',
                        '9983267000',
                        '9497577641',
                        '9587010909',
                        '9896462030',
                        '9996648196',
                        '9605347247',
                        '9526747827',
                        '8210057756',
                        '9155683091',
                        '9441939866',
                        '9006632666',
                        '9636510847',
                        '9603530803',
                        '9032977321',
                        '9908233227',
                        '8210407548',
                        '9959312850',
                        '8699483238',
                        '8008389083',
                        '9304336536',
                        '7091090777',
                        '8540826878',
                        '9888811002',
                        '9063378889',
                        '8876382701',
                        '9048727017',
                        '7501024457',
                        '8116696755',
                        '9591857365',
                        '9947400561',
                        '9344154518',
                        '9911889930',
                        '7993477047',
                        '8297160843',
                        '7358372200',
                        '8368906209',
                        '9670138991',
                        '7875588024',
                        '9992543244',
                        '8800161495',
                        '7419319333',
                        '8093319311',
                        '9158788825',
                        '8309143331',
                        '8888437830',
                        '8308864238',
                        '8617462701',
                        '8123884685',
                        '7302184292',
                        '9867558692',
                        '6296230409',
                        '8867145938',
                        '7432948348',
                        '9616150011',
                        '9110140392',
                        '9634560472',
                        '6206004575',
                        '9802557501',
                        '7398840737',
                        '6200697418',
                        '6002538609',
                        '8306567656',
                        '9174976678',
                        '9911837972',
                        '9198572036',
                        '9988223202',
                        '9036670023',
                        '8240085583',
                        '8707259203',
                        '7900957749',
                        '9500849816',
                        '8142873280',
                        '8086138568',
                        '8866134911',
                        '7015352173',
                        '9390078076',
                        '9048467238',
                        '7044741933',
                        '9083692919',
                        '9867043117',
                        '9869330195',
                        '9766413235',
                        '9980092145',
                        '9368903860',
                        '7905768114',
                        '9945426569',
                        '9546643031',
                        '8398989293',
                        '9309228801',
                        '9719060300',
                        '9896844644',
                        '9032702946',
                        '8449785136',
                        '9884928223',
                        '9847343266',
                        '9889022665',
                        '9600088998',
                        '9015212692',
                        '8988036595',
                        '8447194813',
                        '8148723251',
                        '7879131511',
                        '8792656682',
                        '9160001100',
                        '9727707678',
                        '9744943643',
                        '9747622992',
                        '9834636317',
                        '9028338918',
                        '8287430910',
                        '6290422689',
                        '9847242372',
                        '7000491712',
                        '9880124800',
                        '8547554481',
                        '7477466606',
                        '7411346537',
                        '7869598223',
                        '8871022312',
                        '9844847563',
                        '6361050288',
                        '7259291367',
                        '7974805348',
                        '9916555766',
                        '9559914399',
                        '7088440099',
                        '9695977799',
                        '7007449050',
                        '9773456244',
                        '9452664881',
                        '8562936824',
                        '9548856057',
                        '9919802719',
                        '9984223330',
                        '9591069115',
                        '9058999504',
                        '9582119114',
                        '9759164012',
                        '9674449701',
                        '9038224662',
                        '9933416121',
                        '7439939437',
                        '9749362736',
                        '9629538899',
                        '9585156007',
                        '9840886835',
                        '8489919958',
                        '9711015621',
                        '9020258223',
                        '8589041140',
                        '9953820542',
                        '9994784214',
                        '7007501810',
                        '9773848846',
                        '9427233104',
                        '9599645951',
                        '9946631857',
                        '9068397142',
                        '7089278489',
                        '8374603658',
                        '8779675182',
                        '7004152123',
                        '8756309477',
                        '7796863236',
                        '8638094675',
                        '9985225525',
                        '9811077196',
                        '8874734444',
                        '9381863784',
                        '9961409734',
                        '9987917231',
                        '9361551933',
                        '8970115042',
                        '9265507426',
                        '8919958745',
                        '7892967216',
                        '9182617418',
                        '9381885366',
                        '8073259475',
                        '9458888552',
                        '9346111975',
                        '8210336586',
                        '9989601649',
                        '9948869103',
                        '9478830199',
                        '7003763470',
                        '7089411881',
                        '8271182899',
                        '9621216580',
                        '9229292692',
                        '8077723685',
                        '9743110363',
                        '9567453729',
                        '7303642407',
                        '9890750508',
                        '9100669212',
                        '8340492676',
                        '7842342343',
                        '9158219012',
                        '7000456493',
                        '6395967280',
                        '8198050839',
                        '8839342714',
                        '6284392975',
                        '9284894366',
                        '9976627976',
                        '7594026062',
                        '7386117905',
                        '8792671418',
                        '8511087122',
                        '9136162196',
                        '9373195152',
                        '9353384767',
                        '8472053719',
                        '6297182580',
                        '7744025686',
                        '9920105009',
                        '8591140616',
                        '9822822662',
                        '9838985193',
                        '8247434698',
                        '6005239526',
                        '7840803204',
                        '7891608861',
                        '6000854636',
                        '7003167252',
                        '9368497466',
                        '8309451595',
                        '8494826739',
                        '9967489086',
                        '7508380352',
                        '7737603505',
                        '9168999899',
                        '7908705054',
                        '8185815011',
                        '8908537464',
                        '7306792983',
                        '8639388455',
                        '7736260378',
                        '9730492973',
                        '9075843693',
                        '9034401609',
                        '7903529732',
                        '8113000041',
                        '8602021551',
                        '6263938457',
                        '7810897479',
                        '9054158711',
                        '8385813674',
                        '9166400104',
                        '7006066461',
                        '7003781281',
                        '7900660515',
                        '9904930069',
                        '7777960196',
                        '9008152999',
                        '9748817016',
                        '7003007785',
                        '9860084603',
                        '9126560153',
                        '9964668482',
                        '7044967410',
                        '8509382933',
                        '9698689766',
                        '9609092291',
                        '8249066743',
                        '8329296016',
                        '8266974395',
                        '6302839817',
                        '9995490892',
                        '7019057632',
                        '9631947323',
                        '7738621957',
                        '9137893650',
                        '7679630303',
                        '9455304643',
                        '6300094970',
                        '7754966561',
                        '9623623029',
                        '8141391927',
                        '9521255711',
                        '9604820920',
                        '7278948287',
                        '7770053353',
                        '7506362820',
                        '9094239354',
                        '7002561141',
                        '7228052781',
                        '8801520249',
                        '9898401590',
                        '9620170746',
                        '7799991997',
                        '9503334524',
                        '9330848698',
                        '8617572327',
                        '7073991551',
                        '7007014540',
                        '9060705124',
                        '8082433716',
                        '9791883878',
                        '8638532785',
                        '7755953227',
                        '9869956113',
                        '9058177776',
                        '7907489509',
                        '8687993933',
                        '8432357410',
                        '8547471840',
                        '9947607025',
                        '8056477708',
                        '9730502088',
                        '9538417380',
                        '8116030183',
                        '9706929499',
                        '9850898946',
                        '9714204761',
                        '8757894191',
                        '9725157390',
                        '8979831937',
                        '9986629625',
                        '7016106468',
                        '9930955235',
                        '7219322662',
                        '7356358157',
                        '8143197057',
                        '7399514666',
                        '9309119535',
                        '8989677930',
                        '8128632034',
                        '8187873707',
                        '7977015427',
                        '9635535494',
                        '8388080963',
                        '9746883800',
                        '8088819707',
                        '7355719112',
                        '8590257353',
                        '9251777729',
                        '8883222922',
                        '8951472974',
                        '9028466101',
                        '9860888127',
                        '8777725804',
                        '8252111164',
                        '8778347005',
                        '7567455989',
                        '7987970120',
                        '9960597076',
                        '9797577057',
                        '7384157156',
                        '9473089123',
                        '9700145100',
                        '8600316247',
                        '9008515897',
                        '9677874623',
                        '8089323732',
                        '9939930618',
                        '9182585892',
                        '7044915936',
                        '9329237702',
                        '6264941758',
                        '7558875386',
                        '9712504720',
                        '7020105027',
                        '8095417001',
                        '8110854546',
                        '6392453275',
                        '8307878307',
                        '8303922039',
                        '9990153576',
                        '8405967907',
                        '7007506746',
                        '9381901486',
                        '9303211309',
                        '8981307957',
                        '8181000691',
                        '8106998330',
                        '9819650582',
                        '8667051440',
                        '9907002209',
                        '6207063447',
                        '8880948912',
                        '8754340736',
                        '9585469777',
                        '9164008977',
                        '9645520031',
                        '9479977973',
                        '7219140824',
                        '8273024464',
                        '9545114813',
                        '7001370319',
                        '9659422430',
                        '9834901122',
                        '9048025297',
                        '9782160015',
                        '7090171886',
                        '8258058538',
                        '7569777650',
                        '9993635052',
                        '8402804957',
                        '6366198815',
                        '9499831919',
                        '7980321327',
                        '8639296477',
                        '8486634259',
                        '7356258081',
                        '8791529182',
                        '8617445850',
                        '9330158030',
                        '9664224013',
                        '9150111545',
                        '7896849557',
                        '6397027694',
                        '7815953635',
                        '9810957523',
                        '8077835073',
                        '8589081233',
                        '7549583029',
                        '9538344595',
                        '9464748456',
                        '9599057535',
                        '7725999901',
                        '9911900411',
                        '8125803161',
                        '9368029856',
                        '9820432736',
                        '9804269889',
                        '9036980130',
                        '9413546925',
                        '9766143432',
                        '7507069979',
                        '9729825699',
                        '9463925140',
                        '9545890202',
                        '8055803316',
                        '9893997873',
                        '8929401850',
                        '9997303415',
                        '8655727963',
                        '9885524348',
                        '8224001655',
                        '8420173940',
                        '9831574723',
                        '9819887001',
                        '9922959157',
                        '9619184867',
                        '9960355004',
                        '9819194747',
                        '7276650002',
                        '9670193178',
                        '9404211779',
                        '8708074285',
                        '8218390210',
                        '8949100540',
                        '8805821993',
                        '8431203022',
                        '8390619119',
                        '8115150365',
                        '7509814202',
                        '7822004927',
                        '9123121967',
                        '8125447539',
                        '9820138934',
                        '9530002426',
                        '8469862241',
                        '7708674124',
                        '9452681521',
                        '9595189324',
                        '8129695764',
                        '7278946293',
                        '8383079831',
                        '9800133672',
                        '8976645021',
                        '9108775708',
                        '8511599878',
                        '8005603252',
                        '9140800272',
                        '8871608319',
                        '8090800712',
                        '9140225472',
                        '8279498972',
                        '9519258822',
                        '9336914028',
                        '9838263803',
                        '9098297585',
                        '7903286108',
                        '7988065751',
                        '8755422880',
                        '8073683323',
                        '9828597685',
                        '9304943022',
                        '8817412529',
                        '9525939458',
                        '7022462429',
                        '9602485849',
                        '9624251446',
                        '9666557570',
                        '7259459959',
                        '9775362236',
                        '9733366314',
                        '8435315936',
                        '7034540114',
                        '8638295589',
                        '9742432540',
                        '7036952601',
                        '9024378827',
                        '8108947483',
                        '8240019281',
                        '8928086373',
                        '7506149474',
                        '9557167736',
                        '9890387894',
                        '9593211751',
                        '7890043283',
                        '7909086736',
                        '6393091159',
                        '7003098015',
                        '8085374282',
                        '9416637847',
                        '6354384235',
                        '9694815155',
                        '7588254498',
                        '8768570941',
                        '8670502356',
                        '9883531932',
                        '9447713192',
                        '7908458303',
                        '9899025603',
                        '9528811293',
                        '9649333404',
                        '9805749805',
                        '9927194124',
                        '7278028783',
                        '8320487547',
                        '7999765291',
                        '9368489281',
                        '7985312642',
                        '7842392134',
                        '8865858987',
                        '8950622889',
                        '9380008684',
                        '7011527271',
                        '9630140352',
                        '7973311611',
                        '9773828281',
                        '8376969170',
                        '9642173919',
                        '8218906572',
                        '9058320223',
                        '8423777796',
                        '8872589766',
                        '9503150317',
                        '7897503301',
                        '9340208577',
                        '9182135523',
                        '9153836177',
                        '8109909209',
                        '9313649973',
                        '8708975602',
                        '8707535826',
                        '8928872438',
                        '9899428419',
                        '8617622830',
                        '8944895763',
                        '7018896613',
                        '9735145311',
                        '7905609307',
                        '6386122397',
                        '7986797051',
                        '7063190407',
                        '8072311130',
                        '9549144699',
                        '9010391183',
                        '8670448299',
                        '8618048726',
                        '7206686807',
                        '9503933159',
                        '6294398174',
                        '7745060451',
                        '7980723433',
                        '9154044471',
                        '9897770207',
                        '9664201332',
                        '9930727174',
                        '7869991103',
                        '6398911192',
                        '8083138095',
                        '8670672813',
                        '8019814972',
                        '9769882764',
                        '9967879030',
                        '8016134868',
                        '8975908594',
                        '9804077691',
                        '9820332053',
                        '8507181007',
                        '9620881061',
                        '7395879895',
                        '6282885472',
                        '9050925455',
                        '8220839191',
                        '6351148740',
                        '6369971844',
                        '8696422143',
                        '9653128459',
                        '9967846628',
                        '6388768326',
                        '8906790401',
                        '8779636327',
                        '9663219141',
                        '7008400964',
                        '6375746091',
                        '8554942703',
                        '8707652772',
                        '9860978067',
                        '9544616630',
                        '9819127612',
                        '9625507980',
                        '9992609707',
                        '8709957199',
                        '8309918481',
                        '9971429517',
                        '8748970624',
                        '9894409113',
                        '7977016189',
                        '9641871273',
                        '7015403014',
                        '9304464896',
                        '9592328102',
                        '9798913849',
                        '9795414751',
                        '7003329625',
                        '8296209953',
                        '7994318496',
                        '9917714313',
                        '9869108385',
                        '7305786602',
                        '9657678654',
                        '9985066343',
                        '8919936805',
                        '9923576477',
                        '8005976211',
                        '9392960557',
                        '8873284520',
                        '9892700631',
                        '7906769593',
                        '7503000666',
                        '9398579409',
                        '9884791266',
                        '7356812465',
                        '6289016780',
                        '9247784194',
                        '8386055999',
                        '9966180509',
                        '8606713826',
                        '8727887973',
                        '8758490805',
                        '9346663484',
                        '8360678290',
                        '7546975860',
                        '8600220182',
                        '8888309897',
                        '9673614016',
                        '9769837621',
                        '9096814892',
                        '9821481341',
                        '9022581993',
                        '9890871788',
                        '9518581462',
                        '9822558837',
                        '9698437743',
                        '8436485152',
                        '9163112900',
                        '8886848533',
                        '9995559782',
                        '9989867316',
                        '9467774753',
                        '8697949405',
                        '7278046553',
                        '9177255766',
                        '9636697461',
                        '9887147004',
                        '9034937088',
                        '9909415334',
                        '9887363569',
                        '8249336258',
                        '9805146732',
                        '9938846961',
                        '9718698999',
                        '8809418611',
                        '9894566321',
                        '9909006764',
                        '8010194557',
                        '9726231143',
                        '9899987661',
                        '9597344010',
                        '9544849404',
                        '8510998484',
                        '7615992864',
                        '9829122555',
                        '8769409296',
                        '9866331991',
                        '9828864077',
                        '8547305299',
                        '8708423074',
                        '9887181070',
                        '9700078429',
                        '9828060026',
                        '8235383735',
                        '9534810783',
                        '8011371114',
                        '9705553693',
                        '7002482616',
                        '8982327181',
                        '9658666981',
                        '8559070109',
                        '9401299108',
                        '9358060190',
                        '9100551583',
                        '9546226925',
                        '9848365900',
                        '9642727108',
                        '9386653563',
                        '9796629733',
                        '7005244134',
                        '9308948675',
                        '9830515059',
                        '6300608299',
                        '9061836493',
                        '9586770169',
                        '7001249581',
                        '9967469804',
                        '9895008235',
                        '8118808982',
                        '9975326708',
                        '9372096602',
                        '8099908498',
                        '9020294469',
                        '7470600299',
                        '9101460292',
                        '9116956429',
                        '8420281360',
                        '7760246099',
                        '9154111546',
                        '9175575731',
                        '9101822166',
                        '9089934655',
                        '7057444559',
                        '6205946835',
                        '9974849046',
                        '6305020735',
                        '9768156767',
                        '7666392384',
                        '9692006705',
                        '8298596225',
                        '6386039427',
                        '9144550357',
                        '9051839967',
                        '8789250783',
                        '8630730554',
                        '9045395299',
                        '9034775564',
                        '8897023267',
                        '8597341206',
                        '6299129834',
                        '7017111796',
                        '8009979719',
                        '9074615778',
                        '7836802169',
                        '7240869908',
                        '8356925026',
                        '8578816289',
                        '8354994972',
                        '7676256024',
                        '8129492603',
                        '7673930929',
                        '7056242357',
                        '7265997572',
                        '8075123569',
                        '9714834750',
                        '7568806411',
                        '9773402157',
                        '7507507958',
                        '9022464886',
                        '9664395548',
                        '8624804845',
                        '9405478786',
                        '9833344001',
                        '8275522244',
                        '9897160643',
                        '9972725433',
                        '9738010182',
                        '9986760312',
                        '9739071188',
                        '9914307547',
                        '7981216583',
                        '9867665957',
                        '8923386233',
                        '9933355965',
                        '9034552234',
                        '9723378692',
                        '9747055577',
                        '9310805234',
                        '9791808891',
                        '9728328007',
                        '8770122474',
                        '9874364403',
                        '9665121712',
                        '9522720871',
                        '9888955771',
                        '8847372721',
                        '9029418903',
                        '9573855771',
                        '9988573532',
                        '9946894757',
                        '8423454041',
                        '9051957055',
                        '7352522339',
                        '8250692253',
                        '9860944250',
                        '9916516368',
                        '9743665543',
                        '9738575852',
                        '8319488107',
                        '9620070703',
                        '9452526050',
                        '9536992063',
                        '9719100261',
                        '8299177492',
                        '9555729029',
                        '9759411966',
                        '7905397483',
                        '9839126478',
                        '9451780418',
                        '9932028550',
                        '9007219899',
                        '8629925747',
                        '9944466818',
                        '7980730993',
                        '9051944118',
                        '9836354441',
                        '9932026587',
                        '9232581632',
                        '9831055512',
                        '7980985641',
                        '9830204425',
                        '8052631314',
                        '9873160525',
                        '9050320007',
                        '9788884027',
                        '9810606572',
                        '9994121196',
                        '8680063446',
                        '9744104401',
                        '9659332237',
                        '8200230527',
                        '8943668351',
                        '6282493917',
                        '8574343433',
                        '8839394461',
                        '8008786476',
                        '9967809719',
                        '9857946486',
                        '9351565150',
                        '8824248835',
                        '7985572842',
                        '8595374949',
                        '8866091015',
                        '8688861163',
                        '8580914031',
                        '7439667976',
                        '8777731490',
                        '6300299392',
                        '9182284520',
                        '9074709538',
                        '8273866145',
                        '7738151078',
                        '8828662325',
                        '7983905626',
                        '7025460875',
                        '7569069190',
                        '9929040122',
                        '9983343997',
                        '8452061392',
                        '9767496127',
                        '9700717144',
                        '9795558640',
                        '8077374481',
                        '8917481892',
                        '7208187603',
                        '7873350983',
                        '7602834199',
                        '7989806403',
                        '9844444634',
                        '8769803009',
                        '9305112367',
                        '8770332048',
                        '7084704250',
                        '7532883913',
                        '9309810682',
                        '7300357480',
                        '7012678283',
                        '9594254606',
                        '7504494336',
                        '8856929425',
                        '9947677985',
                        '9161051515',
                        '8707630305',
                        '7715066818',
                        '7001175496',
                        '7259476667',
                        '9350346880',
                        '7900092008',
                        '9728639511',
                        '8923546426',
                        '7768029011',
                        '9567209498',
                        '9922266652',
                        '9677554756',
                        '7204321929',
                        '9660196395',
                        '9206205202',
                        '7985958471',
                        '8943041837',
                        '9755710772',
                        '9754055544',
                        '8807776681',
                        '8148283731',
                        '9503060670',
                        '9770779774',
                        '9111888046',
                        '9551599122',
                        '7003554708',
                        '7005815226',
                        '9913708010',
                        '7870680998',
                        '7002719193',
                        '9602671219',
                        '7479383010',
                        '7509533429',
                        '9766663559',
                        '6266013841',
                        '9044462640',
                        '9920891811',
                        '9714143452',
                        '8423686588',
                        '9635615272',
                        '8582906381',
                        '7869441257',
                        '9043643985',
                        '9633214602',
                        '6391415008',
                        '9900828536',
                        '9634040640',
                        '7002519620',
                        '7033523272',
                        '8581805899',
                        '7972181219',
                        '9167348842',
                        '9977794344',
                        '7799598977',
                        '6383543898',
                        '8981535558',
                        '8268228385',
                        '9822921693',
                        '9594063997',
                        '8219818057',
                        '9618486801',
                        '9563311814',
                        '7411200946',
                        '9898228095',
                        '8360470377',
                        '8233915285',
                        '9894803623',
                        '7006629527',
                        '6385484402',
                        '8200548223',
                        '8609889315',
                        '9562918032',
                        '9064776058',
                        '8532851320',
                        '8848007512',
                        '8967310383',
                        '9106917151',
                        '7499630485',
                        '9566550790',
                        '9000097162',
                        '8103696935',
                        '9930454198',
                        '9846665074',
                        '8496923216',
                        '9895542461',
                        '7007878098',
                        '9531599383',
                        '8961696032',
                        '9313537114',
                        '9211030968',
                        '8504967171',
                        '9173567963',
                        '9665729012',
                        '9126465993',
                        '7486878874',
                        '7792074330',
                        '9666986639',
                        '9496111709',
                        '9881172828',
                        '9110181347',
                        '9987944435',
                        '9746573793',
                        '6295699984',
                        '9696559620',
                        '7988728648',
                        '8888809756',
                        '7417167176',
                        '8698757564',
                        '9782102223',
                        '9888552810',
                        '9062327375',
                        '9718211105',
                        '9556532388',
                        '7299706035',
                        '7666415678',
                        '8465901568',
                        '9980171669',
                        '9986785866',
                        '7698987373',
                        '9924715920',
                        '6206726050',
                        '7980065475',
                        '8868820806',
                        '9550021679',
                        '9701917112',
                        '9832093231',
                        '7449116990',
                        '9012514134',
                        '9775967222',
                        '8017119262',
                        '9014284063',
                        '8586949891',
                        '9573682452',
                        '9999895946',
                        '9336988489',
                        '7795526467',
                        '6282673312',
                        '9820777281',
                        '9352101132',
                        '6290601760',
                        '9012208787',
                        '8608590406',
                        '9946315313',
                        '7337657931',
                        '8867971760',
                        '7887903036',
                        '9921688759',
                        '9809955875',
                        '8601412120',
                        '8340521975',
                        '9638704734',
                        '7010924511',
                        '9712274911',
                        '9883393664',
                        '8938855488',
                        '8876995895',
                        '8838185186',
                        '7026268070',
                        '7537820206',
                        '7722047166',
                        '9916992706',
                        '8333933823',
                        '9095888007',
                        '9959092220',
                        '6303243909',
                        '9750744785',
                        '7385535761',
                        '8013717320',
                        '9091438845',
                        '9888309434',
                        '9795405537',
                        '9315101511',
                        '8699010624',
                        '8400448510',
                        '9080215548',
                        '8891227092',
                        '9654907776',
                        '8445225187',
                        '9944512791',
                        '7980383187',
                        '7823005981',
                        '8793388653',
                        '9435983196',
                        '8894533177',
                        '8876278956',
                        '8090266652',
                        '7351519104',
                        '8638695189',
                        '8097518648',
                        '8623032961',
                        '8077810524',
                        '7393820818',
                        '8507005631',
                        '9694133666',
                        '9960005784',
                        '7600459112',
                        '9618327557',
                        '8509407025',
                        '7376742410',
                        '9068101006',
                        '9008507918',
                        '7976315693',
                        '9948530452',
                        '7736079550',
                        '9962075780',
                        '9664144896',
                        '9561004872',
                        '7796488719',
                        '7276177958',
                        '7502184778',
                        '7769802535',
                        '9983131070',
                        '9048273246',
                        '8974566387',
                        '7058363236',
                        '7972020414',
                        '9366189088',
                        '9175777600',
                        '9325664351',
                        '7888356769',
                        '6238433191',
                        '9810548566',
                        '7066478027',
                        '8140529717',
                        '7066240941',
                        '9731976675',
                        '9996269689',
                        '7860720925',
                        '8457900904',
                        '8789393302',
                        '9000585979',
                        '8082397997',
                        '8341350459',
                        '8927050479',
                        '9853607924',
                        '8943999543',
                        '9720766800',
                        '9739254376',
                        '9935272228',
                        '9992220252',
                        '9820320352',
                        '9820979148',
                        '7208769374',
                        '7800780028',
                        '9829297472',
                        '9278820009',
                        '9351646392',
                        '9435570101',
                        '9785428644',
                        '9582488402',
                        '9177340172',
                        '9988364063',
                        '7006399935',
                        '9561352935',
                        '9555338789',
                        '9870616191',
                        '9767449809',
                        '7020666742',
                        '9850360722',
                        '9702958110',
                        '7719919262',
                        '9823366771',
                        '9049099199',
                        '7506642007',
                        '9822418729',
                        '9730700820',
                        '8055357679',
                        '9881825634',
                        '9730779360',
                        '9960183317',];


            
                        if(!$depot){
              Mail::to('shailesh.sirsikar1@cipla.com')->send(new NeblogisticDepotTmMapping($post));  
              return response()->json(['status' => 'mapping error', 'message' => 'Data not submitted. You are not mapped to a depot. Please contact system administrator']);  
            }

            if (in_array($post['doctor_mobile_number'], $phones)) {
                return response()->json([
                    'status' => 'failure',
                    'message' => 'The phone number you used belongs to a Cipla employee and cannot be used as a doctor\'s phone number.'
                ]);
            }

            if ($post['do_you_need_more_than_5_nebulizers'] === 'No') {
                $count = DB::table('neblogistic')
                    ->where('msl_code', $post['msl_code'])
                    ->whereMonth('created_at', date('m'))
                    ->whereYear('created_at', date('Y'))
                    ->whereIn('status', ['Requested', 'L1 Approved', 'Approved'])
                    ->sum('no_of_nebulizer');

                $remaining = 5 - $count;
                if ($remaining <= 0) {
                    return response()->json(['status' => 'failure', 'message' => 'You have already reached the monthly limit of 5 nebulizers for this doctor.' ]);
                }
                if ($post['no_of_nebulizer'] > $remaining) {
                    return response()->json(['status' => 'failure', 'message' => 'Only {$remaining} more nebulizer(s) can be requested this month.' ]);
                }
            }


            $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_type'], 
                    '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'], 
                    'geolocation_longitude' => $post['geolocation_longitude'], 
                    'geolocation_address' => $post['geolocation_address'], 
                    'geolocation_json' => $post['geolocation_json'],
                    'depot_id' => $depot->id,
                    'depot_name' => $depot->name,
                    'old_employee_code' => $post['emp_id'],
                    'more_than_5_nebulizer' => $post['do_you_need_more_than_5_nebulizers'],
                    // 'transporter'
                    'remarks' => $post['remarks'],
                    'paramedic_alternate_contact_number' => $post['paramedic_alternate_contact_number']
            ];

            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'];
            }

            if (isset($post['status']) && $post['status'] === 'Requested') {
                $datatosave['created_at'] = date('Y-m-d H:i:s');
            }

            $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'])) {
                    $subid = $post['submission_id'];
                    $oldBySubmission = DB::table('neblogistic')->where('submission_id', $post['submission_id'])->first();
                    $oldBySubmissionArray = $oldBySubmission ? json_decode(json_encode($oldBySubmission), true) : null;
                    DB::table('neblogistic')->where('submission_id', $post['submission_id'])->update($datatosave);
                    if ($oldBySubmissionArray) {
                        NeblogisticAuditService::logUpdate(
                            $oldBySubmission->id,
                            $oldBySubmissionArray,
                            $datatosave,
                            null,
                            $request
                        );
                    }

                    $finfo = null;
                    if ($post['status'] != 'Partially Saved') {
                        $post['record_id'] = $post['submission_id'];
                        unset($post['submission_id']);
                        unset($post['id']);
                        $finfo = LambdaRequest::postrequest('form', 'formentity/submitform', ['formdata' => $post, 'entity_id' => $formdata->form_id, 'user_id' => $formdata->user_id, 'partition' => $formdata->partition ]);
                        $datatosave['submission_id'] = $finfo->data->submission->id;
                        $datatosave['abm_user_id'] = $finfo->data->submission->workflow_next_approver;
                        $oldById = DB::table('neblogistic')->where('id', $subid)->first();
                        $oldByIdArray = $oldById ? json_decode(json_encode($oldById), true) : null;
                        DB::table('neblogistic')->where('id', $subid)->update($datatosave);
                        if ($oldByIdArray) {
                            NeblogisticAuditService::logUpdate(
                                $subid,
                                $oldByIdArray,
                                $datatosave,
                                null,
                                $request
                            );
                        }
                        Log::debug("Updating Neblogistics 2");
                        Log::debug(print_r($finfo, true));
                    }else{
                        $oldPartial = DB::table('neblogistic')->where('id', $post['submission_id'])->first();
                        $oldPartialArray = $oldPartial ? json_decode(json_encode($oldPartial), true) : null;
                        DB::table('neblogistic')->where('id', $post['submission_id'])->update($datatosave);
                        if ($oldPartialArray) {
                            NeblogisticAuditService::logUpdate(
                                $post['submission_id'],
                                $oldPartialArray,
                                $datatosave,
                                null,
                                $request
                            );
                        }
                    }

                } else {
                    //create mysql dynamo
                    $insertedId = DB::table('neblogistic')->insertGetId($datatosave);
                    if (!empty($datatosave['request_letter'])) {
                        $newLetterUrl = $this->neblogisticPrefixRequestLetterOnS3($datatosave['request_letter'], $insertedId);
                        if ($newLetterUrl !== $datatosave['request_letter']) {
                            $datatosave['request_letter'] = $newLetterUrl;
                            DB::table('neblogistic')->where('id', $insertedId)->update(['request_letter' => $newLetterUrl]);
                        }
                    }
                    // Log INSERT operation
                    NeblogisticAuditService::logInsert($insertedId, $datatosave, $request);
                    
                    //echo '
'; print_r($datatosave); exit;

                    $finfo = null;
                    $res = false;

                    if ($post['status'] != 'Partially Saved') {
                        $post['record_id'] = $insertedId;
                        $finfo = LambdaRequest::postrequest('form', 'formentity/submitform', ['formdata' => $post, 'entity_id' => $formdata->form_id, 'user_id' => $formdata->user_id, 'partition' => $formdata->partition ]);
                    }
                    // Get old data before update
                    $oldData = DB::table('neblogistic')->where('id', $insertedId)->first();
                    $oldDataArray = $oldData ? json_decode(json_encode($oldData), true) : null;
                    
                    $submissionId = isset($finfo->data->submission->id) ? $finfo->data->submission->id : null;
                    $abmid = isset($finfo->data->submission->workflow_next_approver) ? $finfo->data->submission->workflow_next_approver : null;

                    if ($post['status'] != 'Partially Saved') {
                        $res = DB::table('neblogistic')->where('id', $insertedId)->update(['submission_id' => $submissionId, 'abm_user_id' => $abmid]);
                    }
                    // Log UPDATE operation
                    if ($res) {
                        NeblogisticAuditService::logUpdate(
                            $insertedId, 
                            $oldDataArray, 
                            ['submission_id' => $submissionId],
                            ['submission_id' => ['old' => $oldDataArray['submission_id'] ?? null, 'new' => $submissionId]],
                            $request
                        );
                    }
                    
                    Log::debug("Creating Neblogistics");
                    Log::debug(print_r($finfo, true));
                }

                if($post['status'] != 'Partially Saved'){
                    if (empty($post['submission_id']) && !empty($datatosave['submission_id'])) {
                        $post['submission_id'] = $datatosave['submission_id'];
                    }
                    // Mail::to($datatosave['emp_email'])->send(new Neblogistic($post));
                    // Mail::to($datatosave['abm_email'])->cc('ravigulhane1983@gmail.com')->send(new NeblogisticAbm($post));
                    // DB::table('neblogistic')
                    //     ->where('submission_id', $post['submission_id'])
                    //     ->update(['email_sent' => 1]);
                }
                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;
            $id = DB::table('team3_nebmitra_doctors')
            ->insertGetId([
                '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']
            ]);

            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['chemist_name'],
                'type' => 'nebmitra_chemist',
                'user_id' => $post['user_id'],
                'msl_code' => 'NEBMITRA_CHEMIST_'.$id,
                'phone' => $post['mobile_number']
            ];
            $cont = LambdaRequest::postrequest('contact', 'contact/create', $contactdata, $token[0]->access_token);
            $contactid = $cont->data->item->id;
            $positioncode = $cont->data->item->position;


            DB::table('team3_nebmitra_doctors')
            ->where('id', $id)
            ->update([
                'contact_id' => $contactid,
                'position_code' => $positioncode
                ]);

            Log::debug(print_r(['Add Chemist'], true));
            Log::debug(print_r($contactid, true));
            Log::debug(print_r($post, true));
            Log::debug(print_r($contactdata, true));
            Log::debug(print_r($cont, true));
            Log::debug(print_r(['Add Chemist End'], true));

            return response()->json(['status' => 'success']);
        }

        if($formdata->form_id == '1750326824-c1c033e6-9d6e-4647-b0dd-d3d28e6953e5') {
            
            $dummyformid = '1777352315-9ef1a37a-70b0-4fbc-8b72-1ddd78ce0573';

            $dummyPost = $post;

            if (!empty($dummyPost['doctor_name'])) {
                $dummyPost['contact_id'] = $dummyPost['doctor_name'];
            }

            if (!empty($dummyPost['dummyformid'])) {
                $dummyPost['id'] = $dummyPost['dummyformid'];
            }

            $processedDummyPost = $this->processformdata($dummyformid, $dummyPost, $formdata->user_id, $formdata->partition);
            $finfo = LambdaRequest::postrequest('form', 'formentity/submitform', ['formdata' => $processedDummyPost, 'entity_id' => $dummyformid, 'user_id' => $formdata->user_id, 'partition' => $formdata->partition ]);
            $post['proxy_formid'] = $finfo->data->submission->id;
            Log::debug(print_r(['dummyformlogs'], true));

            Log::debug(print_r(['formdata' => $processedDummyPost], true));
            Log::debug(print_r($finfo, true));


            if($finfo->status != 'success') {
                if($finfo->statusCode == 401) {
                    return response()->json(['status' => 'failure', 'message' => $finfo->data ]);
                }
                return response()->json(['status' => 'failure']);
            }
            
        }

        if($formdata->form_id == '1777713876-e5a33d1a-8d00-4800-9b88-e78815ece1d4') {

            $dummyformid = '1777958143-ac54e629-bc33-4201-9610-742562431581';

            $dummyPost = $post;

            if (!empty($dummyPost['center_name'])) {
                $dummyPost['contact_id'] = $dummyPost['center_name'];
            }

            if (!empty($dummyPost['dummyformid'])) {
                $dummyPost['id'] = $dummyPost['dummyformid'];
            }

            $processedDummyPost = $this->processformdata($dummyformid, $dummyPost, $formdata->user_id, $formdata->partition);
            $finfo = LambdaRequest::postrequest('form', 'formentity/submitform', ['formdata' => $processedDummyPost, 'entity_id' => $dummyformid, 'user_id' => $formdata->user_id, 'partition' => $formdata->partition ]);
            Log::debug(print_r(['formdata' => $processedDummyPost, 'entity_id' => $dummyformid, 'user_id' => $formdata->user_id, 'partition' => $formdata->partition ], true));
            Log::debug(print_r($finfo, true));
            $post['proxy_formid'] = $finfo->data->submission->id;
            Log::debug(print_r(['dummyformlogs'], true));

            Log::debug(print_r(['formdata' => $processedDummyPost], true));
            Log::debug(print_r($finfo, true));


            if($finfo->status != 'success') {
                if($finfo->statusCode == 401) {
                    return response()->json(['status' => 'failure', 'message' => $finfo->data ]);
                }
                return response()->json(['status' => 'failure']);
            }

        }

        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']);
        }

        if($formdata->form_id == '1779187275-848fd8f3-6ea2-4521-9d85-85ec424fa8d5' || $formdata->form_id == '1781237897-1c44a1d5-844c-470f-bc6c-cef8945ad09f') {
            $selectedCategory = $post['select-category'] ?? null;

            $categoryAttributes = [
                'foracort-ciphaler' => 'foracort_ciphaler',
                'duolin-synchrobreathe' => 'duolin_synchrobreathe',
                'foracort-g' => 'foracort_g',
                'pedia' => 'pedia',
                'triple-combination-voltido-trio-indaflo-g' => 'triple_combination_voltido_trio_indaflo_g',
                'ics-laba-seroflo-maxiflo-voltido' => 'ics_laba_seroflo_maxiflo_voltido',
                'competition-dr' => 'competition_dr',
            ];

            $categoryField = $categoryAttributes[$selectedCategory] ?? null;
            $month1Key = $categoryField ? $categoryField . '_month_1' : 'month_1';
            $month2Key = $categoryField ? $categoryField . '_month_2' : 'month_2';
            $month3Key = $categoryField ? $categoryField . '_month_3' : 'month_3';
            $convertedKey = $categoryField ? $categoryField . '_converted' : 'converted';

            $doctorIds = array_unique(array_merge(
                array_keys($post['submission_id'] ?? []),
                array_keys($post[$month1Key] ?? []),
                array_keys($post[$month2Key] ?? []),
                array_keys($post[$month3Key] ?? []),
                array_keys($post[$convertedKey] ?? []),
                array_keys($post['converted'] ?? []),
                array_keys($post['month_1'] ?? []),
                array_keys($post['month_2'] ?? []),
                array_keys($post['month_3'] ?? [])
            ));

            $contactIds = [];
            $ids = [];
            $convertedArr = [];
            $month1 = [];
            $month2 = [];
            $month3 = [];
            $categoryFieldArr = [];

            foreach ($doctorIds as $doctorId) {
                $row = [
                    'submission_id' => $post['submission_id'][$doctorId] ?? '',
                    'converted' => $post[$convertedKey][$doctorId] ?? $post['converted'][$doctorId] ?? '',
                    'month_1' => $post[$month1Key][$doctorId] ?? $post['month_1'][$doctorId] ?? '0',
                    'month_2' => $post[$month2Key][$doctorId] ?? $post['month_2'][$doctorId] ?? '0',
                    'month_3' => $post[$month3Key][$doctorId] ?? $post['month_3'][$doctorId] ?? '0',
                ];

                $hasValue = false;
                foreach (['submission_id', 'converted', 'month_1', 'month_2', 'month_3'] as $field) {
                    if ($row[$field] !== '' && $row[$field] !== null) {
                        $hasValue = true;
                        break;
                    }
                }

                if (!$hasValue) {
                    continue;
                }

                $contactIds[] = $doctorId;
                $ids[] = ($row['submission_id'] === '' || $row['submission_id'] === null)
                    ? null
                    : $row['submission_id'];
                $convertedArr[] = ($row['converted'] === '' || $row['converted'] === null)
                    ? '0'
                    : $row['converted'];
                $month1[] = $row['month_1'];
                $month2[] = $row['month_2'];
                $month3[] = $row['month_3'];

                if ($categoryField) {
                    $categoryFieldArr[] = in_array($row['converted'], ['1', 1, 'Yes'], true) ? 'Yes' : 'No';
                }
            }

            $post['contact_id'] = $contactIds;
            $post['id'] = $ids;
            $post['converted'] = $convertedArr;
            $post[$convertedKey] = $convertedArr;
            $post['month_1'] = $month1;
            $post['month_2'] = $month2;
            $post['month_3'] = $month3;
            $post[$month1Key] = $month1;
            $post[$month2Key] = $month2;
            $post[$month3Key] = $month3;

            if ($categoryField) {
                $post[$categoryField] = $categoryFieldArr;
            }

            unset($post['submission_id']);

            //return response()->json($post);
        }
        
        if ($formdata->form_type == 'enrollment_form') {
            $contacts = [];
            foreach ($post['contact_id'] as $i => $contact_id) {
                $row = [ 'contact_id' => $contact_id ];
                foreach ($post as $key => $value) {
                    if (in_array($key, ['contact_id', 'user_id', 'hierarchy_id'])) { continue; }
                    if (is_array($value)) {
                        $row[$key] = $value[$i] ?? 'No';
                    }
                }
                $contacts[] = $row;
            }
            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') ->first();
            foreach ($contacts as $contact) {
                $contactdata = [
                    'domain'      => $domain,
                    'application' => $application,
                    'user_id'     => $post['user_id'] ?? null,
                    'hierarchy'   => $post['hierarchy_id'] ?? null,
                    'id'          => $contact['contact_id'],
                ];
                foreach ($contact as $key => $value) {
                    if ($key !== 'contact_id') {
                        $contactdata[$key] = $value;
                    }
                }
                // Log::info('CONTACT UPDATE PAYLOAD', $contactdata);
                LambdaRequest::postrequest( 'contact', 'contact/update', $contactdata, $token->access_token );
            }
            return response()->json(['status' => 'success']);
        }

        if ($formdata->form_id == '1775980892-f0346e7e-e9e5-4f85-9924-beb91fcb8fda') {

            $categoryField = 'po5_novel_meeting';

            $selectedContacts = [];
            for ($i = 1; $i <= 20; $i++) {
                if (!empty($post['doctor_name_' . $i])) {
                    $selectedContacts[] = $post['doctor_name_' . $i];
                }
            }

            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')
                ->first();

            $previousEntries = \App\Helpers\Formhelper::getMultiformData(
                $formdata->partition,
                $formdata->form_id,
                $formdata->user_id
            );

            $previousContactIdsWithCategory = [];
            $contactIdToSubmissionId = [];

            if (
                isset($previousEntries->data) &&
                isset($previousEntries->data->submissions) &&
                is_array($previousEntries->data->submissions)
            ) {
                foreach ($previousEntries->data->submissions as $submission) {
                    if (
                        isset($submission->formdata) &&
                        is_object($submission->formdata) &&
                        isset($submission->formdata->contact_id)
                    ) {

                        if (
                            isset($submission->formdata->$categoryField) &&
                            $submission->formdata->$categoryField == 'Yes'
                        ) {

                            // ✅ FIX: handle array contact_id
                            $contactIds = (array) $submission->formdata->contact_id;

                            foreach ($contactIds as $cid) {
                                if (!empty($cid)) {
                                    $previousContactIdsWithCategory[] = $cid;
                                    $contactIdToSubmissionId[$cid] = $submission->id;
                                }
                            }
                        }
                    }
                }
            }

            $deselectedContacts = array_diff($previousContactIdsWithCategory, $selectedContacts);

            $existingSelectedContacts = [];
            $newSelectedContacts = [];

            foreach ($selectedContacts as $contact_id) {
                if (isset($contactIdToSubmissionId[$contact_id])) {
                    $existingSelectedContacts[] = $contact_id;
                } else {
                    $newSelectedContacts[] = $contact_id;
                }
            }

            $sequencedContacts = array_merge(
                array_values($deselectedContacts),
                $existingSelectedContacts,
                $newSelectedContacts
            );

            // ✅ FIX: keep ids aligned
            $ids = [];
            foreach ($sequencedContacts as $contact_id) {
                $ids[] = $contactIdToSubmissionId[$contact_id] ?? null;
            }

            ${$categoryField} = [];
            foreach ($sequencedContacts as $contact_id) {
                if (in_array($contact_id, $deselectedContacts)) {
                    ${$categoryField}[] = 'No';
                } else {
                    ${$categoryField}[] = 'Yes';
                }
            }

            foreach (array_merge($existingSelectedContacts, $newSelectedContacts) as $contact_id) {

                $availability = null;
                for ($i = 1; $i <= 20; $i++) {
                    if (
                        !empty($post['doctor_name_' . $i]) &&
                        $post['doctor_name_' . $i] == $contact_id
                    ) {
                        $availability = $post['breathefree_is_available_' . $i] ?? null;
                        break;
                    }
                }

                $contactdata = [
                    'domain' => $domain,
                    'application' => $application,
                    'user_id' => $post['user_id'],
                    $categoryField => 'Yes',
                    'id' => $contact_id,
                ];

                if (!empty($availability)) {
                    $contactdata['po5_breathefree_is_available'] = $availability;
                }

                LambdaRequest::postrequest(
                    'contact',
                    'contact/update',
                    $contactdata,
                    $token->access_token
                );
            }

            foreach ($deselectedContacts as $contact_id) {

                $availability = null;
                for ($i = 1; $i <= 20; $i++) {
                    if (
                        !empty($post['doctor_name_' . $i]) &&
                        $post['doctor_name_' . $i] == $contact_id
                    ) {
                        $availability = $post['breathefree_is_available_' . $i] ?? null;
                        break;
                    }
                }

                $contactdata = [
                    'domain' => $domain,
                    'application' => $application,
                    'user_id' => $post['user_id'],
                    $categoryField => 'No',
                    'id' => $contact_id,
                ];

                if (!empty($availability)) {
                    $contactdata['po5_breathefree_is_available'] = $availability;
                }

                LambdaRequest::postrequest(
                    'contact',
                    'contact/update',
                    $contactdata,
                    $token->access_token
                );
            }

            $post['contact_id'] = $sequencedContacts;
            $post['id'] = $ids;
            $post[$categoryField] = ${$categoryField};
        }

        // if ($formdata->form_id == '1779187275-848fd8f3-6ea2-4521-9d85-85ec424fa8d5') {

        //     $categoryField = 'po5_ace_meeting';

        //     $selectedContacts = [];
        //     for ($i = 1; $i <= 20; $i++) {
        //         if (!empty($post['doctor_name_' . $i])) {
        //             $selectedContacts[] = $post['doctor_name_' . $i];
        //         }
        //     }

        //     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')
        //         ->first();

        //     $previousEntries = \App\Helpers\Formhelper::getMultiformData(
        //         $formdata->partition,
        //         $formdata->form_id,
        //         $formdata->user_id
        //     );

        //     $previousContactIdsWithCategory = [];
        //     $contactIdToSubmissionId = [];

        //     if (
        //         isset($previousEntries->data) &&
        //         isset($previousEntries->data->submissions) &&
        //         is_array($previousEntries->data->submissions)
        //     ) {
        //         foreach ($previousEntries->data->submissions as $submission) {
        //             if (
        //                 isset($submission->formdata) &&
        //                 is_object($submission->formdata) &&
        //                 isset($submission->formdata->contact_id)
        //             ) {

        //                 if (
        //                     isset($submission->formdata->$categoryField) &&
        //                     $submission->formdata->$categoryField == 'Yes'
        //                 ) {

        //                     // ✅ FIX: handle array contact_id
        //                     $contactIds = (array) $submission->formdata->contact_id;

        //                     foreach ($contactIds as $cid) {
        //                         if (!empty($cid)) {
        //                             $previousContactIdsWithCategory[] = $cid;
        //                             $contactIdToSubmissionId[$cid] = $submission->id;
        //                         }
        //                     }
        //                 }
        //             }
        //         }
        //     }

        //     $deselectedContacts = array_diff($previousContactIdsWithCategory, $selectedContacts);

        //     $existingSelectedContacts = [];
        //     $newSelectedContacts = [];

        //     foreach ($selectedContacts as $contact_id) {
        //         if (isset($contactIdToSubmissionId[$contact_id])) {
        //             $existingSelectedContacts[] = $contact_id;
        //         } else {
        //             $newSelectedContacts[] = $contact_id;
        //         }
        //     }

        //     $sequencedContacts = array_merge(
        //         array_values($deselectedContacts),
        //         $existingSelectedContacts,
        //         $newSelectedContacts
        //     );

        //     // ✅ FIX: keep ids aligned
        //     $ids = [];
        //     foreach ($sequencedContacts as $contact_id) {
        //         $ids[] = $contactIdToSubmissionId[$contact_id] ?? null;
        //     }

        //     ${$categoryField} = [];
        //     foreach ($sequencedContacts as $contact_id) {
        //         if (in_array($contact_id, $deselectedContacts)) {
        //             ${$categoryField}[] = 'No';
        //         } else {
        //             ${$categoryField}[] = 'Yes';
        //         }
        //     }

        //     foreach (array_merge($existingSelectedContacts, $newSelectedContacts) as $contact_id) {

        //         $availability = null;
        //         for ($i = 1; $i <= 20; $i++) {
        //             if (
        //                 !empty($post['doctor_name_' . $i]) &&
        //                 $post['doctor_name_' . $i] == $contact_id
        //             ) {
        //                 $availability = $post['breathefree_is_available_' . $i] ?? null;
        //                 break;
        //             }
        //         }

        //         $contactdata = [
        //             'domain' => $domain,
        //             'application' => $application,
        //             'user_id' => $post['user_id'],
        //             $categoryField => 'Yes',
        //             'id' => $contact_id,
        //         ];

        //         if (!empty($availability)) {
        //             $contactdata['po5_breathefree_is_available'] = $availability;
        //         }

        //         LambdaRequest::postrequest(
        //             'contact',
        //             'contact/update',
        //             $contactdata,
        //             $token->access_token
        //         );
        //     }

        //     foreach ($deselectedContacts as $contact_id) {

        //         $availability = null;
        //         for ($i = 1; $i <= 20; $i++) {
        //             if (
        //                 !empty($post['doctor_name_' . $i]) &&
        //                 $post['doctor_name_' . $i] == $contact_id
        //             ) {
        //                 $availability = $post['breathefree_is_available_' . $i] ?? null;
        //                 break;
        //             }
        //         }

        //         $contactdata = [
        //             'domain' => $domain,
        //             'application' => $application,
        //             'user_id' => $post['user_id'],
        //             $categoryField => 'No',
        //             'id' => $contact_id,
        //         ];

        //         if (!empty($availability)) {
        //             $contactdata['po5_breathefree_is_available'] = $availability;
        //         }

        //         LambdaRequest::postrequest(
        //             'contact',
        //             'contact/update',
        //             $contactdata,
        //             $token->access_token
        //         );
        //     }

        //     $post['contact_id'] = $sequencedContacts;
        //     $post['id'] = $ids;
        //     $post[$categoryField] = ${$categoryField};
        // }

        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', 'galact_saturday' => isset($post['galact_saturday'][$i])?'Yes':'No', 'celol_d3_thursday' => isset($post['celol_d3_thursday'][$i])?'Yes':'No' ];
                // , 'ferium_xt_thursday' => isset($post['ferium_xt_thursday'][$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'],
                    'celol_d3_thursday' => $contact['celol_d3_thursday'],
                    'id' => $contact['contact_id'],
                ];
                $cont = LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token[0]->access_token);
            }
            return response()->json(['status' => 'success']);
        }

        if($formdata->form_id == '1770113055-b65a4310-83e0-49ad-ad98-6a226beb2bc3') {
            $contacts = [];
            foreach($post['doctor_name'] as $i => $contact_id) {
                $contacts[] = ['contact_id' => $contact_id, 'glycohale_power_punch' => 'Yes', 'dr_potential_for_glycohale' => $post['dr_potential_for_glycohale_in_units'][$i] ];
            }
            // return response()->json(['status' => 'failure', 'history' => $contacts, 'post' => $post]);
            
            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'],
                    'glycohale_power_punch' => $contact['glycohale_power_punch'],
                    'dr_potential_for_glycohale' => $contact['dr_potential_for_glycohale'],
                    'id' => $contact['contact_id'],
                ];
                $cont = LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token[0]->access_token);
            }
            // return response()->json(['status' => 'success']);
            // return response()->json(['status' => 'success', 'contacts' => $contacts]);

        }

        //["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' ];
            }
            Log::debug(print_r(['contact_id'], true));
            Log::debug(print_r($contacts, true));
            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);
            }
            Log::debug(print_r(['contactdata'], true));
            Log::debug(print_r($contactdata, true));
            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 == '1755612216-4cfb5429-9401-40b1-9374-37d65fecbc0c') {
            $contacts = [];
            foreach($post['contact_id'] as $i => $contact_id) {
                $contacts[] = ['contact_id' => $contact_id, 'nebulizer_distribution_con' => isset($post['nebulizer_distribution_con'][$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'],
                    'nebulizer_distribution_con' => $contact['nebulizer_distribution_con'],
                    'id' => $contact['contact_id'],
                ];
                $cont = LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token[0]->access_token);
            }
            return response()->json(['status' => 'success']);
        }

        if($formdata->form_id == '1768816889-343321b6-6dde-4e9a-845e-645a47932700') {
            $contacts = [];
            foreach($post['contact_id'] as $i => $contact_id) {
                $contacts[] = ['contact_id' => $contact_id, 'emanzen_thursday' => isset($post['emanzen_thursday'][$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'],
                    'emanzen_thursday' => $contact['emanzen_thursday'],
                    'id' => $contact['contact_id'],
                ];
                $cont = LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token[0]->access_token);
            }
            return response()->json(['status' => 'success']);
        }

        if($formdata->form_id == '1772548223-15a3e319-3ae0-48ba-a553-c640b99e9b62') {
            $contacts = [];
            foreach($post['contact_id'] as $i => $contact_id) {
                $contacts[] = ['contact_id' => $contact_id, 'fitjoint_knee_adaption' => isset($post['fitjoint_knee_adaption'][$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'],
                    'fitjoint_knee_adaption' => $contact['fitjoint_knee_adaption'],
                    'id' => $contact['contact_id'],
                ];
                $cont = LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token[0]->access_token);
            }
            return response()->json(['status' => 'success']);
        }

        if($formdata->form_id == '1773740254-07da2335-4ff7-42e4-8937-b43dfb218a5a') {

            Log::debug('STEP 1: Initial POST');
            Log::debug(print_r($post, true));

            $contacts = [];

            foreach($post['contact_id'] as $i => $cid) {

                $isChecked = isset($post['orofer_tuesday_enrol'][$i]);

                // ✅ Build structured array like contact update
                $contacts[] = [
                    'contact_id' => $cid,
                    'orofer_tuesday_enrol' => $isChecked ? 'Yes' : 'No'
                ];

                Log::debug("Index $i => Contact: $cid => " . ($isChecked ? 'Yes' : 'No'));
            }

            // ✅ IMPORTANT: send full structured data
            $post['contacts'] = $contacts;

            // ❌ Optional: remove old arrays if not needed
            // unset($post['contact_id']);
            // unset($post['orofer_tuesday_enrol']);

            Log::debug('STEP 2: Final POST for submission');
            Log::debug(print_r($post, true));

            // ========================
            // CONTACT UPDATE (same logic reused)
            // ========================
            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')
                ->first();

            foreach($contacts as $contact) {

                $contactdata = [
                    'domain' => $domain,
                    'application' => $application,
                    'user_id' => $post['user_id'],
                    'orofer_tuesday_enrol' => $contact['orofer_tuesday_enrol'],
                    'id' => $contact['contact_id'],
                ];

                Log::debug('Updating Contact');
                Log::debug(print_r($contactdata, true));

                LambdaRequest::postrequest(
                    'contact',
                    'contact/update',
                    $contactdata,
                    $token->access_token
                );
            }

            Log::debug('STEP 3: POST');
            Log::debug(print_r($post, true));
        }

        if($formdata->form_id == '1768820353-9e26cf7b-73c0-4d34-a2f3-5ca559afa560') {
            $contacts = [];
            foreach($post['contact_id'] as $i => $contact_id) {
                $contacts[] = ['contact_id' => $contact_id, 'galact_thursday' => isset($post['galact_thursday'][$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'],
                    'galact_thursday' => $contact['galact_thursday'],
                    'id' => $contact['contact_id'],
                ];
                $cont = LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token[0]->access_token);
            }
            return response()->json(['status' => 'success']);
        }

        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 == '1764312102-2f7e9477-fa29-4040-b5da-b15df9e06b78') {
            Log::debug(print_r('newrcpa', true));
            Log::debug(print_r($post, true));

            // Build brand → Cipla qty / value maps from original data
            $brandQtyMap   = [];
            $brandValueMap = [];

            $a = $post['qty_cipla_brand'];
            $r = [];
            $prev = null;
            foreach ($a as $v) {
                if ($prev !== null && $v == $prev) {   // use == instead of ===
                    $r[] = $v;
                }
                $prev = $v;
            }
            $post['qty_cipla_brand'] = $r;

            $a = $post['value_cipla_brand'];
            $r = [];
            $prev = null;
            foreach ($a as $v) {
                if ($prev !== null && $v == $prev) {   // use == instead of ===
                    $r[] = $v;
                }
                $prev = $v;
            }
            $post['value_cipla_brand'] = $r;

            // Build maps based on brand_name aligned with qty_cipla_brand & value_cipla_brand
            if (!empty($post['brand_name'])) {
                foreach ($post['brand_name'] as $i => $brand) {

                    // Map qty: first non-zero, non-empty occurrence per brand
                    if (!isset($brandQtyMap[$brand]) && isset($post['qty_cipla_brand'][$i])) {
                        $q = $post['qty_cipla_brand'][$i];
                        if ($q !== '' && $q !== null && (float)$q != 0) {
                            $brandQtyMap[$brand] = $q;
                        }
                    }

                    // Map value: first non-zero, non-empty occurrence per brand
                    if (!isset($brandValueMap[$brand]) && isset($post['value_cipla_brand'][$i])) {
                        $v = $post['value_cipla_brand'][$i];
                        if ($v !== '' && $v !== null && (float)$v != 0) {
                            $brandValueMap[$brand] = $v;
                        }
                    }
                }
            }

            // Now rebuild arrays keeping only rows where competitor qty/net_value > 0,
            // and putting Cipla qty/value only once per brand.

            $brand_name              = [];
            $company_name            = [];
            $qty_cipla_brand         = [];
            $value_cipla_brand       = [];
            $competitor_brand        = [];
            $qty_of_competitor_brand = [];
            $net_value               = [];

            $lastBrand = null;

            foreach ($post['brand_name'] as $i => $brand) {

                // Keep only rows where competitor side has some business
                if (
                    (isset($post['qty_of_competitor_brand'][$i]) && $post['qty_of_competitor_brand'][$i] > 0) ||
                    (isset($post['net_value'][$i]) && $post['net_value'][$i] > 0)
                ) {
                    // Always push competitor-side details
                    $brand_name[]              = $brand;
                    $company_name[]            = $post['company_name'][$i] ?? '';
                    $competitor_brand[]        = $post['competitor_brand'][$i] ?? '';
                    $qty_of_competitor_brand[] = $post['qty_of_competitor_brand'][$i] ?? 0;
                    $net_value[]               = $post['net_value'][$i] ?? 0;

                    // Cipla side: only once per brand
                    if ($lastBrand !== $brand) {
                        //$++;
                        $qty_cipla_brand[]   = $brandQtyMap[$brand]   ?? 0;
                        $value_cipla_brand[] = $brandValueMap[$brand] ?? 0;
                        $lastBrand           = $brand;
                    } else {
                        // For subsequent rows of the same brand, no duplicate Cipla qty/value
                        $qty_cipla_brand[]   = 0;
                        $value_cipla_brand[] = 0;
                    }
                }
            }

            // Overwrite $post with the cleaned arrays
            $post['brand_name']              = $brand_name;
            $post['company_name']            = $company_name;
            $post['qty_cipla_brand']         = $qty_cipla_brand;
            $post['value_cipla_brand']       = $value_cipla_brand;
            $post['competitor_brand']        = $competitor_brand;
            $post['qty_of_competitor_brand'] = $qty_of_competitor_brand;
            $post['net_value']               = $net_value;

            // Clean up extra fields coming from the form
            unset($post['brand_brand_name']);
            unset($post['brand_qty_cipla_brand']); // if present

            // Keep speciality as is (line is actually redundant but harmless)
            $post['speciality'] = $post['speciality'];

            Log::debug(print_r('afterloop', true));
            Log::debug(print_r($post, true));
        }

        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 == '1761883527-dc4bc1e1-4333-4db9-b2da-e3480d2da9cc') {
        
            Log::info('CATEGORY e3480d2da9cc:', [$post['category']]);
            
            $attributes = [
                'SB Dr Tagging' => 'po5_synchrobreathe',
                'Ciphaler Dr Tagging' => 'po5_ciphaler'
            ];

            $category = $post['category'];

            $categoryField = $attributes[$category] ?? null;
            if (!$categoryField) {
                return response()->json(['status' => 'error', 'message' => 'Invalid category'], 400);
            }

            $selectedContacts = [];
            for ($i = 1; $i <= 20; $i++) {
                if (!empty($post['doctor_' . $i])) {
                    $selectedContacts[] = $post['doctor_' . $i];
                }
            }

            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')
                ->first();

            // Get all previous submissions for this user/form/partition *once*
            $previousEntries = \App\Helpers\Formhelper::getMultiformData($formdata->partition, $formdata->form_id, $formdata->user_id);
            //echo '
'; print_r($previousEntries); exit;
            // Gather list of previous contact IDs where this categoryField was Yes, and keep mapping to their submission IDs
            $previousContactIdsWithCategory = [];
            $contactIdToSubmissionId = [];
            if (
                isset($previousEntries->data) 
                && isset($previousEntries->data->submissions) 
                && is_array($previousEntries->data->submissions)
            ) {
                foreach ($previousEntries->data->submissions as $submission) {
                    if (
                        isset($submission->formdata) && is_object($submission->formdata) &&
                        isset($submission->formdata->contact_id) && !empty($submission->formdata->contact_id)
                    ) {
                        // Only interested in those for this category for "Yes"
                        if ($submission->formdata->category == $category) {
                            $previousContactIdsWithCategory[] = $submission->formdata->contact_id;
                            $contactIdToSubmissionId[$submission->formdata->contact_id] = $submission->id;
                        }
                    }
                }
            }

            // Sequence: Put deselected contacts first (those which were previously Yes but not in current selection)
            $deselectedContacts = array_diff($previousContactIdsWithCategory, $selectedContacts);

            // Then put existing still-selected contacts (selected & previously "Yes")
            $existingSelectedContacts = [];
            $newSelectedContacts = [];
            foreach ($selectedContacts as $contact_id) {
                if (isset($contactIdToSubmissionId[$contact_id])) {
                    $existingSelectedContacts[] = $contact_id;
                } else {
                    $newSelectedContacts[] = $contact_id;
                }
            }

            // Final sequence: [deselectedContacts ("No")], [existingSelectedContacts ("Yes")], [newSelectedContacts ("Yes")]
            $sequencedContacts = array_merge(array_values($deselectedContacts), $existingSelectedContacts, $newSelectedContacts);

            // Build ids array to match $sequencedContacts:
            $ids = [];
            foreach ($sequencedContacts as $contact_id) {
                if (isset($contactIdToSubmissionId[$contact_id])) {
                    $ids[] = $contactIdToSubmissionId[$contact_id];
                }
                // else {
                //     $ids[] = null;
                // }
            }

            // Build categoryField values to match sequenced order
            ${$categoryField} = [];
            foreach ($sequencedContacts as $contact_id) {
                if (in_array($contact_id, $deselectedContacts)) {
                    ${$categoryField}[] = 'No';
                } else {
                    ${$categoryField}[] = 'Yes';
                }
            }

            // Update "Yes" for selected contacts (existing & new)
            foreach (array_merge($existingSelectedContacts, $newSelectedContacts) as $contact_id) {

                // get breathefree value for this contact
                $availability = null;
                for ($i = 1; $i <= 20; $i++) {
                    if (
                        !empty($post['doctor_' . $i]) &&
                        $post['doctor_' . $i] == $contact_id
                    ) {
                        $availability = $post['breathefree_is_available_' . $i] ?? null;
                        break;
                    }
                }

                $contactdata = [
                    'domain' => $domain,
                    'application' => $application,
                    'user_id' => $post['user_id'],
                    $categoryField => 'Yes',
                    'id' => $contact_id,
                ];

                // ✅ add only if present
                if (!empty($availability)) {
                    $contactdata['po5_breathefree_is_available'] = $availability;
                }

                LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token->access_token);
            }

            // Update "No" for deselectedContacts
            // foreach (array_merge($existingSelectedContacts, $newSelectedContacts) as $contact_id) {
            foreach ($deselectedContacts as $contact_id){
                // get breathefree value for this contact
                $availability = null;
                for ($i = 1; $i <= 20; $i++) {
                    if (
                        !empty($post['doctor_' . $i]) &&
                        $post['doctor_' . $i] == $contact_id
                    ) {
                        $availability = $post['breathefree_is_available_' . $i] ?? null;
                        break;
                    }
                }

                $contactdata = [
                    'domain' => $domain,
                    'application' => $application,
                    'user_id' => $post['user_id'],
                    $categoryField => 'No',
                    'id' => $contact_id,
                ];

                // ✅ add only if present
                if (!empty($availability)) {
                    $contactdata['po5_breathefree_is_available'] = $availability;
                }

                LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token->access_token);
            }

            
            // Assign arrays to $post with matching sequence: contact_id, id, $categoryField (deselected first, then kept/new)
            $post['contact_id'] = $sequencedContacts;
            $post['id'] = $ids;
            $post[$categoryField] = ${$categoryField};
            // echo '
'; print_r($post); exit;
            //echo "
"; print_r($post); print_r($contacts); exit;
            //return response()->json(['status' => 'success', 'post' => $post, 'contactIdToSubmissionId' => $contactIdToSubmissionId, 'deselectedContacts' => $deselectedContacts]);
        }

        if ($formdata->form_id == '1762175787-4051d820-93c7-4295-8100-019574d9ca3e') {
             Log::debug(print_r('test', true));
            
            $attributes = [
                'DPI Competition Dr' => 'dpi_competition_dr',
                'MDI Competition Dr' => 'mdi_competition_dr',
                'Respi Phy Upgradation Dr' => 'respi_phy_upgradation_dr',
                'LABA/LAMA Competition Dr' => 'labalama_competition_dr',
            ];

            $category = $post['category'];
            Log::debug(print_r('formdata', true));

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

            $categoryField = $attributes[$category] ?? null;
            if (!$categoryField) {
                return response()->json(['status' => 'error', 'message' => 'Invalid category'], 400);
            }

            $selectedContacts = [];
            for ($i = 1; $i <= 5; $i++) {
                if (!empty($post['doctor_' . $i])) {
                    $selectedContacts[] = $post['doctor_' . $i];
                }
            }

            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')
                ->first();

            // Get all previous submissions for this user/form/partition *once*
            $previousEntries = \App\Helpers\Formhelper::getMultiformData($formdata->partition, $formdata->form_id, $formdata->user_id);
            //echo '
'; print_r($previousEntries); exit;
            // Gather list of previous contact IDs where this categoryField was Yes, and keep mapping to their submission IDs
            $previousContactIdsWithCategory = [];
            $contactIdToSubmissionId = [];
            if (
                isset($previousEntries->data) 
                && isset($previousEntries->data->submissions) 
                && is_array($previousEntries->data->submissions)
            ) {
                foreach ($previousEntries->data->submissions as $submission) {
                    if (
                        isset($submission->formdata) && is_object($submission->formdata) &&
                        isset($submission->formdata->contact_id) && !empty($submission->formdata->contact_id)
                    ) {
                        // Only interested in those for this category for "Yes"
                        if ($submission->formdata->category == $category) {
                            $previousContactIdsWithCategory[] = $submission->formdata->contact_id;
                            $contactIdToSubmissionId[$submission->formdata->contact_id] = $submission->id;
                        }
                    }
                }
            }

            // Sequence: Put deselected contacts first (those which were previously Yes but not in current selection)
            $deselectedContacts = array_diff($previousContactIdsWithCategory, $selectedContacts);

            // Then put existing still-selected contacts (selected & previously "Yes")
            $existingSelectedContacts = [];
            $newSelectedContacts = [];
            foreach ($selectedContacts as $contact_id) {
                if (isset($contactIdToSubmissionId[$contact_id])) {
                    $existingSelectedContacts[] = $contact_id;
                } else {
                    $newSelectedContacts[] = $contact_id;
                }
            }

            // Final sequence: [deselectedContacts ("No")], [existingSelectedContacts ("Yes")], [newSelectedContacts ("Yes")]
            $sequencedContacts = array_merge(array_values($deselectedContacts), $existingSelectedContacts, $newSelectedContacts);

            // Build ids array to match $sequencedContacts:
            $ids = [];
            foreach ($sequencedContacts as $contact_id) {
                if (isset($contactIdToSubmissionId[$contact_id])) {
                    $ids[] = $contactIdToSubmissionId[$contact_id];
                }
                // else {
                //     $ids[] = null;
                // }
            }

            // Build categoryField values to match sequenced order
            ${$categoryField} = [];
            foreach ($sequencedContacts as $contact_id) {
                if (in_array($contact_id, $deselectedContacts)) {
                    ${$categoryField}[] = 'No';
                } else {
                    ${$categoryField}[] = 'Yes';
                }
            }

            // Update "Yes" for selected contacts (existing & new)
            foreach (array_merge($existingSelectedContacts, $newSelectedContacts) as $contact_id) {
                $contactdata = [
                    'domain' => $domain,
                    'application' => $application,
                    'user_id' => $post['user_id'],
                    $categoryField => 'Yes',
                    'id' => $contact_id,
                ];
                LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token->access_token);
                
            }

            
            // Update "No" for deselectedContacts
            foreach ($deselectedContacts as $contact_id) {

                Log::debug(print_r('contact_id', true));
                Log::debug(print_r($contact_id, true));

                Log::debug(print_r('categoryField', true));
                Log::debug(print_r($categoryField, true));

                $contactdata = [
                    'domain' => $domain,
                    'application' => $application,
                    'user_id' => $post['user_id'],
                    $categoryField => 'No',
                    'id' => $contact_id,
                ];
                LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token->access_token);

                // Also update the formdata submission (if found)
                if (isset($contactIdToSubmissionId[$contact_id])) {
                    $submissionId = $contactIdToSubmissionId[$contact_id];
                    // Try to get the previous formdata for the submission (look back in previousEntries)
                    $prevFormdata = null;
                    foreach ($previousEntries->data->submissions as $submission) {
                        if ($submission->id == $submissionId) {
                            $prevFormdata = (array) $submission->formdata;
                            break;
                        }
                    }
                    if ($prevFormdata !== null) {
                        $prevFormdata[$categoryField] = 'No';
                        LambdaRequest::postrequest('form', 'formentity/updatesubmission', [
                            'submission_id' => $submissionId,
                            'formdata' => $prevFormdata,
                        ], $token->access_token);
                    }
                }
            }

            
            // Assign arrays to $post with matching sequence: contact_id, id, $categoryField (deselected first, then kept/new)
            $post['contact_id'] = $sequencedContacts;
            $post['id'] = $ids;
            $post[$categoryField] = ${$categoryField};
            //echo '
'; print_r($post); exit;
            //echo "
"; print_r($post); print_r($contacts); exit;
            //return response()->json(['status' => 'success', 'post' => $post, 'contactIdToSubmissionId' => $contactIdToSubmissionId, 'deselectedContacts' => $deselectedContacts]);
        }



        // if($formdata->form_id == '1761818463-f0735d63-1912-4cb0-a181-6dc55751c375') {
        //     $contacts = [];
        //     foreach($post['contact_id'] as $i => $contact_id) {
        //         // $contacts[] = ['contact_id' => $contact_id, 'engagement_wishlist' => isset($post['engagement_wishlist'][$i])?'Yes':'No' ];
        //         if (!empty($post['engagement_wishlist'][$i])) {
        //             $contacts[] = [
        //                 'contact_id' => $contact_id,
        //                 'engagement_wishlist' => 'Yes'
        //             ];
        //         }
        //     }

        //     Log::debug('Contact List');
        //     Log::debug(print_r($contacts, true));

        //     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'],
        //             'engagement_wishlist' => $contact['engagement_wishlist'],
        //             'id' => $contact['contact_id'],
        //         ];
        //         $cont = LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token[0]->access_token);
        //     }
        //     // return response()->json(['status' => 'success']);
        // }

        
        if($formdata->form_id == '1761824966-7f47b36c-ad44-4544-a924-68ece3c8800f' || $formdata->form_id == '1761818463-f0735d63-1912-4cb0-a181-6dc55751c375') {
            $previousEntries = \App\Helpers\Formhelper::getMultiformData($formdata->partition, $formdata->form_id, $formdata->user_id);
            $contIdToSubmissionId = [];
            if (isset($previousEntries->data) && isset($previousEntries->data->submissions) && is_array($previousEntries->data->submissions)) {
                foreach ($previousEntries->data->submissions as $submission) {
                    if (isset($submission->formdata->cont_id) && isset($submission->id)) {
                        $contIdToSubmissionId[$submission->formdata->cont_id] = $submission->id;
                    }
                }
            }
            
            $contacts = [];
            foreach($post['contact_id'] as $i => $contact_id) {
                if (isset($post['engagement_wishlist'][$i]) && $post['engagement_wishlist'][$i] === 'Yes') {
                    $submission_id = isset($contIdToSubmissionId[$contact_id]) ? $contIdToSubmissionId[$contact_id] : null;
                    $contacts[] = ['contact_id' => $contact_id, 'engagement_wishlist' => 'Yes', 'submission_id' => $submission_id];
                }
            }
            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'],
                    'engagement_wishlist' => $contact['engagement_wishlist'],
                    'id' => $contact['contact_id'],
                ];
                $cont = LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token[0]->access_token);
            }

            // For each $contIdToSubmissionId where engagement_wishlist is not yes, update engagement_wishlist as no
            // And for all such, add to the $post arrays after completed above
            $existingContactIdsWithYes = array_column($contacts, 'contact_id');
            $noContactsToAddToPost = [];
            foreach ($contIdToSubmissionId as $contact_id => $submission_id) {
                // Check if this contact is in $contacts with engagement_wishlist 'Yes'
                $found = false;
                foreach ($contacts as $contact) {
                    if ($contact['contact_id'] == $contact_id && $contact['engagement_wishlist'] === 'Yes') {
                        $found = true;
                        break;
                    }
                }
                if (!$found) {
                    // Not found → engagement_wishlist should be 'No'
                    $contactdata = [
                        'domain' => $domain,
                        'application' => $application,
                        'user_id' => $post['user_id'],
                        'engagement_wishlist' => 'No',
                        'id' => $contact_id,
                    ];
                    $cont = LambdaRequest::postrequest('contact', 'contact/update', $contactdata, $token[0]->access_token);

                    // Also add this contact to be appended to the $post arrays
                    $noContactsToAddToPost[] = [
                        'contact_id' => $contact_id,
                        'engagement_wishlist' => 'No',
                        'submission_id' => $submission_id
                    ];
                }
            }

            // We need to order contacts so that those whose contact_id is in previousEntries (i.e., have submission_id) come first
            $existing = [];
            $new = [];

            foreach ($contacts as $contact) {
                if (!empty($contact['submission_id'])) {
                    $existing[] = $contact;
                } else {
                    $new[] = $contact;
                }
            }
            // Add the NO contacts to the beginning, because they have submission_id
            foreach($noContactsToAddToPost as $noContact) {
                $existing[] = $noContact;
            }
            // Merge, with existing first, then new
            $ordered = array_merge($existing, $new);
            $post['contact_id'] = [];
            $post['engagement_wishlist'] = [];
            $post['id'] = [];

            foreach ($ordered as $i => $contact) {
                $post['contact_id'][$i] = $contact['contact_id'];
                $post['engagement_wishlist'][$i] = $contact['engagement_wishlist'];
                $post['id'][$i] = $contact['submission_id'];
            }
            //echo "
"; print_r($post); print_r($contacts); exit;
            // 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 == '1768891186-e0ac4546-6cf4-4665-aac9-066bdb5f25ea') {
            $contacts = [];
            foreach($post['contact_id'] as $i => $contact_id) {
                if (isset($post['foracort_g_ciphaler'][$i])) {
                    $contacts[] = $contact_id;
                    //$ardc_bf_competition[] = $post['ardc_bf_competition_dr_list_check'][$i];
                }
            }
            $post['contact_id'] = $contacts;
            Log::debug(print_r(['foracort_g_ciphaler test data'], true));
            Log::debug(print_r($post, true));
            // 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 ($formdata->form_id == '1757310587-2f18dc06-9107-4553-a0cb-11ac90b09dda') {
            $submitData = [
                'form_id' => '1757934154-bdf4d06a-e633-433a-ad84-682761924bfc',
                'user_id' => $post['user_id'] ?? '',
                'total_eas_hcps_april_sep_for_cresar_grp' => $post['total_eas_hcps_april_sep_for_cresar_grp'] ?? '',
                'total_eas_hcps_april_sep_for_empacip_grp' => $post['total_eas_hcps_april_sep_for_empacip_grp'] ?? '',
                'eas_hcps_met_mtd_sep25_for_cresar_grp' => $post['eas_hcps_met_mtd_sep25_for_cresar_grp'] ?? '',
                'eas_hcps_met_mtd_sep25_for_empacip_grp' => $post['eas_hcps_met_mtd_sep25_for_empacip_grp'] ?? '',
                'eas_hcps_met_twice_mtd_sep25_for_cresar_grp' => $post['eas_hcps_met_twice_mtd_sep25_for_cresar_grp'] ?? '',
                'eas_hcps_met_twice_mtd_sep25_for_empacip_grp' => $post['eas_hcps_met_twice_mtd_sep25_for_empacip_grp'] ?? '',
            ];
            if (!empty($post['eas_hcp_id'])) {
                $submitData['id'] = $post['eas_hcp_id'];
            }
            LambdaRequest::postrequest('form', 'formentity/submitform', [
                'formdata' => $submitData,
                'entity_id' => $submitData['form_id'],
                'user_id' => $submitData['user_id'],
                'partition' => $formdata->partition ?? ''
            ]);
        }


        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();
        

        if($post['form_id'] == '1718178830-d871301e-312b-4a60-nebmitra-15afa4ce6163'){
                Log::info("view nebmitra form" . print_r($post, true));
		        
                $response = LambdaRequest::getrequest('form', 'formentity/getsubmissiondetails', 
                    ['form_id' => $post['form_id'], 'partition' => 'rapport-team3', 'id' => $post['id']]
                );

                Log::info("response of gsd" . print_r($response, true));


                $sub_status = '';
                if($post['action'] == 'approve'){
                    $sub_status = 'Approved';
                }elseif($post['action'] == 'reject'){
                    $sub_status = 'Rejected';
                }

                $data = (array) $response->data->submission->formdata;
                $data['submission_status'] = $sub_status;
                $data['id'] = $post['id'];
                $data['reason'] = $post['reason'];

                $finfo = LambdaRequest::postrequest( 'form', 'formentity/submitform', 
                    [ 
                        'formdata' => $data, 
                        'entity_id' => $post['form_id'],
                        'user_id' => $data['user_id'],
                        'partition' => 'rapport-team3'
                    ] 
                );
                Log::info("Lambda response: " . print_r($finfo, true));
                return response()->json($finfo);
        }

        // if($post['form_id'] == '1750914801-153443b9-94d0-4dcb-b3f3-4fa11588a0a9'){
        //         Log::info("view neblogistic form" . print_r($post, true));
        //         // return response()->json('success');

        //         if($post['countofneb'] <= 5){
        //             $sub_status = '';
        //             if($post['action'] == 'approve'){
        //                 $sub_status = 'L1 Approved';
        //             }elseif($post['action'] == 'reject'){
        //                 $sub_status = 'Rejected';
        //             }

        //             $data['status'] = $sub_status;
        //             $data['id'] = $post['id'];
        //             $data['user_id'] = $post['user_id'];
        //             $finfo = LambdaRequest::postrequest( 'form', 'formentity/submitform', 
        //                 [ 
        //                     'formdata' => $data, 
        //                     'entity_id' => $post['form_id'],
        //                     'user_id' => $data['user_id'],
        //                     'partition' => 'rapport-team3'
        //                 ] 
        //             );

        //             if ($sub_status !== '') {
        //                 $oldNeb = DB::table('neblogistic')->where('submission_id', $post['id'])->first();
        //                 $oldNebArray = $oldNeb ? json_decode(json_encode($oldNeb), true) : null;
        //                 $statusUpdate = ['status' => $sub_status];
        //                 DB::table('neblogistic')
        //                     ->where('submission_id', $post['id'])
        //                     ->update($statusUpdate);
        //                 if ($oldNebArray) {
        //                     NeblogisticAuditService::logUpdate(
        //                         $oldNeb->id,
        //                         $oldNebArray,
        //                         $statusUpdate,
        //                         null,
        //                         $request
        //                     );
        //                 }
        //             }
        //             Log::info("Lambda response: " . print_r($finfo, true));
        //         }
        // }

        $actorUserId = $this->resolveActingApproverUserId($post, $formdata);
        if (!$this->isValidActingApproverUserId($actorUserId)) {
            return response()->json([
                'status' => 'error',
                'message' => 'A valid approver user_id is required.',
            ], 400);
        }

        $partition = !empty($post['partition'])
            ? $post['partition']
            : ($formdata ? $formdata->partition : '');
        if (empty($partition)) {
            return response()->json([
                'status' => 'error',
                'message' => 'Partition is required.',
            ], 400);
        }

        $payload = [
            'submission_id' => $post['submission_id'] ?? $post['id'],
            'form_id' => $post['form_id'],
            'action' => $post['action'],
            'user_id' => $actorUserId,
            'partition' => $partition,
            'reason' => $post['reason'] ?? '',
            'form_name' => $post['form_name'] ?? '',
        ];
        $accessToken = $this->getServiceAccessTokenForPartition($partition);
        $finfo = LambdaRequest::postrequest(
            'form',
            'formentity/approvereject',
            $payload,
            $accessToken ?: ''
        );

        Log::debug("---------------- FINFO -----------------");
        Log::debug(print_r($finfo, true));
        Log::debug("---------------- POST -----------------");
        Log::debug(print_r($post, true));
        Log::debug(print_r($formdata, true));

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

    public function approverejectmultiple(Request $request) {
        $post = $request->all();
        $formdata = $request->session()->get('formdata');
        $actorUserId = $this->resolveActingApproverUserId($post, $formdata);
        if (!$this->isValidActingApproverUserId($actorUserId)) {
            return response()->json([
                'status' => 'error',
                'message' => 'A valid approver user_id is required.',
            ], 400);
        }

        $partition = !empty($post['partition'])
            ? $post['partition']
            : ($formdata ? $formdata->partition : '');
        if (empty($partition)) {
            return response()->json([
                'status' => 'error',
                'message' => 'Partition is required.',
            ], 400);
        }

        $accessToken = $this->getServiceAccessTokenForPartition($partition);
        foreach ($post['ids'] as $id) {
            LambdaRequest::postrequest(
                'form',
                'formentity/approvereject',
                [
                    'submission_id' => $id,
                    'form_id' => $post['form_id'],
                    'action' => $post['action'],
                    'user_id' => $actorUserId,
                    'partition' => $partition,
                    'reason' => $post['reason'] ?? '',
                    'form_name' => $post['form_name'] ?? '',
                ],
                $accessToken ?: (Auth::user()->access_token ?? '')
            );
        }
        return response()->json($post);
    }

    protected function isValidActingApproverUserId($userId): bool
    {
        if ($userId === null || $userId === '') {
            return false;
        }
        $userId = (string) $userId;
        if ($userId === 'vacant' || str_starts_with($userId, 'vacant-')) {
            return false;
        }
        return true;
    }

    protected function resolveActingApproverUserId(array $post, $formdata = null): ?string
    {
        if (!empty($post['user_id']) && $this->isValidActingApproverUserId($post['user_id'])) {
            return (string) $post['user_id'];
        }
        if (Auth::check() && !empty(Auth::user()->user_id) && $this->isValidActingApproverUserId(Auth::user()->user_id)) {
            return (string) Auth::user()->user_id;
        }
        if ($formdata && !empty($formdata->user_id) && $this->isValidActingApproverUserId($formdata->user_id)) {
            return (string) $formdata->user_id;
        }
        return null;
    }

    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 '1758515400-da19c8cc-4109-4840-9222-afd342f33213':
            //     $ptformdata = $post;
            //     $ptformdata['form_id'] = '1761142083-5aa0d6f8-5641-41fb-868d-37690a1e8b4d'; //Proxyformid
            //     $ptformdata['contact_id'] = $post['hospital_name'];
            //     LambdaRequest::postrequest('form', 'formentity/submitform', ['formdata' => $ptformdata, 'entity_id' => $ptformdata['form_id'], 'user_id' => $user_id, 'partition' => $partition ]);
            // break;
            case '1758515400-da19c8cc-4109-4840-9222-afd342f33213':
                $ptformdata = $post;
                if(isset($post['proxy_submission_id'])) {
                    $ptformdata['id'] = $post['proxy_submission_id'];
                }
                $ptformdata['form_id'] = '1761142083-5aa0d6f8-5641-41fb-868d-37690a1e8b4d'; //Proxyformid
                $ptformdata['contact_id'] = $post['hospital_name'];
                Log::debug(print_r(["ptformdata"], true));
                Log::debug(print_r(['formdata' => $ptformdata, 'entity_id' => $ptformdata['form_id'], 'user_id' => $user_id, 'partition' => $partition ], true));
                $response = LambdaRequest::postrequest('form', 'formentity/submitform', ['formdata' => $ptformdata, 'entity_id' => $ptformdata['form_id'], 'user_id' => $user_id, 'partition' => $partition ]);
                Log::debug(print_r(["proxyforoutput"], true));
                Log::debug(print_r($response, true));
                // exit;
                $post['proxy_submission_id'] = $response->data->submission->id;
            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', '');
        $doctor_id = $request->input('doctor_id', '');
        $params = ['form_id' => $form_id, 'user_id' => $user_id, 'partition' => $partition];
        if (!empty($doctor_id)) {
            $params['filters'] = ['formdata.doctor_id' => $doctor_id];
        }
        $history = LambdaRequest::postrequest('form', 'formentity/getformhistory', $params);
        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));
        $canDeleteSubmission = $this->sessionFlag($formdata, 'delete_submission');
        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, 'formdata' => $formdata, 'can_delete_submission' => $canDeleteSubmission ];
        } else {
            $data = ['form' => $history->data->form, 'questions' => $history->data->questions, 'submissions' => $history->data->submissions, 'formname' => $history->data->formname, 'form_id' => $form_id, 'formdata' => $formdata, 'can_delete_submission' => $canDeleteSubmission ];
        }

        $userAttrs = $this->userAttributeCodes($history->data->form ?? null);
        $userAttrLabels = $this->resolveUserAttributeLabels($userAttrs);
        $data['userAttrs'] = $userAttrs;
        $data['userAttrLabels'] = $userAttrLabels;

        if($request->input('export', false)) {
            $exceldata = [];
            $exceldata[] = [$formdata->title];
            $exceldata[] = [''];
            $headers = ['Submission Date', 'Submitted By'];
            foreach ($userAttrs as $attr) {
                $headers[] = $userAttrLabels[$attr] ?? ucwords(str_replace('_', ' ', (string) $attr));
            }
            $headers[] = 'Approval Status';
            foreach($history->data->questions as $question) {
                if (isset($question->type) && $question->type == 'hidden') {
                    continue;
                }
                if (isset($question->type) && $question->type == 'multitextbox' && !empty($question->options)) {
                    foreach ($question->options as $k => $v) {
                        $optLabel = is_object($v) ? ($v->display ?? $v->label ?? $k) : $v;
                        $headers[] = $optLabel.' ('.$question->label.')';
                    }
                } else {
                    $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 : '';
                foreach ($userAttrs as $attr) {
                    $row[] = $this->userAttributeValue($submission->user_info ?? null, $attr);
                }
                $row[] = isset($submission->workflow_status) ? $submission->workflow_status : '';
                foreach($history->data->questions as $q => $v) {
                    if (isset($v->type) && $v->type == 'hidden') {
                        continue;
                    }
                    if (isset($v->type) && $v->type == 'multitextbox' && !empty($v->options)) {
                        foreach ($v->options as $optKey => $optMeta) {
                            $fieldKey = is_object($optMeta) ? ($optMeta->value ?? $optKey) : $optKey;
                            if (isset($submission->formdata->{$fieldKey})) {
                                $raw = $submission->formdata->{$fieldKey};
                                $row[] = is_array($raw) ? implode(', ', $raw) : (is_object($raw) ? json_encode($raw) : $raw);
                            } elseif (isset($submission->formdata->{$q}) && (is_object($submission->formdata->{$q}) || is_array($submission->formdata->{$q}))) {
                                $box = (array) $submission->formdata->{$q};
                                $raw = $box[$fieldKey] ?? '-';
                                $row[] = is_array($raw) ? implode(', ', $raw) : (is_object($raw) ? json_encode($raw) : $raw);
                            } else {
                                $row[] = '-';
                            }
                        }
                    } else {
                        if (!isset($submission->formdata->{$q})) {
                            $row[] = '-';
                        } elseif (is_array($submission->formdata->{$q})) {
                            $row[] = implode(', ', $submission->formdata->{$q});
                        } elseif (is_object($submission->formdata->{$q})) {
                            $row[] = collect((array) $submission->formdata->{$q})->map(function ($val, $key) {
                                return $key.': '.$val;
                            })->implode(', ');
                        } else {
                            $row[] = $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']);

        $apiPost = $post;
        unset($apiPost['authorization']);
        if ($download) {
            $apiPost['export'] = 1;
        }

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

        $breadcrumbs = [];
        $isTeamReport = isset($response->data->graph->agg_type) && $response->data->graph->agg_type === 'team';
        if ($isTeamReport && 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);
        }

        $post = array_merge((array)$response->data->post, $post);
        if (isset($post['metrics']) && is_string($post['metrics'])) {
            $post['metrics'] = array_values(array_filter(
                explode(',', $post['metrics']),
                function ($m) { return trim((string) $m) !== ''; }
            ));
        } elseif (isset($post['metrics']) && is_array($post['metrics'])) {
            $post['metrics'] = array_values(array_filter(
                $post['metrics'],
                function ($m) { return trim((string) $m) !== ''; }
            ));
        }

        if (isset($response->data->graph->metrics) && is_array($response->data->graph->metrics)) {
            $selectedMetrics = (!empty($post['metrics']) && is_array($post['metrics'])) ? $post['metrics'] : [];

            $allMetricFieldsMissingOrEmpty = false;
            foreach ($response->data->graph->metrics as $metric) {
                if (is_object($metric)) {
                    if (!isset($metric->metric) || $metric->metric === '' || $metric->metric === null) {
                        $allMetricFieldsMissingOrEmpty = true;
                        break;
                    }
                } elseif (is_array($metric)) {
                    if (!isset($metric['metric']) || $metric['metric'] === '' || $metric['metric'] === null) {
                        $allMetricFieldsMissingOrEmpty = true;
                        break;
                    }
                }
            }

            $showAllMetrics = empty($selectedMetrics) || $allMetricFieldsMissingOrEmpty;

            foreach ($response->data->graph->metrics as &$metric) {
                if ($showAllMetrics) {
                    if (is_object($metric)) {
                        $metric->is_visible = true;
                    } elseif (is_array($metric)) {
                        $metric['is_visible'] = true;
                    }
                } else {
                    if (is_object($metric)) {
                        $metric->is_visible = $this->metricMatchesFilter($metric, $selectedMetrics);
                    } elseif (is_array($metric)) {
                        $metric['is_visible'] = $this->metricMatchesFilter((object) $metric, $selectedMetrics);
                    }
                }
            }
            unset($metric);

            if (isset($response->data->graph->values->metrics) && is_array($response->data->graph->values->metrics)) {
                foreach ($response->data->graph->values->metrics as &$metric) {
                    if ($showAllMetrics) {
                        if (is_object($metric)) {
                            $metric->is_visible = true;
                        } elseif (is_array($metric)) {
                            $metric['is_visible'] = true;
                        }
                    } else {
                        if (is_object($metric)) {
                            $metric->is_visible = $this->metricMatchesFilter($metric, $selectedMetrics);
                        } elseif (is_array($metric)) {
                            $metric['is_visible'] = $this->metricMatchesFilter((object) $metric, $selectedMetrics);
                        }
                    }
                }
                unset($metric);
            }
        }

        if (empty($post['metrics'])) {
            unset($post['metrics']);
        }

        if (isset($response->data->graph)) {
            $this->normalizeLeaderboardMeRow($response->data->graph);
        }

        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[] = [''];
            $reportType = $post['type'] ?? null;
            if (!$reportType && isset($response->data->post)) {
                $reportType = is_object($response->data->post)
                    ? ($response->data->post->type ?? null)
                    : ($response->data->post['type'] ?? null);
            }
            switch ($reportType) {
                case 'leaderboard':
                case 'scoreboard':
                    $isTeamReport = isset($response->data->graph->agg_type) && $response->data->graph->agg_type === 'team';
                    $hideRank = $isTeamReport && $reportType === 'leaderboard';
                    $headings = $hideRank
                        ? ["User", "Designation", 'Zone', 'Region', "Area", "Territory"]
                        : ["Rank", "User", "Designation", 'Zone', 'Region', "Area", "Territory"];
                    foreach ($response->data->graph->metrics as $metric) {
                        if (isset($metric->is_visible) && !$metric->is_visible) {
                            continue;
                        }
                        $headings[] = $metric->display;
                    }
                    $exceldata[] = $headings;

                    $graphValues = $response->data->graph->values ?? [];
                    if (is_object($graphValues)) {
                        $graphValues = array_values((array) $graphValues);
                    }
                    if (!is_array($graphValues)) {
                        $graphValues = [];
                    }

                    foreach ($graphValues as $val) {
                        if (!isset($val->user)) {
                            continue;
                        }
                        $user = $val->user;
                        $positions = $user->positions ?? null;
                        $row = $hideRank
                            ? [
                                (string) ($user->name ?? '-'),
                                (string) ($user->designation ?? '-'),
                            ]
                            : [
                                (string) ($val->rank ?? ''),
                                (string) ($user->name ?? '-'),
                                (string) ($user->designation ?? '-'),
                            ];
                        $row[] = ($positions && isset($positions->Zone)) ? $positions->Zone : (($positions && isset($positions->Country)) ? $positions->Country : '-');
                        $row[] = ($positions && isset($positions->Region)) ? $positions->Region : '-';
                        $row[] = ($positions && isset($positions->Area)) ? $positions->Area : '-';
                        $row[] = ($positions && isset($positions->Territory)) ? $positions->Territory : '-';

                        foreach ($response->data->graph->metrics as $metric) {
                            if (isset($metric->is_visible) && !$metric->is_visible) {
                                continue;
                            }
                            $row[] = $this->leaderboardStatValue($val->stats ?? null, $metric);
                        }

                        $exceldata[] = $row;
                    }

                    //echo '
'; print_r($exceldata); exit; 
                    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) {
                            if (isset($metric->is_visible) && $metric->is_visible) {
                                $headers[] = $metric->metric ?? ($metric->display ?? '');
                            }
                        }
                        $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) {
                                if (isset($metric->is_visible) && $metric->is_visible) {
                                    $cell = $this->tabularMetricStatValue($metric, $user->id);
                                    $row[] = $cell !== null ? $cell : '-';
                                }
                            }
                            $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) {
                            if (isset($metric->is_visible) && !$metric->is_visible) {
                                continue;
                            }
                            $headers[] = $metric->metric ?? ($metric->display ?? '');
                        }
                        $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) {
                                if (isset($metric->is_visible) && !$metric->is_visible) {
                                    continue;
                                }
                                $cell = $this->tabularMetricStatValue($metric, $contact->id);
                                $row[] = $cell !== null ? $cell : '-';
                            }
                            $exceldata[] = $row;
                        }
                    }
                break;
            }
            //echo '
'; print_r($exceldata); exit;
            $data = new \StdClass;
            $data->sender_name = 'Rapport Support';
            $data->sender_email = 'support1@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]);
            } elseif ($email) {
                Mail::to($response->data->user->email)->send(new ReportExcel($data));
                return response()->json(['sent' => 'yes']);
            } else {
                return Excel::download(new InvoicesExport($exceldata), 'report.xlsx');
            }
            
        } else {
            $colors = ['FECD00', '01C14B', 'FF8050', '4A5CD0', '707070'];
            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]);

    }

    /** rapport-team4 or rapport-team4-{formId} -> rapport-team4 */
    protected function normalizeWorkflowPartition($partition) {
        if (empty($partition)) {
            return $partition;
        }
        if (preg_match('/^(rapport-[^-]+)/', $partition, $m)) {
            return $m[1];
        }
        $parts = explode('-', $partition);
        if (count($parts) >= 2 && $parts[0] === 'rapport') {
            return $parts[0] . '-' . $parts[1];
        }
        return $partition;
    }

    protected function getServiceAccessTokenForPartition($partition) {
        $partition = $this->normalizeWorkflowPartition($partition);
        $parts = explode('-', $partition);
        if (count($parts) < 2) {
            return null;
        }
        $domain = $parts[1];
        $user = DB::table('users')
            ->select('access_token')
            ->where('domain', $domain)
            ->whereNotNull('access_token')
            ->where('access_token', '!=', '')
            ->orderBy('updated_at', 'desc')
            ->first();

        return $user ? $user->access_token : null;
    }

    protected function workflowApprovalApiPayload($entityId, $partition, $userId, $submissionId, $formId) {
        return [
            'entity_id' => $entityId,
            'partition' => $this->normalizeWorkflowPartition($partition),
            'user_id' => $userId,
            'submission_id' => $submissionId,
            'form_id' => $formId,
        ];
    }

    protected function workflowApprovalActionsDisabled($workflowStatus, $approvalRecordStatus): bool
    {
        if (in_array($workflowStatus, ['approved', 'rejected'], true)) {
            return true;
        }
        return in_array($approvalRecordStatus, ['approve', 'reject', 'approved', 'rejected'], true);
    }

    protected function workflowApprovalStatusLabel($workflowStatus, $approvalRecordStatus): string
    {
        if ($workflowStatus === 'approved' || $workflowStatus === 'rejected') {
            return $workflowStatus;
        }
        if ($approvalRecordStatus === 'approve') {
            return 'approved';
        }
        if ($approvalRecordStatus === 'reject') {
            return 'rejected';
        }
        return $workflowStatus;
    }

    protected function workflowApprovalStatusMessage($workflowStatus, $approvalRecordStatus): string
    {
        if ($workflowStatus === 'approved') {
            return 'This submission has been fully approved.';
        }
        if ($workflowStatus === 'rejected') {
            return 'This submission has been rejected.';
        }
        if ($approvalRecordStatus === 'approve') {
            return 'You have already approved this submission. It may be awaiting approval from other approvers.';
        }
        if ($approvalRecordStatus === 'reject') {
            return 'You have already rejected this submission.';
        }
        return 'This submission is no longer awaiting your action.';
    }

    protected function previewUrlFromApprovalResponse($previewUrl) {
        if (empty($previewUrl)) {
            return '';
        }
        $query = parse_url($previewUrl, PHP_URL_QUERY);
        if (empty($query)) {
            return $previewUrl;
        }
        parse_str($query, $params);
        if (!empty($params['data'])) {
            return url('/form/preview?data=' . urlencode($params['data']));
        }

        return $previewUrl;
    }

    public function workflowApproval(Request $request) {
        $submissionId = $request->input('submission_id');
        $userId = $request->input('user_id');
        $formId = $request->input('form_id');
        $partition = $request->input('partition');
        $entityId = $request->input('entity_id');

        if (empty($submissionId) || empty($userId) || empty($formId) || empty($partition) || empty($entityId)) {
            return view('form.workflow-approval-error')->with([
                'message' => 'Missing required parameters: submission_id, user_id, form_id, partition, and entity_id are required.',
            ]);
        }

        $approvalPayload = $this->workflowApprovalApiPayload($entityId, $partition, $userId, $submissionId, $formId);
        $accessToken = $this->getServiceAccessTokenForPartition($partition);
        $response = LambdaRequest::postrequest(
            'form',
            'formentity/approval',
            $approvalPayload,
            $accessToken ?: ''
        );

        if (!isset($response->status) || $response->status !== 'success' || !isset($response->data->preview->preview_url)) {
            $message = $response->message ?? 'Unable to load submission for approval.';
            return view('form.workflow-approval-error')->with(['message' => $message]);
        }

        $preview = $response->data->preview;
        $previewUrl = $this->previewUrlFromApprovalResponse($preview->preview_url ?? '');
        $workflowStatus = $preview->workflow_status ?? 'unapproved';
        $approvalRecordStatus = $preview->approval_status ?? 'unapproved';
        $actionsDisabled = $this->workflowApprovalActionsDisabled($workflowStatus, $approvalRecordStatus);
        $statusLabel = $this->workflowApprovalStatusLabel($workflowStatus, $approvalRecordStatus);

        return view('form.workflow-approval')->with([
            'preview_url' => $previewUrl,
            'form_name' => $preview->form_name ?? '',
            'submitted_by' => $preview->submitted_by ?? '',
            'workflow_status' => $statusLabel,
            'submission_id' => $submissionId,
            'user_id' => $userId,
            'form_id' => $formId,
            'partition' => $partition,
            'entity_id' => $entityId,
            'actions_disabled' => $actionsDisabled,
            'status_message' => $this->workflowApprovalStatusMessage($workflowStatus, $approvalRecordStatus),
        ]);
    }

    public function workflowApprovalAction(Request $request) {
        $post = $request->all();
        $submissionId = $post['submission_id'] ?? '';
        $userId = $post['user_id'] ?? '';
        $formId = $post['form_id'] ?? '';
        $partition = $post['partition'] ?? '';
        $action = $post['action'] ?? '';

        if (empty($submissionId) || empty($userId) || empty($formId) || empty($partition)) {
            return response()->json(['status' => 'error', 'message' => 'Missing required parameters.'], 400);
        }
        if (!$this->isValidActingApproverUserId($userId)) {
            return response()->json(['status' => 'error', 'message' => 'A valid approver user_id is required.'], 400);
        }
        if (!in_array($action, ['approve', 'reject'])) {
            return response()->json(['status' => 'error', 'message' => 'Invalid action.'], 400);
        }
        if ($action === 'reject' && empty(trim($post['reason'] ?? ''))) {
            return response()->json(['status' => 'error', 'message' => 'Reject reason is required.'], 400);
        }

        $approverejectPayload = [
            'submission_id' => $submissionId,
            'form_id' => $formId,
            'action' => $action,
            'user_id' => $userId,
            'partition' => $partition,
            'reason' => $post['reason'] ?? '',
            'form_name' => $post['form_name'] ?? '',
        ];
        if (!empty($post['entity_id'])) {
            $approverejectPayload['approval_id'] = $post['entity_id'];
        }
        $accessToken = $this->getServiceAccessTokenForPartition($partition);
        $response = LambdaRequest::postrequest(
            'form',
            'formentity/approvereject',
            $approverejectPayload,
            $accessToken ?: ''
        );

        if (isset($response->status) && $response->status === 'success') {
            $workflowStatus = 'unapproved';
            $approvalRecordStatus = $action === 'approve' ? 'approve' : 'reject';
            if (!empty($post['entity_id'])) {
                $approvalPayload = $this->workflowApprovalApiPayload(
                    $post['entity_id'],
                    $partition,
                    $userId,
                    $submissionId,
                    $formId
                );
                $accessToken = $this->getServiceAccessTokenForPartition($partition);
                $approvalResponse = LambdaRequest::postrequest(
                    'form',
                    'formentity/approval',
                    $approvalPayload,
                    $accessToken ?: ''
                );
                if (isset($approvalResponse->status) && $approvalResponse->status === 'success' && isset($approvalResponse->data->preview)) {
                    $preview = $approvalResponse->data->preview;
                    $workflowStatus = $preview->workflow_status ?? $workflowStatus;
                    $approvalRecordStatus = $preview->approval_status ?? $approvalRecordStatus;
                }
            }
            return response()->json([
                'status' => 'success',
                'message' => $action === 'approve' ? 'Submission approved successfully.' : 'Submission rejected successfully.',
                'status_label' => $this->workflowApprovalStatusLabel($workflowStatus, $approvalRecordStatus),
                'status_message' => $this->workflowApprovalStatusMessage($workflowStatus, $approvalRecordStatus),
            ]);
        }

        return response()->json([
            'status' => 'error',
            'message' => $response->message ?? 'Unable to process approval action.',
        ], 500);
    }

    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;
        $params = ['questions' => $finfo->data->questions, 'form' => $formdata, 'id' => $finfo->data->formdata->submission_id, 'form_id' => $finfo->data->formdata->form_id, 'submitted_formdata'=> isset($finfo->data->submitted_data) ? $finfo->data->submitted_data : []];

        if (\View::exists('form.'.$formdata->partition.'.preview-'.$formdata->form_id)) {
            return view('form.'.$formdata->partition.'.preview-'.$formdata->form_id)->with($params);
        } elseif (\View::exists('form.preview-'.$formdata->form_id)) {
            return view('form.preview-'.$formdata->form_id)->with($params);
        } elseif (\View::exists('form.'.$formdata->partition.'.'.$formdata->form_id)) {
            return view('form.'.$formdata->partition.'.'.$formdata->form_id)->with($params);
        } elseif (\View::exists('form.'.$formdata->form_id)) {
            return view('form.'.$formdata->form_id)->with($params);
        } elseif (\View::exists('form.preview-'.$formdata->form_id)) {
            return view('form.preview-'.$formdata->form_id)->with($params);
        } else{
            return view('form.common')->with($params);
        }
        // if (\View::exists('form.'.$formdata->form_id)) {
        //     return view('form.'.$formdata->form_id)->with($params);
        // } else {
        //     return view('form.common')->with($params);
        // }
    }

    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');
        $formInfo = json_decode($post['form_info'] ?? '');
        $imageFieldNames = $this->getPersonalizationImageFieldNames($formInfo);
        $images = [];
        foreach ($request->file() as $fname => $file) {
            if (!$file instanceof \Illuminate\Http\UploadedFile || !$file->isValid()) {
                continue;
            }
            $post[$fname] = $this->_uploadMediaLocal($request, $fname, 'public/personalized/'.$post['form_id'].'/'.$fname);
            if (in_array($fname, $imageFieldNames, true)) {
                $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'] = $formInfo;
        // Skip cropper unless this template has an image overlay and a valid image was uploaded
        $post['skip_cropper'] = empty($imageFieldNames) || count($images) === 0;
        if ($post['skip_cropper']) {
            $post['redirect'] = '/form/generatepersonalization';
        }
        $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'); Log::debug(print_r(['testpo'], true)); Log::debug(print_r($formdata, true)); Log::debug(print_r($form_info, true)); //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 = []; $linkvalue = null; $linkPosition = null; $finfo = null; $contactMap = []; 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 ]); Log::debug(print_r(['testpocontact'], true)); Log::debug(print_r($finfo, true)); if(isset($finfo->data->submission->contacts) && count($finfo->data->submission->contacts) > 0) { // $form_info['doctor_name'] = $finfo->data->submission->contacts[0]->name ?? ''; foreach($finfo->data->submission->contacts as $c) { if(isset($c->id)) { foreach($form_info as $k => $fi) { if($fi == $c->id) { $form_info[$k] = $c->name ?? ''; } } } } } Log::debug(print_r($contactMap, true)); } 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;
            // }
            //echo '
'; print_r($form_info); 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':
                    case 'link':
                        if (!isset($form_info[$pos->field_name]) || $form_info[$pos->field_name] === '') {
                            break;
                        }

                        $text = (string) $form_info[$pos->field_name];
                        $isLinkField = ($pos->type === 'link')
                            || (isset($pos->field_name) && stripos((string) $pos->field_name, 'link') !== false);
                        if ($isLinkField) {
                            $text = $this->normalizePersonalizationLinkText($text);
                        }

                        if ($this->shouldCapturePersonalizationPdfLink($form_info['form_info'], $i, $pos)) {
                            $linkvalue = $this->normalizePersonalizationLinkUrl($text);
                            $linkPosition = $pos;
                        }

                        if (!$this->shouldCapturePersonalizationPdfLink($form_info['form_info'], $i, $pos)) {
                            $this->drawPersonalizationTextOnImage($outputImage, $pos, $text, $isLinkField);
                        }
                        break;

                    case 'multiline':
                        if (isset($form_info[$pos->field_name]) && $form_info[$pos->field_name] !== '') {
                            $this->drawPersonalizationMultilineOnImage(
                                $outputImage,
                                $pos,
                                (string) $form_info[$pos->field_name]
                            );
                        }
                        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);
        }

        $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 (empty($linkvalue)) {
                exec('convert '.implode(' ', $form_info['pdf_images']).' -quality 100 '.$folder.'/'.$pdffile);
                $form_info['pdf_file'] = $pdffile;
            } else {
                $this->createPersonalizationPdfWithLink(
                    $w,
                    $h,
                    $form_info['pdf_images'][0],
                    $folder.'/'.$pdffile,
                    $linkvalue ?? '',
                    $linkPosition
                );
                $form_info['pdf_file'] = $pdffile;
            }
        }
        $form_info['personalization_id'] = $form_info['form_info']->id;

        if (isset($formdata) && !empty($formdata) && $formdata->user_id != '' && $finfo && isset($finfo->data->submission->id)) {
            $submissionUpdate = [
                'id' => $finfo->data->submission->id,
                'personalization_id' => $form_info['personalization_id'],
                'genareted_image' => $genareted_image,
            ];
            if (!empty($form_info['pdf_file'])) {
                $submissionUpdate['pdf_file'] = $form_info['pdf_file'];
            }

            $finfo = LambdaRequest::postrequest('form', 'formentity/submitform', [
                'formdata' => $submissionUpdate,
                'entity_id' => $formdata->form_id,
                'user_id' => $formdata->user_id,
                'partition' => $formdata->partition,
            ]);
            Log::debug(print_r(['personalization_submission_update'], true));
            Log::debug(print_r($finfo, true));
        }

        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"}]'); //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) { $sessionForm = $request->session()->get('formdata'); $submission_id = $request->input('id') ?: $request->input('submission_id'); $form_id = $request->input('form_id') ?: (is_object($sessionForm) ? ($sessionForm->form_id ?? null) : null); $partition = $request->input('partition') ?: (is_object($sessionForm) ? ($sessionForm->partition ?? null) : null); $user_id = $request->input('user_id') ?: (is_object($sessionForm) ? ($sessionForm->user_id ?? null) : null); $form_info = null; $finfo = null; $personalizations = []; if ($submission_id && $form_id && $partition) { $finfo = LambdaRequest::postrequest('form', 'formentity/getformdefination', [ 'form_id' => $form_id, 'user_id' => $user_id ?: '', 'partition' => $partition, 'id' => $submission_id, ]); $apiFormdata = null; if (is_object($finfo) && isset($finfo->data) && is_object($finfo->data) && isset($finfo->data->formdata)) { $apiFormdata = $finfo->data->formdata; } if (is_object($finfo) && isset($finfo->data) && is_object($finfo->data) && isset($finfo->data->personalizations)) { $personalizations = $finfo->data->personalizations; } // Fallback: getsubmissiondetails is more reliable when getformdefination fails // (e.g. elastic user lookup / processquestions errors). $formdataLooksEmpty = empty($apiFormdata); if (!$formdataLooksEmpty && (is_object($apiFormdata) || is_array($apiFormdata))) { $keys = array_keys((array) $apiFormdata); $meaningful = array_diff($keys, ['title']); $formdataLooksEmpty = count($meaningful) === 0; } if ($formdataLooksEmpty) { try { $details = LambdaRequest::getrequest('form', 'formentity/getsubmissiondetails', [ 'form_id' => $form_id, 'partition' => $partition, 'id' => $submission_id, ]); if (is_object($details) && isset($details->data->submission->formdata)) { $apiFormdata = $details->data->submission->formdata; if (empty($user_id) && isset($details->data->submission->user_id)) { $user_id = $details->data->submission->user_id; } } } catch (\Throwable $e) { Log::error('downloadpersonalization_getsubmissiondetails_failed: '.$e->getMessage()); } } if (empty($apiFormdata)) { Log::debug(print_r([ 'downloadpersonalization_missing_formdata', 'submission_id' => $submission_id, 'form_id' => $form_id, 'partition' => $partition, 'finfo' => $finfo, ], true)); return view('form.download')->with([ 'folder' => 'personalized/' . $form_id . '/', 'images' => [], 'error' => 'Unable to load generated assets for this submission.', ]); } $form_info = is_array($apiFormdata) ? $apiFormdata : (array) $apiFormdata; $form_info['form_id'] = $form_id; } elseif (!$submission_id) { $form_info = $request->session()->get('form_info'); } if (empty($form_info) || empty($form_info['form_id'])) { return view('form.download')->with([ 'folder' => $form_id ? ('personalized/' . $form_id . '/') : '', 'images' => [], 'error' => 'Unable to load generated assets. Missing form context — please open the list again and retry.', ]); } if (isset($form_info['genareted_image'])) { if (is_string($form_info['genareted_image'])) { $form_info['genareted_image'] = json_decode($form_info['genareted_image'], true) ?: []; } elseif (is_object($form_info['genareted_image'])) { $form_info['genareted_image'] = array_values((array) $form_info['genareted_image']); } elseif (!is_array($form_info['genareted_image'])) { $form_info['genareted_image'] = []; } } else { $form_info['genareted_image'] = []; } //Log::debug(print_r($form_info, true)); //Log::debug(print_r($formdata, true)); $folder = storage_path('app/public/personalized/'.$form_info['form_id']); $needsRegen = empty($form_info['genareted_image']); if (!$needsRegen) { foreach ($form_info['genareted_image'] as $image) { if (!is_string($image) || $image === '' || !file_exists($folder.'/'.$image)) { $needsRegen = true; break; } } } if (!$needsRegen && !empty($form_info['pdf_file']) && !file_exists($folder.'/'.$form_info['pdf_file'])) { $needsRegen = true; } if ($needsRegen && $submission_id && $form_id && $partition) { if (empty($personalizations)) { // Retry definition fetch for templates if first response had no personalizations try { $persInfo = LambdaRequest::postrequest('form', 'formentity/getformdefination', [ 'form_id' => $form_id, 'user_id' => $user_id ?: '', 'partition' => $partition, 'id' => $submission_id, ]); if (is_object($persInfo) && isset($persInfo->data->personalizations)) { $personalizations = $persInfo->data->personalizations; } } catch (\Throwable $e) { Log::error('downloadpersonalization_personalizations_retry_failed: '.$e->getMessage()); } } $personalization = $this->resolvePersonalizationTemplate($form_info, $personalizations); if ($personalization) { try { $generated = $this->regeneratePersonalizationAssets($form_id, $form_info, $personalization); if (!empty($generated['genareted_image'])) { $form_info['genareted_image'] = $generated['genareted_image']; if (!empty($generated['pdf_file'])) { $form_info['pdf_file'] = $generated['pdf_file']; } $form_info['personalization_id'] = $personalization->id; // Persist so subsequent downloads skip regeneration $persistUserId = $user_id ?: ($form_info['user_id'] ?? null); if (!empty($persistUserId)) { $submissionUpdate = [ 'id' => $submission_id, 'personalization_id' => $personalization->id, 'genareted_image' => $form_info['genareted_image'], ]; if (!empty($form_info['pdf_file'])) { $submissionUpdate['pdf_file'] = $form_info['pdf_file']; } LambdaRequest::postrequest('form', 'formentity/submitform', [ 'formdata' => $submissionUpdate, 'entity_id' => $form_id, 'user_id' => $persistUserId, 'partition' => $partition, ]); } } else { Log::error('downloadpersonalization_regen_empty', [ 'submission_id' => $submission_id, 'form_id' => $form_id, 'personalization_id' => $personalization->id ?? null, ]); } } catch (\Throwable $e) { Log::error('downloadpersonalization_regen_failed: '.$e->getMessage(), [ 'submission_id' => $submission_id, 'form_id' => $form_id, 'trace' => $e->getTraceAsString(), ]); } } else { Log::error('downloadpersonalization_no_personalization_template', [ 'submission_id' => $submission_id, 'form_id' => $form_id, 'personalization_id' => $form_info['personalization_id'] ?? null, 'personalizations_count' => is_countable($personalizations) ? count($personalizations) : 0, ]); } } if (empty($form_info['genareted_image']) && empty($form_info['pdf_file'])) { return view('form.download')->with([ 'folder' => 'personalized/' . $form_info['form_id'] . '/', 'images' => [], 'error' => 'Unable to load generated assets for this submission.', ]); } $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;
            }
            $viewPartition = $partition ?: ($form_info['partition'] ?? '');
            $viewFormId = $form_id ?: ($form_info['form_id'] ?? '');
            if ($viewPartition && $viewFormId && \View::exists('form.'.$viewPartition.'.download-'.$viewFormId)) {
                return view('form.'.$viewPartition.'.download-'.$viewFormId)->with($res);
            } else {
                return view('form.download')->with($res);
            }
        }
        //return view('form.download')->with($res);
    }

    /**
     * Overlay image field names from a personalization template's positions.
     */
    private function getPersonalizationImageFieldNames($formInfo): array
    {
        $names = [];
        if (!is_object($formInfo) || empty($formInfo->positions)) {
            return $names;
        }
        foreach ((array) $formInfo->positions as $posJson) {
            $positions = is_string($posJson) ? json_decode($posJson) : $posJson;
            foreach ((array) $positions as $pos) {
                if (is_object($pos) && isset($pos->type) && $pos->type === 'image' && !empty($pos->field_name)) {
                    $names[] = $pos->field_name;
                }
            }
        }
        return array_values(array_unique($names));
    }

    /**
     * Pick personalization template for a submission (by personalization_id, else first).
     */
    private function resolvePersonalizationTemplate(array $form_info, $personalizations)
    {
        if (empty($personalizations)) {
            return null;
        }
        if (is_object($personalizations)) {
            $personalizations = array_values((array) $personalizations);
        }
        if (!is_array($personalizations)) {
            return null;
        }
        $personalizationId = $form_info['personalization_id'] ?? null;
        if ($personalizationId) {
            foreach ($personalizations as $pers) {
                if (is_array($pers)) {
                    $pers = (object) $pers;
                }
                if (is_object($pers) && isset($pers->id) && (string) $pers->id === (string) $personalizationId) {
                    return $pers;
                }
            }
        }
        $first = reset($personalizations);
        if (is_array($first)) {
            $first = (object) $first;
        }
        return is_object($first) ? $first : null;
    }

    /**
     * Resolve a personalization image field path from stored submission values.
     */
    private function resolvePersonalizationImagePath(array $form_info, string $fieldName): ?string
    {
        $candidates = [];
        if (!empty($form_info['cropped-'.$fieldName])) {
            $candidates[] = $form_info['cropped-'.$fieldName];
        }
        if (!empty($form_info[$fieldName])) {
            $candidates[] = $form_info[$fieldName];
        }
        foreach ($candidates as $value) {
            if (!is_string($value) || $value === '') {
                continue;
            }
            if (strpos($value, '/storage/') === 0 || strpos($value, 'storage/') === 0) {
                $local = storage_path(str_replace('/storage', 'app/public', '/'.ltrim($value, '/')));
                if (file_exists($local)) {
                    return $local;
                }
            }
            $asPublic = storage_path('app/public/'.ltrim(str_replace('/storage/', '', $value), '/'));
            if (file_exists($asPublic)) {
                return $asPublic;
            }
            if (file_exists($value)) {
                return $value;
            }
        }
        return null;
    }

    /**
     * Decode personalization positions (JSON string or already-decoded array/object).
     */
    private function decodePersonalizationPositions($raw)
    {
        if ($raw === null || $raw === '') {
            return [];
        }
        if (is_string($raw)) {
            $decoded = json_decode($raw);
            if (is_array($decoded) || is_object($decoded)) {
                return $decoded;
            }
            return [];
        }
        if (is_array($raw) || is_object($raw)) {
            return $raw;
        }
        return [];
    }

    /**
     * Regenerate personalization images/PDF from submission field values + template.
     */
    private function regeneratePersonalizationAssets(string $form_id, array $form_info, object $personalization): array
    {
        $genareted_image = [];
        $pdf_images = [];
        $folder = storage_path('app/public/personalized/'.$form_id);
        if (!is_dir($folder)) {
            @mkdir($folder, 0755, true);
        }

        $templates = isset($personalization->templates) ? $personalization->templates : [];
        if (is_string($templates)) {
            $decodedTemplates = json_decode($templates, true);
            $templates = is_array($decodedTemplates) ? $decodedTemplates : [$templates];
        } elseif (is_object($templates)) {
            $templates = array_values((array) $templates);
        }
        if (empty($templates) && !empty($personalization->template)) {
            $templates = [$personalization->template];
        }
        if (empty($templates)) {
            Log::error('regeneratePersonalizationAssets_no_templates', [
                'form_id' => $form_id,
                'personalization_id' => $personalization->id ?? null,
            ]);
            return ['genareted_image' => []];
        }

        $positionsAll = isset($personalization->positions) ? $personalization->positions : [];
        if (is_string($positionsAll)) {
            $decodedPositions = json_decode($positionsAll, true);
            $positionsAll = is_array($decodedPositions) ? $decodedPositions : [];
        } elseif (is_object($positionsAll)) {
            $positionsAll = (array) $positionsAll;
        }

        $w = 0;
        $h = 0;
        foreach ($templates as $i => $template) {
            if (!is_string($template) || $template === '') {
                continue;
            }
            $temp = pathinfo($template);
            $extension = $temp['extension'] ?? 'png';
            $templateLocal = $folder.'/template-'.$personalization->id.'_'.$i.'.'.$extension;
            if (!file_exists($templateLocal)) {
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $template);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
                $data = curl_exec($ch);
                $curlErr = curl_error($ch);
                curl_close($ch);
                if ($data === false || $data === '') {
                    throw new \RuntimeException('Failed to download personalization template: '.$curlErr);
                }
                Storage::disk('public')->put('personalized/'.$form_id.'/template-'.$personalization->id.'_'.$i.'.'.$extension, $data);
            }

            $outputImage = $this->retimage($templateLocal);
            if (!$outputImage) {
                throw new \RuntimeException('Failed to read personalization template image: '.$templateLocal);
            }
            $w = imagesx($outputImage);
            $h = imagesy($outputImage);
            $positions = $this->decodePersonalizationPositions($positionsAll[$i] ?? []);

            $maskimages = [];
            foreach ($positions as $pos) {
                $pos = is_array($pos) ? (object) $pos : $pos;
                if (!is_object($pos)) {
                    continue;
                }
                if (isset($pos->type) && $pos->type == 'image' && isset($pos->fill) && $pos->fill == 'mask') {
                    $maskimages[] = $pos;
                }
            }
            if (sizeof($maskimages) > 0) {
                $tempimage = imagecreatetruecolor($w, $h);
                foreach ($maskimages as $pos) {
                    $image = $this->resolvePersonalizationImagePath($form_info, (string) $pos->field_name);
                    if (!$image) {
                        continue;
                    }
                    $photoimg = $this->retimage($image);
                    $photosize = getimagesize($image);
                    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;
            }

            foreach ($positions as $pos) {
                $pos = is_array($pos) ? (object) $pos : $pos;
                if (!is_object($pos) || !isset($pos->type)) {
                    continue;
                }
                switch ($pos->type) {
                    case 'image':
                        if (!(isset($pos->fill) && $pos->fill == 'mask')) {
                            $image = $this->resolvePersonalizationImagePath($form_info, (string) $pos->field_name);
                            if (!$image) {
                                break;
                            }
                            $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':
                    case 'link':
                        if (!isset($form_info[$pos->field_name]) || $form_info[$pos->field_name] === '') {
                            break;
                        }
                        $text = (string) $form_info[$pos->field_name];
                        $isLinkField = ($pos->type === 'link')
                            || (isset($pos->field_name) && stripos((string) $pos->field_name, 'link') !== false);
                        if ($isLinkField) {
                            $text = $this->normalizePersonalizationLinkText($text);
                        }
                        $this->drawPersonalizationTextOnImage($outputImage, $pos, $text, $isLinkField);
                        break;
                    case 'multiline':
                        if (isset($form_info[$pos->field_name]) && $form_info[$pos->field_name] !== '') {
                            $this->drawPersonalizationMultilineOnImage(
                                $outputImage,
                                $pos,
                                (string) $form_info[$pos->field_name]
                            );
                        }
                        break;
                }
            }

            $filename = 'generated-'.strtotime('now').'_'.$i.'.png';
            $genareted_image[] = $filename;
            $createpdf = isset($personalization->createpdf) ? (array) $personalization->createpdf : [];
            if (isset($createpdf[$i]) && $createpdf[$i] == 'yes') {
                $pdf_images[] = $folder.'/'.$filename;
            }
            imagepng($outputImage, $folder.'/'.$filename);
            imagedestroy($outputImage);
        }

        $result = ['genareted_image' => $genareted_image];
        $createpdfAll = isset($personalization->createpdf) ? (array) $personalization->createpdf : [];
        if (!empty($createpdfAll) && in_array('yes', $createpdfAll, true) && !empty($pdf_images)) {
            $pdffile = 'combined-'.strtotime('now').'.pdf';
            exec('convert '.implode(' ', $pdf_images).' -quality 100 '.$folder.'/'.$pdffile);
            if (file_exists($folder.'/'.$pdffile)) {
                $result['pdf_file'] = $pdffile;
            }
        }

        return $result;
    }

    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': case 'link': if (!isset($finfo->data->formdata->{$pos->field_name}) || $finfo->data->formdata->{$pos->field_name} === '') { break; } $text = (string) $finfo->data->formdata->{$pos->field_name}; $isLinkField = ($pos->type === 'link') || (isset($pos->field_name) && stripos((string) $pos->field_name, 'link') !== false); if ($isLinkField) { $text = $this->normalizePersonalizationLinkText($text); } $this->drawPersonalizationTextOnImage($outputImage, $pos, $text, $isLinkField); break; case 'multiline': if (isset($finfo->data->formdata->{$pos->field_name}) && $finfo->data->formdata->{$pos->field_name} !== '') { $this->drawPersonalizationMultilineOnImage( $outputImage, $pos, (string) $finfo->data->formdata->{$pos->field_name} ); } 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;
    }

    /**
     * Check if cache is working correctly
     */
    protected function isCacheWorking() {
        try {
            $testKey = 'cache_test_' . time();
            $testValue = 'test_' . rand(1000, 9999);
            
            // Try to write and read from cache
            Cache::put($testKey, $testValue, 10);
            $retrieved = Cache::get($testKey);
            
            // Clean up
            Cache::forget($testKey);
            
            return $retrieved === $testValue;
        } catch (\Exception $e) {
            Log::warning('Cache check failed: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Rate limiting using cache
     */
    protected function checkRateLimitCache($ip, $limit = 10, $window = 60) {
        $cacheKey = 'downloaddata_rate_limit_' . md5($ip);
        $currentTime = time();
        
        $cacheData = Cache::get($cacheKey);
        
        if (!$cacheData || !isset($cacheData['reset_at']) || $currentTime >= $cacheData['reset_at']) {
            $cacheData = [
                'count' => 0,
                'reset_at' => $currentTime + $window
            ];
        }
        
        if ($cacheData['count'] >= $limit) {
            $retryAfter = max(1, $cacheData['reset_at'] - $currentTime);
            return [
                'allowed' => false,
                'retry_after' => $retryAfter
            ];
        }
        
        $cacheData['count']++;
        $ttl = max($window, $cacheData['reset_at'] - $currentTime);
        Cache::put($cacheKey, $cacheData, $ttl + 5);
        
        return [
            'allowed' => true,
            'remaining' => $limit - $cacheData['count']
        ];
    }

    /**
     * Ensure rate_limit_logs table exists
     */
    protected function ensureRateLimitTable() {
        try {
            // Check if table exists
            if (!DB::getSchemaBuilder()->hasTable('rate_limit_logs')) {
                DB::statement("CREATE TABLE IF NOT EXISTS `rate_limit_logs` (
                    `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
                    `ip_hash` varchar(64) NOT NULL,
                    `endpoint` varchar(255) NOT NULL,
                    `request_count` int(11) NOT NULL DEFAULT 0,
                    `reset_at` int(11) NOT NULL,
                    `created_at` timestamp NULL DEFAULT NULL,
                    `updated_at` timestamp NULL DEFAULT NULL,
                    PRIMARY KEY (`id`),
                    UNIQUE KEY `ip_endpoint` (`ip_hash`, `endpoint`),
                    KEY `reset_at` (`reset_at`)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
            }
        } catch (\Exception $e) {
            Log::error('Failed to create rate_limit_logs table: ' . $e->getMessage());
        }
    }

    /**
     * Rate limiting using database
     */
    protected function checkRateLimitDatabase($ip, $endpoint, $limit = 10, $window = 60) {
        try {
            $this->ensureRateLimitTable();
            
            $ipHash = md5($ip);
            $currentTime = time();
            $oneMinuteAgo = $currentTime - 60; // 1 minute ago in seconds

            // First, delete all entries before 1 minute (older than 1 minute)
            // Delete entries where created_at is older than 1 minute ago
            DB::table('rate_limit_logs')
                ->where('endpoint', $endpoint)
                ->where('created_at', '<', date('Y-m-d H:i:s', $oneMinuteAgo))
                ->delete();
            
            // Calculate total number of records in the table for this endpoint
            $totalRecords = DB::table('rate_limit_logs')
                ->where('endpoint', $endpoint)
                ->count();
            
            // If total records is more than or equal to 10, return 429 response
            if ($totalRecords >= $limit) {
                return [
                    'allowed' => false,
                    'retry_after' => 60, // Retry after 1 minute
                    'remaining' => 0
                ];
            }
            
            // If less than 10, make an entry and continue
            DB::table('rate_limit_logs')->insert([
                'ip_hash' => $ipHash,
                'endpoint' => $endpoint,
                'request_count' => 1,
                'reset_at' => $currentTime + $window,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ]);
            
            return [
                'allowed' => true,
                'remaining' => $limit - $totalRecords - 1
            ];
            
        } catch (\Exception $e) {
            Log::error('Database rate limiting failed: ' . $e->getMessage());
            // If database fails, allow the request (fail open)
            return ['allowed' => true, 'remaining' => $limit];
        }
    }

    public function downloaddata(Request $request) {
        // Rate limiting: 10 requests per minute per IP
        $ip = $request->ip() ?? $request->header('X-Forwarded-For') ?? $request->server('REMOTE_ADDR') ?? 'unknown';
        // Handle X-Forwarded-For header which can contain multiple IPs
        if (strpos($ip, ',') !== false) {
            $ips = array_map('trim', explode(',', $ip));
            $ip = $ips[0];
        }
        $ip = trim($ip);
        
        // Check rate limit - try cache first, fallback to database
        $rateLimitResult = null;
        $useCache = true;
        $endpoint = 'downloaddata';
        
        // Static variable to cache the cache check result (avoid checking on every request)
        // static $cacheWorking = null;
        // if ($cacheWorking === null) {
        //     $cacheWorking = $this->isCacheWorking();
        // }
        
        // if ($cacheWorking) {
        //     $rateLimitResult = $this->checkRateLimitCache($ip, 10, 60);
        //     // If cache check fails, try database
        //     if (!$rateLimitResult || !isset($rateLimitResult['allowed'])) {
        //         $cacheWorking = false; // Mark cache as not working
        //     }
        // }
        
        // // If cache is not working or cache check failed, use database
        // if (!$cacheWorking || !$rateLimitResult || !isset($rateLimitResult['allowed'])) {
        //     $rateLimitResult = $this->checkRateLimitDatabase($ip, $endpoint, 10, 60);
        // }

        $rateLimitResult = $this->checkRateLimitDatabase($ip, $endpoint, 10, 60);
        // If rate limit exceeded, return 429
        if (!$rateLimitResult['allowed']) {
            $retryAfter = $rateLimitResult['retry_after'];
            return response()->json([
                'error' => 'Rate limit exceeded',
                'message' => 'Too many requests. Please try again in ' . $retryAfter . ' seconds.',
                'retry_after' => $retryAfter
            ], 429)->header('Retry-After', $retryAfter)
              ->header('X-RateLimit-Limit', '10')
              ->header('X-RateLimit-Remaining', '0');
        }
        
        $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;
        // }
        
        
        if (is_object($formdata) && property_exists($formdata, 'form_id')) {
            $form_id = $request->input('form_id', $formdata->form_id);
        } else {
            return response()->json([
                'error' => 'Form data not found',
                'message' => 'Form information was not found or not valid.'
            ], 404);
        }

        $startdate = $request->input('startdate', '');
        $enddate = $request->input('enddate', '');
        if ($startdate === '' || $enddate === '') {
            return response()->json([
                'error' => 'Invalid date range',
                'message' => 'Start date and end date are required for export.'
            ], 422);
        }
        try {
            $start = new \DateTime($startdate);
            $end = new \DateTime($enddate);
        } catch (\Exception $e) {
            return response()->json([
                'error' => 'Invalid date range',
                'message' => 'Start date or end date is invalid.'
            ], 422);
        }
        if ($end < $start) {
            return response()->json([
                'error' => 'Invalid date range',
                'message' => 'End date must be on or after start date.'
            ], 422);
        }
        $maxEnd = (clone $start)->modify('+12 months');
        if ($end > $maxEnd) {
            return response()->json([
                'error' => 'Invalid date range',
                'message' => 'Date range must not exceed 12 months.'
            ], 422);
        }

        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 {
            $serviceParams = [
                'form_id' => $form_id,
                'user_id' => $formdata->user_id,
                'partition' => $formdata->partition,
                'team_report' => 1,
                'json_file' => 1
            ];
            if (isset($formdata->all_data_access) && $formdata->all_data_access == true) {
                $serviceParams['alldata'] = 1;
            }
            $serviceParams['date_range'] = [$startdate, $enddate];
            $history = LambdaRequest::postrequest('form', 'formentity/getformhistory', $serviceParams);
            // echo '
'; print_r($history); exit;

            $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($serviceParams, true));
        // echo '
'; print_r($formdata); exit;
        $exceldata = [];
        $exceldata[] = [$formdata->title];
     
        $exceldata[] = [''];
        $headers = ['Submission Date', 'Submitted By', 'Employee Code', 'Approval Status'];
        $userAttrs = $this->userAttributeCodes($history->data->form ?? null);
        $userAttrLabels = $this->resolveUserAttributeLabels($userAttrs);
        foreach ($userAttrs as $attr) {
            $headers[] = $userAttrLabels[$attr] ?? ucwords(str_replace('_', ' ', (string) $attr));
        }
        $exportShowPositions = $history->data->form->show_positions ?? $history->data->form->show_position ?? 'no';
        $exportPositionColumns = $this->getAvailablePositionColumns($history->data->submissions ?? [], $exportShowPositions);
        $positionLabels = [
            'territory' => 'Territory',
            'area' => 'Area',
            'region' => 'Region',
            'zone' => 'Zone',
        ];
        foreach ($exportPositionColumns as $positionField) {
            $headers[] = $positionLabels[$positionField] ?? ucfirst($positionField);
        }
        if(isset($history->data) && isset($history->data->form) && isset($history->data->form->show_manager_details) && $history->data->form->show_manager_details === 'yes'){
            $headers = array_merge( $headers, ['L1 Manager', 'L1 Employee Code', 'L2 Manager', 'L2 Employee Code'] );
        }
        foreach($history->data->questions as $question) {
            if (isset($question->type) && $question->type == 'hidden') {
                continue;
            }
            if (isset($question->type) && $question->type == 'multitextbox' && !empty($question->options)) {
                foreach ($question->options as $k => $v) {
                    $optLabel = is_object($v) ? ($v->display ?? $v->label ?? $k) : $v;
                    $headers[] = $optLabel.' ('.$question->label.')';
                }
            } else {
                $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->user_info->employee_code) ? $submission->user_info->employee_code : '';
            $row[] = isset($submission->workflow_status) ? $submission->workflow_status : '';
            foreach ($userAttrs as $attr) {
                $row[] = $this->userAttributeValue($submission->user_info ?? null, $attr);
            }
            foreach ($exportPositionColumns as $positionField) {
                $row[] = isset($submission->{$positionField}) ? $submission->{$positionField} : '';
            }
            if(isset($history->data) && isset($history->data->form) && isset($history->data->form->show_manager_details) && $history->data->form->show_manager_details === 'yes'){
                $row[] = isset($submission->manager1_name) ? $submission->manager1_name : '';
                $row[] = isset($submission->manager1_code) ? $submission->manager1_code : '';
                $row[] = isset($submission->manager2_name) ? $submission->manager2_name : '';
                $row[] = isset($submission->manager2_code) ? $submission->manager2_code : '';
            }
            foreach($history->data->questions as $q => $v) {
                if (isset($v->type) && $v->type == 'hidden') {
                    continue;
                }
                if (isset($v->type) && $v->type == 'multitextbox' && !empty($v->options)) {
                    foreach ($v->options as $optKey => $optMeta) {
                        $fieldKey = is_object($optMeta) ? ($optMeta->value ?? $optKey) : $optKey;
                        if (isset($submission->formdata->{$fieldKey})) {
                            $raw = $submission->formdata->{$fieldKey};
                            $row[] = is_array($raw) ? implode(', ', $raw) : (is_object($raw) ? json_encode($raw) : $raw);
                        } elseif (isset($submission->formdata->{$q}) && (is_object($submission->formdata->{$q}) || is_array($submission->formdata->{$q}))) {
                            $box = (array) $submission->formdata->{$q};
                            $raw = $box[$fieldKey] ?? '-';
                            $row[] = is_array($raw) ? implode(', ', $raw) : (is_object($raw) ? json_encode($raw) : $raw);
                        } else {
                            $row[] = '-';
                        }
                    }
                } else {
                    if (!isset($submission->formdata->{$q})) {
                        $row[] = '-';
                    } elseif (is_array($submission->formdata->{$q})) {
                        $row[] = implode(', ', $submission->formdata->{$q});
                    } elseif (is_object($submission->formdata->{$q})) {
                        $row[] = collect((array) $submission->formdata->{$q})->map(function ($val, $key) {
                            return $key.': '.$val;
                        })->implode(', ');
                    } else {
                        $row[] = $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 = 'support1@stratawiz.com';
            $data->subject = 'Attached Report';
            $data->body = '';
            $data->attachment = $report;
            $data->attachment_name = 'report.xlsx';

            Mail::to( $history->data->user_details[0]->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) {

        $fields = $request->input('fields', '');

        $params = [
        'hierarchy' => $request->input('hierarchy', ''),
        'partition' => $request->input('partition', ''),
        ];

        if (!empty($fields)) {
            $params['fields'] = $fields;
        }

        $response = LambdaRequest::getrequest(
            'contact',
            'contact/get_my_contacts',
            $params
        );

        Log::debug(print_r(['getdoctorlist'], true));
        Log::debug(print_r($response, true));


        // $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;
        if($post['form_id'] == '1718178830-d871301e-312b-4a60-nebmitra-15afa4ce6163' && in_array("1655449175-a39a5017-8232-4d58-NEBMITRAABM-90d06bc733d0", json_decode($user->roles) )) {
            $history = LambdaRequest::signedrequest('post', 'form', 'formentity/getallsubmissions', ['partition' => $post['partition'], 'form_id'=>$post['form_id'], 'hierarchy' => $user->hierarchy,  'filters' => json_encode($filters) ], 120);
        } else {
            $history = LambdaRequest::signedrequest('post', 'form', 'formentity/getallsubmissions', ['partition' => $post['partition'], 'form_id'=>$post['form_id'], 'limit' => 500, 'filters' => json_encode($filters) ], 360);
        }
        
        if ($post['form_id'] == '1713351143-9afc68f4-653f-491a-9e0e-a27d61ed1e07') {
            $codes = [
                'zadonase_tablets_10s',
                'zadonase_tablets_10s_camp',
                'quicnac_ab_tablets_100600_mg10s',
                'quicnac_ab_tablets_100600_mg10s_camp',
                'quicnac_tablets_600mg_10s',
                'quicnac_tablets_600mg_10s_camp',
                'pulmosmart_05_mg_pulmules_2_ml',
                'pulmosmart_05_mg_pulmules_2_ml_camp',
                'pulmosmart_1mg_pulmules_2_ml',
                'pulmosmart_1mg_pulmules_2_ml_camp',
                'budasure_l_05_mg_pulmules_2_ml',
                'budasure_l_05_mg_pulmules_2_ml_camp',
                'pulmosmart_200_pulmicaps_30s',
                'pulmosmart_200_pulmicaps_30s_camp',
                'pulmosmart_400_pulmicaps_30s',
                'pulmosmart_400_pulmicaps_30s_camp',
                'pulmosmart_dose_counter_mdi_200_inhaler',
                'pulmosmart_dose_counter_mdi_200_inhaler_camp',
                'pulmosmart_g',
                'pulmosmart_g_camp',
                'glycoquic_f',
                'glycoquic_f_camp',
                'iprasure_ls',
                'iprasure_ls_camp',
                'viloresp_200',
                'viloresp_200_camp',
                'pulmosmart_dose_counter_mdi_400_inhaler',
                'pulmosmart_dose_counter_mdi_400_inhaler_camp',
                'pulmosmart_pulmules_2_ml',
                'pulmosmart_pulmules_2_ml_camp',
                'innohaler_dpi_device',
                'innohaler_dpi_device_camp',
                'innospacer',
                'innospacer_camp',
                'budasure_pulmules_2ml',
                'budasure_pulmules_2ml_camp',
                'fibnib_capsules_100_10s',
                'fibnib_capsules_100_10s_camp',
                'fibnib_capsules_150_10s',
                'fibnib_capsules_150_10s_camp',
                'viloresp_pulmicaps_capsules_15_sale',
                'viloresp_pulmicaps_capsules_15_sale_camp',
                'iprasure_pulmules_25_ml',
                'iprasure_pulmules_25_ml_camp',
                'clearneb_pulmules_3_wv_4ml_amp',
                'clearneb_pulmules_3_wv_4ml_amp_camp',
                'glycoquic_pulmules_25mcg_2mlsales',
                'glycoquic_pulmules_25mcg_2mlsales_camp',
                'total_clinic_business',
                'total_clinic_business_camp',
                'total-camp-business_pts_value',
                'total-clinic-business_pts_value',
                'patient_rx_count',
                'patient_rx_count_camp',
                'total_competitor_business',
                'total_competitor_business_camp',
            ];
            if (isset($history->data->questions) && is_array($history->data->questions)) {
                $history->data->questions = array_values(array_filter($history->data->questions, function($que) use ($codes) {
                    return !in_array($que->code ?? null, $codes);
                }));
            }
        }


        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[] = isset($que->code) && isset($sub->{$que->code}) ? $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($history); 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();
        //echo '
'; print_r($user); exit;
        $post = ['partition' => 'rapport-'.$user->domain, 'form_id' => '1718178830-d871301e-312b-4a60-nebmitra-15afa4ce6163'];
        $filters = ["formdata.submission_status" => "Invoice Uploded"];
        if(in_array("1655449175-a39a5017-8232-4d58-NEBMITRAABM-90d06bc733d0", json_decode($user->roles) )) {
            $filters['hierarchy'] = $user->hierarchy;
            //$history = LambdaRequest::signedrequest('post', 'form', 'formentity/getallsubmissions', ['form_id' => $post['form_id'], 'partition' => $post['partition'], 'hierarchy' => $user->hierarchy], 120);
        } else {
            //$history = LambdaRequest::signedrequest('post', 'form', 'formentity/getallsubmissions', ['form_id' => $post['form_id'], 'partition' => $post['partition'], 'filters' => json_encode($filters)], 120);
        }
        $history = LambdaRequest::signedrequest('post', 'form', 'formentity/getallsubmissions', ['form_id' => $post['form_id'], 'partition' => $post['partition'], 'filters' => json_encode($filters)], 120);
        //echo '
'; print_r($history); 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);
        }

        //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']);
    }

    public function pulmocarecoachingtool(Request $request) {
        $type = $request->input('type', 'feedback');
        if($type == 'goal') {
            return view('pulmocarecoachingtool.'.$type);
        } else {
            return view('pulmocarecoachingtool.'.$type);
        }
    }

    public function read_invoices(Request $request) {
        $data = $request->all();

        $invoice = LambdaRequest::signedrequest('post', 'contact', 'contact/read_invoices', ['image_url' => 'https://did94hhhcgq1d.cloudfront.net'.str_replace('https://did94hhhcgq1d.cloudfront.net','', $data['image_url'])], 120);
        Log::debug(print_r($invoice, true));
        // $response = (object)[
        //     "status" => "success",
        //     "fields" => (object)[
        //         "name_of_chemist" => "DR G.M Dixit",
        //         "supply_from_stockist" => "Zufall; AND Pvt Ltd",
        //         "area" => "Vidhalan",
        //         "date" => "18/07 P.O"
        //     ],
        //     "products" => [
        //         (object)[
        //             "key" => "levolin-063-mg-respules",
        //             "value" => "LEVOLIN 0.63 MG RESPULE",
        //             "quantity" => "3 BOX"
        //         ],
        //         (object)[
        //             "key" => "budecort-respules-0",
        //             "value" => "BUDECORT 0.5 MG RESPULES",
        //             "quantity" => "3 BOX"
        //         ],
        //         (object)[
        //             "key" => "duolin-3-respule",
        //             "value" => "DUOLIN 3 RESPULES",
        //             "quantity" => "3 BOX"
        //         ],
        //         (object)[
        //             "key" => "budesal-1-mg-respules-2ml",
        //             "value" => "BUDESAL 1MG RESPULES",
        //             "quantity" => "1 BOX"
        //         ]
        //     ],
        //     "other" => [],
        //     "status" => "COMPLETE"
        // ];
    
        return Response::json($invoice->data->item);
    }

    /**
     * Show the Neb Mitra doctors list page with DataTable and export button
     */
    public function neb_mitra_doctors_list()
    {
        return view('form.doctors_list');
    }

    /**
     * Return JSON data for DataTables from team3_nebmitra_doctors
     */
    public function get_neb_mitra_doctors(Request $request)
    {
        $query = DB::table('team3_nebmitra_doctors');
        $user_id = $request->input('user_id');
        $all_data_access = $request->input('all_data_access');
        $role = $request->input('role');
        
        $neb1 = '1655449174-a39a5017-8232-4d58-a253-90d06bc733d0';
        $neb2 = '1655449175-a39a5017-8232-4d58-a253-90d06bc733d0';
        $nebarise = '1655449176-a39a5017-8232-4d58-a253-90d06bc733d0';      
        $nebmitraabm = '1655449175-a39a5017-8232-4d58-NEBMITRAABM-90d06bc733d0';
        
        if(isset($role) && ($role == $neb1 || $role == $neb2 || $role == $nebarise)){
            Log::debug(print_r(['user is neb abm'], true));
            $abm = DB::table('team3_nebmitra_to_abm_mapping')
                            ->select('mitra_user_id', 'mitra_hierarchy_id')
                            ->where('abm_user_id', $user_id)
                            ->get();
        }
        
        $hierarchy = LambdaRequest::getrequest('ums', 'hierarchy/hierarchy_below_me', ['partition' => 'rapport-team3', 'user_id' => $user_id ]);
        if($all_data_access != '1') {
            // Extract user_ids and hierarchy_ids from $hierarchy response
            $user_ids = [];
            $hierarchy_ids = [];
            if (isset($hierarchy->data->hierarchies) && is_array($hierarchy->data->hierarchies)) {
                
                if($role == $nebmitraabm){
                    foreach ($hierarchy->data->hierarchies as $hie) {
                Log::debug(print_r(['hierarchies abm and row'], true));

                        // Add owner id if present
                        if (isset($hie->owner) && !empty($hie->owner)) {
                            $user_ids[] = $hie->owner;
                        }
                        // Always add hierarchy id
                        if (isset($hie->id) && !empty($hie->id)) {
                            $hierarchy_ids[] = $hie->id;
                        }
                    }
                }else{
                    foreach($abm as $row){
                Log::debug(print_r(['inside abm and row'], true));

                        if (isset($row->mitra_user_id) && !empty($row->mitra_user_id)) {
                                $user_ids[] = $row->mitra_user_id;
                        }
                        if (isset($row->mitra_hierarchy_id) && !empty($row->mitra_hierarchy_id)) {
                                $hierarchy_ids[] = $row->mitra_hierarchy_id;
                        }
                    }
                }
                Log::debug(print_r(['user and hierar'], true));
                Log::debug(print_r($user_ids, true));
                Log::debug(print_r($hierarchy_ids, true));

                // Add OR conditions for user_id and hierarchy_id if any found
                if (!empty($user_ids) || !empty($hierarchy_ids)) {
                    $query->where(function($q) use ($user_ids, $hierarchy_ids) {
                        if (!empty($user_ids)) {
                            $q->orWhereIn('user_id', $user_ids);
                        }
                        if (!empty($hierarchy_ids)) {
                            $q->orWhereIn('hierarchy_id', $hierarchy_ids);
                        }
                    });
                }
            }
        }
        
        // DataTables server-side processing
        $search = $request->input('search.value');
        if ($search) {
            $query->where(function($q) use ($search) {
                $q->where('doctor_name', 'like', "%$search%")
                  ->orWhere('mobile_number', 'like', "%$search%")
                  ->orWhere('email_id', 'like', "%$search%")
                  ->orWhere('speciality', 'like', "%$search%")
                  ->orWhere('location', 'like', "%$search%")
                  ->orWhere('district', 'like', "%$search%")
                  ->orWhere('state', 'like', "%$search%")
                  ->orWhere('pincode', 'like', "%$search%")
                  ->orWhere('hq', 'like', "%$search%")
                  ->orWhere('legacy_code', 'like', "%$search%")
                  ->orWhere('uid', 'like', "%$search%")
                  ->orWhere('degree', 'like', "%$search%")
                  ->orWhere('gender', 'like', "%$search%")
                  ->orWhere('position_code', 'like', "%$search%")
                  ->orWhere('micro_interior', 'like', "%$search%")

                  ->orWhere('nebulizing', 'like', "%$search%")
                  ->orWhere('priority', 'like', "%$search%")
                  ->orWhere('competition', 'like', "%$search%")
                  ->orWhere('prescribed_brands', 'like', "%$search%")
                  ->orWhere('other_prescribed_brands', 'like', "%$search%")
                  ->orWhere('type_of_doctor_chemist', 'like', "%$search%")
                  ;
            });
        }

        $total = $query->count();

        // Paging
        $start = $request->input('start', 0);
        $length = $request->input('length', 10);
        $query->skip($start)->take($length);

        // Ordering
        if ($request->has('order')) {
            $columns = $request->input('columns');
            foreach ($request->input('order') as $order) {
                $colIdx = $order['column'];
                $dir = $order['dir'];
                $colName = $columns[$colIdx]['data'];
                $query->orderBy($colName, $dir);
            }
        }

        $data = $query->get();

        return response()->json([
            'draw' => intval($request->input('draw')),
            'recordsTotal' => $total,
            'recordsFiltered' => $total,
            'data' => $data,
        ]);
    }

    public function ajaxgetnebmitradocchem(Request $request)
    {
        $user_id = $request->input('user_id');

        $baseQuery = DB::table('team3_nebmitra_doctors')
            ->where('status', 1)
            ->where('user_id', $user_id);

        $totalRecords = $baseQuery->count();

        $query = DB::table('team3_nebmitra_doctors')
            ->where('status', 1)
            ->where('user_id', $user_id);

        $search = $request->input('search.value');
        if ($search) {
            $query->where(function ($q) use ($search) {
                $q->where('doctor_name', 'like', "%$search%")
                ->orWhere('mobile_number', 'like', "%$search%")
                ->orWhere('email_id', 'like', "%$search%")
                ->orWhere('speciality', 'like', "%$search%")
                ->orWhere('location', 'like', "%$search%")
                ->orWhere('district', 'like', "%$search%")
                ->orWhere('state', 'like', "%$search%")
                ->orWhere('pincode', 'like', "%$search%")
                ->orWhere('hq', 'like', "%$search%")
                ->orWhere('legacy_code', 'like', "%$search%")
                ->orWhere('uid', 'like', "%$search%")
                ->orWhere('degree', 'like', "%$search%")
                ->orWhere('gender', 'like', "%$search%")
                ->orWhere('position_code', 'like', "%$search%")
                ->orWhere('micro_interior', 'like', "%$search%");
            });
        }

        $filteredRecords = $query->count();

        $start = $request->input('start', 0);
        $length = $request->input('length', 10);
        $query->skip($start)->take($length);

        if ($request->has('order')) {
            $columns = $request->input('columns');
            foreach ($request->input('order') as $order) {
                $colIdx = $order['column'];
                $dir = $order['dir'];
                $colName = $columns[$colIdx]['data'];
                $query->orderBy($colName, $dir);
            }
        }

        $data = $query->get();

        return response()->json([
            'draw' => intval($request->input('draw')),
            'recordsTotal' => $totalRecords,
            'recordsFiltered' => $filteredRecords,
            'data' => $data,
        ]);
    }

    public function exportnebmitradocchem(Request $request)
    {
        $user_id = $request->input('user_id');

        $filename = 'doctors_export_' . date('Ymd_His') . '.csv';

        $columns = [
            'id',
            'legacy_code',
            'type',
            'nebulizing',
            'priority',
            'competition',
            'prescribed_brands',
            'other_prescribed_brands',
            'type_of_doctor_chemist',
            'doctor_name',
            'mobile_number',
            'email_id',
            'speciality',
            'degree',
            'gender',
            'no_of_visit',
            'location',
            'district',
            'state',
            'pincode',
            'hq',
            'micro_interior',
            'position_code'
        ];

        $headers = [
            'ID',
            'Legacy Code',
            'Type',
            'Nebulizing',
            'Priority',
            'Competition',
            'Preferred Brands',
            'Other Preferred Brands',
            'Type of Doctor/Chemist',
            'Doctor/Chemist Name',
            'Mobile Number',
            'Email ID',
            'Speciality',
            'Degree',
            'Gender',
            'No. of Visits',
            'Location',
            'District',
            'State',
            'Pincode',
            'HQ',
            'Micro Interior',
            'Position Code'
        ];

        $callback = function () use ($user_id, $columns, $headers) {

            $file = fopen('php://output', 'w');
            fputcsv($file, $headers);

            // 🔹 SAME BASE QUERY AS AJAX
            $query = DB::table('team3_nebmitra_doctors')
                ->select($columns)
                ->where('user_id', $user_id);

            // 🔹 SAME SEARCH LOGIC
            if (!empty(request('search'))) {
                $search = request('search');
                $query->where(function ($q) use ($search) {
                    $q->where('doctor_name', 'like', "%$search%")
                    ->orWhere('mobile_number', 'like', "%$search%")
                    ->orWhere('email_id', 'like', "%$search%")
                    ->orWhere('speciality', 'like', "%$search%")
                    ->orWhere('location', 'like', "%$search%")
                    ->orWhere('district', 'like', "%$search%")
                    ->orWhere('state', 'like', "%$search%")
                    ->orWhere('pincode', 'like', "%$search%")
                    ->orWhere('hq', 'like', "%$search%")
                    ->orWhere('legacy_code', 'like', "%$search%")
                    ->orWhere('uid', 'like', "%$search%")
                    ->orWhere('degree', 'like', "%$search%")
                    ->orWhere('gender', 'like', "%$search%")
                    ->orWhere('position_code', 'like', "%$search%")
                    ->orWhere('micro_interior', 'like', "%$search%");
                });
            }

            $rows = $query->get();

            foreach ($rows as $row) {
                fputcsv($file, (array) $row);
            }

            fclose($file);
        };

        return response()->streamDownload($callback, $filename, [
            'Content-Type' => 'text/csv',
            'Cache-Control' => 'no-store, no-cache',
        ]);
    }

    public function ajaxupdatenebmitradoctors(Request $request)
    {
        $res = DB::table('team3_nebmitra_doctors')
            ->where('id', $request->doctor_id)
            ->update([
                'doctor_name' => $request->input('doctor_name'),
                'mobile_number' => $request->input('mobile_number'),
                'email_id' => $request->input('email_id'),
                'speciality' => $request->input('speciality'),
                'degree' => $request->input('degree'),
                'gender' => $request->input('gender'),
                'location' => $request->input('location'),
                'micro_interior' => $request->input('micro_interior'),
                
                'nebulizing' => $request->nebulizing,
                'priority' => $request->priority,
                'competition' => $request->competition,
                'prescribed_brands' => !empty($request->brands)
                    ? implode(',', $request->brands)
                    : null,
                'other_prescribed_brands' => $request->other_prescribed_brands ?: null,
                'type_of_doctor_chemist' => $request->userType,
                'is_edited' => 1
            ]);

        return response()->json(['status' => 'success', 'data' => $res]);
    }



    /**
     * Export all doctors as CSV
     */
    public function export_neb_mitra_doctors(Request $request)
    {
        Log::debug('=== EXPORT START ===');

        Log::debug('Request payload', $request->all());

        $filename = 'doctors_export_' . date('Ymd_His') . '.csv';

        $columns = [
            'id', 'legacy_code', 'type', 'status', 'nebulizing', 'priority', 'competition',
            'prescribed_brands', 'other_prescribed_brands',
            'type_of_doctor_chemist', 'doctor_name', 'mobile_number', 'email_id',
            'speciality', 'degree', 'gender', 'no_of_visit', 'location', 'district',
            'state', 'pincode', 'hq', 'micro_interior', 'position_code',
            'date_added', 'no_of_followups', 'last_followup_date'
        ];

        $headers = [
            'ID', 'Legacy Code', 'Type', 'Status', 'Nebulizing', 'Priority', 'Competition',
            'Preferred Brands of respules', 'Other Preferred Brands of respules',
            'Type of Doctor/Chemist', 'Doctor/Chemist Name', 'Mobile Number',
            'Email ID', 'Speciality', 'Degree', 'Gender', 'No. of Visits',
            'Location', 'District', 'State', 'Pincode', 'HQ', 'Micro Interior',
            'Position Code', 'Date Added', 'No. of Followups', 'Last Followup Date'
        ];

        $user_id = $request->input('user_id');
        $role = $request->input('role');
        $all_data_access = $request->input('all_data_access');

        Log::debug('User context', compact('user_id', 'role', 'all_data_access'));

        $neb1 = '1655449174-a39a5017-8232-4d58-a253-90d06bc733d0';
        $neb2 = '1655449175-a39a5017-8232-4d58-a253-90d06bc733d0';
        $nebarise = '1655449176-a39a5017-8232-4d58-a253-90d06bc733d0';
        $nebmitraabm = '1655449175-a39a5017-8232-4d58-NEBMITRAABM-90d06bc733d0';

        $abm = collect();

        if ($role == $neb1 || $role == $neb2 || $role == $nebarise) {
            Log::debug('Role matched NEB ABM');

            $abm = DB::table('team3_nebmitra_to_abm_mapping')
                ->select('mitra_user_id', 'mitra_hierarchy_id')
                ->where('abm_user_id', $user_id)
                ->get();

            Log::debug('ABM mappings count: ' . $abm->count());
        }

        Log::debug('Calling hierarchy API');

        $hierarchy = LambdaRequest::getrequest(
            'ums',
            'hierarchy/hierarchy_below_me',
            ['partition' => 'rapport-team3', 'user_id' => $user_id]
        );

        Log::debug('Hierarchy API response', (array) $hierarchy);

        $callback = function () use (
            $columns,
            $headers,
            $role,
            $nebmitraabm,
            $abm,
            $hierarchy,
            $all_data_access
        ) {
            try {

                Log::debug('--- STREAM CALLBACK START ---');

                $file = fopen('php://output', 'w');
                fputcsv($file, $headers);

                $rows = DB::table('team3_nebmitra_doctors')->select($columns);

                Log::debug('Base query created');

                if ($all_data_access != '1') {

                    Log::debug('Applying hierarchy filter');

                    $user_ids = [];
                    $hierarchy_ids = [];

                    if (isset($hierarchy->data->hierarchies) && is_array($hierarchy->data->hierarchies)) {

                        Log::debug('Hierarchy count: ' . count($hierarchy->data->hierarchies));

                        if ($role == $nebmitraabm) {
                            Log::debug('Role = NEB MITRA ABM');

                            foreach ($hierarchy->data->hierarchies as $hie) {
                                Log::debug('Hierarchy row', (array) $hie);

                                if (!empty($hie->owner)) {
                                    $user_ids[] = $hie->owner;
                                }
                                if (!empty($hie->id)) {
                                    $hierarchy_ids[] = $hie->id;
                                }
                            }
                        } else {
                            Log::debug('Role = NEB ABM');

                            foreach ($abm as $row) {
                                Log::debug('ABM row', (array) $row);

                                if (!empty($row->mitra_user_id)) {
                                    $user_ids[] = $row->mitra_user_id;
                                }
                                if (!empty($row->mitra_hierarchy_id)) {
                                    $hierarchy_ids[] = $row->mitra_hierarchy_id;
                                }
                            }
                        }
                    } else {
                        Log::warning('Hierarchy data missing or invalid');
                    }

                    Log::debug('Collected filters', [
                        'user_ids' => $user_ids,
                        'hierarchy_ids' => $hierarchy_ids
                    ]);

                    if (!empty($user_ids) || !empty($hierarchy_ids)) {
                        $rows->where(function ($q) use ($user_ids, $hierarchy_ids) {
                            if (!empty($user_ids)) {
                                $q->orWhereIn('user_id', $user_ids);
                            }
                            if (!empty($hierarchy_ids)) {
                                $q->orWhereIn('hierarchy_id', $hierarchy_ids);
                            }
                        });
                    }
                }

                Log::debug('Final SQL', [$rows->toSql(), $rows->getBindings()]);

        $rows->orderBy('id')->chunk(500, function ($chunk) use ($file) {
            Log::debug('Writing chunk of size: ' . $chunk->count());

            foreach ($chunk as $row) {
                $exportRow = (array) $row;
                if (array_key_exists('status', $exportRow)) {
                    $exportRow['status'] = ((int) $exportRow['status'] === 1) ? 'Active' : 'Inactive';
                }
                fputcsv($file, $exportRow);
            }
        });


            fclose($file);

            Log::debug('--- STREAM CALLBACK END ---');

        } catch (\Throwable $e) {
            Log::error('EXPORT FAILED', [
                'message' => $e->getMessage(),
                'line'    => $e->getLine(),
                'file'    => $e->getFile(),
                'trace'   => $e->getTraceAsString(),
            ]);
        }
    };

    return response()->streamDownload($callback, $filename, [
        'Content-Type' => 'text/csv',
        'Cache-Control' => 'no-store, no-cache',
    ]);
}



    public function delete_doctor_ajax(Request $request)
    {
        // Validate CSRF token (handled by Laravel middleware by default)
        $id = $request->input('id');
        $type = $request->input('type');

        if (!$id || !$type) {
            return response()->json(['status' => 'failure', 'message' => 'ID and type are required']);
        }

        try {
            // Only allow doctor or chemist types for safety
            if (!in_array($type, ['doctor', 'chemist'])) {
                return response()->json(['status' => 'failure', 'message' => 'Invalid type']);
            }

            $affected = DB::table('team3_nebmitra_doctors')
                ->where('id', $id)
                ->where('type', $type)
                ->update(['status' => 0]);

            $neb_contact = DB::table('team3_nebmitra_doctors')
                        ->select('contact_id')
                        ->where('id', $id)
                        ->where('type', $type)
                        ->first();

            if ($neb_contact && !empty($neb_contact->contact_id)) {
                $contact_id = $neb_contact->contact_id;
                $domain = 'team3';
                $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);
            }
            
            if ($affected) {
                return response()->json(['status' => 'success']);
            } else {
                return response()->json(['status' => 'failure', 'message' => 'Doctor not found or already deleted']);
            }
        } catch (\Exception $e) {
            return response()->json(['status' => 'failure', 'message' => $e->getMessage()]);
        }
    }

    public function getnebcountajax(Request $request)
    {
        $mslCode = $request->input('mslcode');

        if (!$mslCode) {
            return response()->json([
                'status' => 'failure', 
                'message' => 'MSL Code is required'
            ]);
        }

        try {

            $data = DB::table('neblogistic')
                ->select('no_of_nebulizer')
                ->where('msl_code', $mslCode)
                ->whereMonth('created_at', date('m'))
                ->whereYear('created_at', date('Y'))
                ->whereIn('status', ['Requested', 'L1 Approved', 'Approved'])
                ->sum('no_of_nebulizer');

            return response()->json([
                'status' => 'success',
                'message' => 'Neblogistics Count',
                'count'   => $data
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'status' => 'failure', 
                'message' => $e->getMessage()
            ]);
        }
    }

    public function imagewithgeolocation(Request $request)
    {
        try {
            if (!$request->boolean('upload_only')) {
                return response()->json(['status' => 'ignored']);
            }

            $fname   = 'upload_photo';
            $formId  = $request->input('form_id');
            $address = $request->input('geolocation_address');
            $font    = storage_path('app/fonts/arial.ttf');

            if (!$request->hasFile($fname)) {
                return response()->json(['status' => 'error', 'message' => 'File not found'], 422);
            }

            $file = $request->file($fname);
            if (!$file->isValid()) {
                return response()->json(['status' => 'error', 'message' => 'Invalid file'], 422);
            }

            $relativePath = $this->_uploadMediaLocal(
                $request,
                $fname,
                'public/geolocationproject/' . $formId . '/' . $fname
            );

            $relativePath = str_replace('storage/', 'public/', $relativePath);
            $imagePath = storage_path('app/' . $relativePath);

            if (!file_exists($imagePath)) {
                throw new \Exception('Image not found: ' . $imagePath);
            }

            $mime = mime_content_type($imagePath);
            if (in_array($mime, ['image/jpeg', 'image/jpg'])) {
                $img = imagecreatefromjpeg($imagePath);
            } elseif ($mime === 'image/png') {
                $img = imagecreatefrompng($imagePath);
            } else {
                throw new \Exception("Unsupported image type: $mime");
            }

            $mime = mime_content_type($imagePath);
            if (in_array($mime, ['image/jpeg', 'image/jpg'])) {
                $img = imagecreatefromjpeg($imagePath);

                /* FIX CAMERA ROTATION (EXIF) */
                $exif = @exif_read_data($imagePath);
                if (!empty($exif['Orientation'])) {
                    switch ($exif['Orientation']) {
                        case 3:
                            $img = imagerotate($img, 180, 0);
                            break;
                        case 6:
                            $img = imagerotate($img, -90, 0);
                            break;
                        case 8:
                            $img = imagerotate($img, 90, 0);
                            break;
                    }
                }

            } elseif ($mime === 'image/png') {
                $img = imagecreatefrompng($imagePath);
            } else {
                throw new \Exception("Unsupported image type: $mime");
            }


            // $color = imagecolorallocate($img, 255, 255, 255);
            // imagettftext(
            //     $img,
            //     16,
            //     0,
            //     20,
            //     imagesy($img) - 20,
            //     $color,
            //     $font,
            //     $address
            // );

            // 
            
            $imgWidth  = imagesx($img);
            $imgHeight = imagesy($img);

            $fontSize = intval($imgHeight * 0.037);
            $fontSize = max(34, min($fontSize, 120));

            $paddingX = intval($imgWidth * 0.07);
            $paddingY = intval($imgHeight * 0.05);

            do {
                $usableWidth = $imgWidth - ($paddingX * 2) - 6;
                $maxCharsPerLine = intval($usableWidth / ($fontSize * 0.6));

                $wrappedText = wordwrap($address, $maxCharsPerLine, "\n");
                $lines = explode("\n", $wrappedText);

                $lineHeight = intval($fontSize * 1.35);
                $totalTextHeight = count($lines) * $lineHeight;

                if ($totalTextHeight > ($imgHeight - ($paddingY * 2))) {
                    $fontSize -= 1;
                } else {
                    break;
                }
            } while ($fontSize > 22);

            $y = $imgHeight - $paddingY - $totalTextHeight;
            $y = max($paddingY, $y);

            $color = imagecolorallocate($img, 255, 255, 255);

            foreach ($lines as $line) {
                $bbox = imagettfbbox($fontSize, 0, $font, $line);

                $minX = min($bbox[0], $bbox[2], $bbox[4], $bbox[6]);
                $maxX = max($bbox[0], $bbox[2], $bbox[4], $bbox[6]);
                $textWidth = $maxX - $minX;

                $x = intval(($imgWidth - $textWidth) / 2) - $minX;

                if ($x < $paddingX) {
                    $x = $paddingX;
                }

                if (($x + $textWidth) > ($imgWidth - $paddingX)) {
                    $x = $imgWidth - $paddingX - $textWidth;
                }

                imagettftext(
                    $img,
                    $fontSize,
                    0,
                    $x,
                    $y,
                    $color,
                    $font,
                    $line
                );

                $y += $lineHeight;
            }


            // 


            /* ---------- DATE TIME STAMP (FIXED) ---------- */

            date_default_timezone_set('Asia/Kolkata');

            $dateText = date('d M Y, h:i A');

            /* Slightly larger, readable */
            $dateFontSize = $fontSize;
            // max(22, intval($fontSize * 0.65) + 3);

            /* Align with address visual start */
            $dateX = $paddingX;

            /* Place below last address line */
            $dateY = $y + intval($dateFontSize * 1.2);

            /* Keep inside image */
            if ($dateY > ($imgHeight - $paddingY)) {
                $dateY = $imgHeight - $paddingY;
            }

            $dateColor = imagecolorallocate($img, 235, 235, 235);

            imagettftext(
                $img,
                $dateFontSize,
                0,
                $dateX,
                $dateY,
                $dateColor,
                $font,
                $dateText
            );

            /* ------------------------------------------------ */


            imagepng($img, $imagePath);
            $stampedFile = new \Illuminate\Http\UploadedFile(
                $imagePath,
                basename($imagePath),
                'image/png',
                null,
                true
            );

            $folder = 'form/' . $formId . '/' . $fname;
            $path = $stampedFile->store($folder, 's3');
            $path = env('AWS_URL') . '/' . $path;

            return response()->json([
                'status' => 'success',
                'data' => [
                    $fname => $path
                ]
            ]);

        } catch (\Throwable $e) {
            Log::error('Image upload failed', [
                'message' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
            ]);

            return response()->json([
                'status' => 'error',
                'message' => 'Unexpected error occurred.'
            ], 500);
        }
    }

    public function customdataandvideoform(Request $request)
    {
        Log::info("===== customdataandvideoform START =====");
        Log::info("Request ID: " . uniqid("video_upload_"));

        try {
                            
            $post = $request->except('_token');
            $formdata = $request->session()->get('formdata');
            if (empty(trim($post['orignal_doctor_name'] ?? '')) && empty(trim($post['name_of_other_doctor'] ?? '')))
            {
                return response()->json(['status'=>'failure','message'=>'Doctor name is required']);
            } 

            Log::info("Incoming POST data keys: " . implode(",", array_keys($post)));
            Log::info("Formdata from session: " . print_r($formdata, true));

            $file_doctorname = $post['orignal_doctor_name'] != ''
                ? $post['orignal_doctor_name']
                : ($post['name_of_other_doctor'] ?? 'unknown');

            $file_doctorname = preg_replace('/[^A-Za-z0-9_-]/', '_', $file_doctorname);
            $file_doctorname = trim($file_doctorname, '_');

            $path = '';
            $name = 'upload_video';
            $folder = 'video';

            // ✅ Log file presence
            Log::info("Checking file input: {$name}");
            Log::info("hasFile({$name}): " . ($request->hasFile($name) ? 'YES' : 'NO'));

            if ($request->hasFile($name)) {

                $file = $request->file($name);

                Log::info("File found. Valid: " . ($file->isValid() ? 'YES' : 'NO'));

                if (!$file->isValid()) {
                    Log::error("File upload invalid. Error code: " . $file->getError());
                    return response()->json(['status' => 'failure', 'message' => 'Invalid video file upload']);
                }

                $ext = $file->getClientOriginalExtension();
                $originalName = $file->getClientOriginalName();
                $mime = $file->getMimeType();
                $size = $file->getSize();

                Log::info("File details => OriginalName: {$originalName}, Ext: {$ext}, Mime: {$mime}, Size(bytes): {$size}");

                $customFileName = $post['employee_code'] . '_' . $file_doctorname . '.' . $ext;

                Log::info("Custom filename generated: {$customFileName}");
                Log::info("Uploading to disk: s3 | folder: {$folder}");

                // Store file temporarily locally
                $localTmpDir = storage_path('app/tmp_video_uploads');
                if (!file_exists($localTmpDir)) {
                    mkdir($localTmpDir, 0777, true);
                }
                $localTmpPath = $localTmpDir . '/' . $customFileName;
                $file->move($localTmpDir, $customFileName);

                // Use ffprobe to get video dimensions and rotation metadata
                $ffprobeCmd = "ffprobe -v error -select_streams v:0 -show_entries stream=width,height:stream_tags=rotate:side_data=rotation,displaymatrix -of json " . escapeshellarg($localTmpPath);
                $ffprobeOutput = shell_exec($ffprobeCmd);
                Log::info("ffprobe output length: " . strlen($ffprobeOutput));
                
                $video_width = null;
                $video_height = null;
                
                if ($ffprobeOutput) {
                    $data = json_decode($ffprobeOutput, true);
                    
                    if (json_last_error() === JSON_ERROR_NONE && isset($data['streams'][0])) {
                        $stream = $data['streams'][0];
                        $video_width = isset($stream['width']) ? (int)$stream['width'] : null;
                        $video_height = isset($stream['height']) ? (int)$stream['height'] : null;
                        
                        $originalWidth = $video_width;
                        $originalHeight = $video_height;
                        
                        // Check for rotation in multiple places
                        $rotationValue = null;
                        
                        // First check side_data rotation (more accurate)
                        if (isset($stream['side_data_list'])) {
                            foreach ($stream['side_data_list'] as $sideData) {
                                if (isset($sideData['rotation'])) {
                                    $rotationValue = (int)$sideData['rotation'];
                                    Log::info("Found rotation in side_data: {$rotationValue}°");
                                    break;
                                }
                            }
                        }
                        
                        // Fallback to stream tags if side_data not found
                        if ($rotationValue === null && isset($stream['tags']['rotate'])) {
                            $rotationValue = (int)$stream['tags']['rotate'];
                            Log::info("Found rotation in stream tags: {$rotationValue}°");
                        }
                        
                        // If rotation is 90 or 270 degrees, swap width and height
                        if ($rotationValue !== null) {
                            $normalizedRotation = $rotationValue % 360;
                            if ($normalizedRotation < 0) {
                                $normalizedRotation += 360;
                            }
                            
                            Log::info("Rotation value: {$rotationValue}°, Normalized: {$normalizedRotation}°");
                            
                            // 90 or 270 degrees means portrait orientation - swap dimensions
                            if ($normalizedRotation == 90 || $normalizedRotation == 270) {
                                $temp = $video_width;
                                $video_width = $video_height;
                                $video_height = $temp;
                                Log::info("Video rotation detected: {$rotationValue}° (normalized: {$normalizedRotation}°), swapped dimensions from {$originalWidth}x{$originalHeight} to {$video_width}x{$video_height}");
                            }
                        }
                        
                        $dimensions = "{$video_width}x{$video_height}";
                        Log::info("Final video dimensions after rotation check: {$dimensions}");
                    } else {
                        // Fallback to simple ffprobe if JSON parsing fails
                        Log::warning("JSON parsing failed, falling back to simple ffprobe");
                        $ffprobeCmdSimple = "ffprobe -v error -select_streams v:0 -show_entries stream=width,height -of csv=p=0:s=x " . escapeshellarg($localTmpPath);
                        $dimensions = trim(shell_exec($ffprobeCmdSimple));
                        if ($dimensions && strpos($dimensions, 'x') !== false) {
                            $parts = explode('x', $dimensions);
                            $video_width = isset($parts[0]) ? (int)$parts[0] : null;
                            $video_height = isset($parts[1]) ? (int)$parts[1] : null;
                        }
                    }
                } else {
                    Log::warning("ffprobe returned no output");
                }

                // Now store the file to S3 using Laravel's storage
                $storedPath = null;
                try {
                    $storedPath = Storage::disk('s3')->putFileAs($folder, new \Illuminate\Http\File($localTmpPath), $customFileName);
                } catch (\Exception $ex) {
                    Log::error("Exception during S3 upload after ffprobe: " . $ex->getMessage());
                    // Clean up temp file
                    @unlink($localTmpPath);
                    return response()->json(['status' => 'failure', 'message' => 'S3 upload failed after ffprobe']);
                }
                // Clean up temp file after S3 upload
                @unlink($localTmpPath);
                // ✅ Try storing
                
                //$storedPath = $file->storeAs($folder, $customFileName, 's3');

                Log::info("storeAs() returned path: " . print_r($storedPath, true));

                if (!$storedPath) {
                    Log::error("storeAs failed: storedPath empty/null");
                    return response()->json(['status' => 'failure', 'message' => 'S3 upload failed']);
                }

                // Optional: check if file exists in S3 after upload
                $exists = Storage::disk('s3')->exists($storedPath);
                Log::info("S3 exists check: " . ($exists ? "YES" : "NO"));

                $path = env('AWS_URL') . '/' . $storedPath;
                Log::info("Final video URL saved: {$path}");

                $post['upload_video'] = $path;

            } else {
                Log::warning("No file uploaded in request for '{$name}'");
            }

            // Keep session data
            $request->session()->put('formdata', $formdata);

            if (isset($formdata) && !empty($formdata) && $formdata->user_id != '') {

                Log::info("Processing form data for submission...");
                $post = $this->processformdata($formdata->form_id, $post, $formdata->user_id, $formdata->partition);

                Log::info("Processed post payload: " . 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::info("Lambda response: " . print_r($finfo, true));

                // Call vgreet/job_create with required params using real video dimensions
                // Note: video_width and video_height are already extracted above with rotation handling

                $personalisation = [
                    "portrait_frame_image" => "/vgreet/frames/vitaliss_frame_portrait.png",
                    "landscape_video_dimensions" => [
                        "width" => 1422,
                        "height" => 800
                    ],
                    "type" => "video_frame",
                    "portrait_video_dimensions" => [
                        "width" => 800,
                        "height" => 1422
                    ],
                    "landscape_frame_image" => "/vgreet/frames/vitaliss_frame_landscape.png"
                ];

                // Determine portrait or landscape based on video dimensions
                $orientation = null;
                if ($video_width && $video_height) {
                    if ($video_height > $video_width) {
                        $orientation = 'portrait';
                        $frame_image = isset($personalisation['portrait_frame_image'])
                            ? (strpos($personalisation['portrait_frame_image'], 's3://') === 0
                                ? $personalisation['portrait_frame_image']
                                : "s3://rapportapp" . $personalisation['portrait_frame_image'])
                            : "s3://rapportapp/vgreet/frames/vitaliss_frame_portrait.png";
                        $frame_width = isset($personalisation['portrait_video_dimensions']['width'])
                            ? $personalisation['portrait_video_dimensions']['width']
                            : 1422;
                        $frame_height = isset($personalisation['portrait_video_dimensions']['height'])
                            ? $personalisation['portrait_video_dimensions']['height']
                            : 800;
                        $fontSize = 15; // tune as needed
                    } else {
                        $orientation = 'landscape';
                        $frame_image = isset($personalisation['landscape_frame_image'])
                            ? (strpos($personalisation['landscape_frame_image'], 's3://') === 0
                                ? $personalisation['landscape_frame_image']
                                : "s3://rapportapp" . $personalisation['landscape_frame_image'])
                            : "s3://rapportapp/vgreet/frames/vitaliss_frame_landscape.png";
                        $frame_width = isset($personalisation['landscape_video_dimensions']['width'])
                            ? $personalisation['landscape_video_dimensions']['width']
                            : 800;
                        $frame_height = isset($personalisation['landscape_video_dimensions']['height'])
                            ? $personalisation['landscape_video_dimensions']['height']
                            : 1422;
                        $fontSize = 20; // tune as needed
                    }
                }

                // Extract 'orignal_doctor_name' from $finfo's formdata if available
                $doctor_name = null;
                if (
                    isset($finfo->data->submission->formdata) &&
                    is_array($finfo->data->submission->formdata) &&
                    array_key_exists('orignal_doctor_name', $finfo->data->submission->formdata)
                ) {
                    $doctor_name = 'Doctor: ' . $finfo->data->submission->formdata['orignal_doctor_name'] . ' | City: ' . $finfo->data->submission->formdata['city'];
                } elseif (
                    isset($finfo->data->submission->formdata) &&
                    is_object($finfo->data->submission->formdata) &&
                    property_exists($finfo->data->submission->formdata, 'orignal_doctor_name')
                ) {
                    $doctor_name = 'Doctor: ' . $finfo->data->submission->formdata->orignal_doctor_name . ' | City: ' . $finfo->data->submission->formdata->city;
                }

                // For this POC, we will log the expected operations:
                Log::info("Video orientation: " . ($orientation ?? 'unknown'));
                Log::info("Frame image to use: " . ($frame_image ?? 'none'));

                // Set default font path (ensure this exists on your server or container)
                $fontPath = storage_path('app/fonts/Poppins-Medium.ttf');
                $processedFrameS3Path = null; // Initialize variable for processed frame S3 path

                if ($doctor_name && isset($frame_image) && file_exists($fontPath)) {
                    // Download frame image from S3 to a temp location using Laravel Storage
                    $s3_relative_path = str_replace('s3://rapportapp/', '', $frame_image);
                    $frameTmpPath = sys_get_temp_dir() . '/' . uniqid('frame_') . '.png';

                    try {
                        // Use Laravel Storage instead of AWS S3 client
                        $frameContent = Storage::disk('s3')->get($s3_relative_path);
                        file_put_contents($frameTmpPath, $frameContent);
                        
                        // Load image with transparency preservation
                        $im = imagecreatefrompng($frameTmpPath);
                        if ($im) {
                            // Enable alpha blending and save alpha channel to preserve transparency
                            imagealphablending($im, false);
                            imagesavealpha($im, true);
                            
                            $fontSize = 18; // tune as needed
                            $fontColorRGB = [255, 255, 255]; // white

                            // Get text bounding box to calculate center
                            $bbox = imagettfbbox($fontSize, 0, $fontPath, $doctor_name);
                            $textWidth = $bbox[2] - $bbox[0];
                            $centerX = ($frame_width / 2) - ($textWidth / 2);

                            // Enable alpha blending for text rendering
                            imagealphablending($im, true);
                            
                            // Print text at (centerX, y=50)
                            $color = imagecolorallocate($im, $fontColorRGB[0], $fontColorRGB[1], $fontColorRGB[2]);
                            imagettftext($im, $fontSize, 0, $centerX, 50, $color, $fontPath, $doctor_name);

                            // Disable alpha blending before saving to preserve transparency
                            imagealphablending($im, false);
                            imagesavealpha($im, true);

                            // Save new image to temp location with transparency
                            $outputFrame = sys_get_temp_dir() . '/' . uniqid('doctor_frame_') . '.png';
                            imagepng($im, $outputFrame, 9); // Use compression level 9 (0-9, 9 is best quality)
                            imagedestroy($im);
                            Log::info("Doctor name '$doctor_name' printed on frame: $outputFrame");
                            
                            // Upload processed frame back to S3
                            try {
                                $processedFrameName = 'processed_' . uniqid() . '_' . $file_doctorname . '.png';
                                $uploadedPath = Storage::disk('s3')->putFileAs(
                                    'vgreet/frames',
                                    new \Illuminate\Http\File($outputFrame),
                                    $processedFrameName
                                );
                                
                                // Get full S3 URL
                                $processedFrameS3Path = env('AWS_URL') . '/' . $uploadedPath;
                                Log::info("Processed frame uploaded to S3: $processedFrameS3Path");
                                
                                // Clean up temp files
                                @unlink($outputFrame);
                                @unlink($frameTmpPath);
                            } catch (\Exception $uploadEx) {
                                Log::error("Failed to upload processed frame to S3: " . $uploadEx->getMessage());
                                @unlink($outputFrame);
                                @unlink($frameTmpPath);
                            }
                        } else {
                            Log::warning("Could not load image from '$frameTmpPath'");
                            @unlink($frameTmpPath);
                        }
                    } catch (\Exception $ex) {
                        Log::error("Failed to fetch or process frame image: " . $ex->getMessage());
                        @unlink($frameTmpPath ?? '');
                    }
                } else {
                    Log::info("Doctor name or frame or font file not available, skipping dynamic frame creation.");
                }

                $user_partition = !empty($finfo->data->submission->partition) ? explode('-', $finfo->data->submission->partition)[0] . '-' . explode('-', $finfo->data->submission->partition)[1] : null;
                $jobParams = [
                    'video_id' => "1770791678-532ce634-58ef-4662-89b3-8aad4ddcfcd8",
                    'video_file_url' => $path, // S3 link of the uploaded video
                    'video_width' => $video_width,
                    'video_height' => $video_height,
                    'reference_entity' => 'form_submission',
                    'reference_id' => $finfo->data->submission->id ?? null,
                    'reference_partition' => $finfo->data->submission->partition ?? null,
                    'reference_to_update' => 'processed_video',
                    'reference_updated_flag' => 'has_video_processed',
                    'user_info' => $finfo->data->submission->user_info ?? null,
                    'user_partition' => $user_partition
                ];
                
                // Add processed frame path to jobParams if available
                if ($processedFrameS3Path) {
                    $jobParams['processed_frame_url'] = $processedFrameS3Path;
                }

                Log::info("Calling vgreet/job_create payload: " . print_r($jobParams, true));

                //return response()->json(['status' => 'failure', 'jobParams' => $jobParams, 'finfo' => $finfo]);
                $vgreetJobResp = LambdaRequest::postrequest(
                    'vgreet',
                    'job/create',
                    $jobParams
                );
                Log::info("vgreet/job_create response: " . print_r($vgreetJobResp, true));

                if ($finfo->status == 'success') {
                    Log::info("===== customdataandvideoform SUCCESS =====");
                    return response()->json(['status' => 'success']);
                } else {
                    Log::error("Lambda submission failed. Status: {$finfo->status}");

                    if (isset($finfo->statusCode) && $finfo->statusCode == 401) {
                        return response()->json(['status' => 'failure', 'message' => $finfo->data]);
                    }

                    return response()->json(['status' => 'failure']);
                }

            } else {
                Log::error("Session formdata missing or user_id empty");
                return response()->json(['status' => 'failure']);
            }

        } catch (\Throwable $e) {
            Log::error("Exception in customdataandvideoform: " . $e->getMessage());
            Log::error($e->getTraceAsString());

            return response()->json([
                'status' => 'failure',
                'message' => 'Server error during upload'
            ]);
        }
    }


    public function team2bfeducators(Request $request)
    {
        $region = trim((string) $request->input('region', ''));
        if ($region === '') {
            return response()->json([]);
        }

        $users = DB::table('team2_bf_educators')
            ->whereRaw('UPPER(region) = ?', [strtoupper($region)])
            ->select('name_of_employee', 'employee_code', 'designation')
            ->orderBy('name_of_employee')
            ->get();

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

    /**
     * Leaderboard stats may be keyed by metric id or by display/title (e.g. unique_new combined metrics).
     */
    protected function leaderboardStatValue($stats, $metric)
    {
        if (!$stats) {
            return 0;
        }
        $metricKey = is_object($metric) ? ($metric->metric ?? '') : ($metric['metric'] ?? '');
        $displayKey = is_object($metric) ? ($metric->display ?? '') : ($metric['display'] ?? '');
        if ($metricKey !== '' && isset($stats->{$metricKey})) {
            return $stats->{$metricKey};
        }
        if ($displayKey !== '' && isset($stats->{$displayKey})) {
            return $stats->{$displayKey};
        }
        return 0;
    }

    /**
     * Doctor List / tabular row stat on a metric object (stats keyed by contact or user id).
     */
    protected function tabularMetricStatValue($metricRow, $entityId)
    {
        if (!$metricRow || !isset($metricRow->stats) || $entityId === null || $entityId === '') {
            return null;
        }
        $stats = $metricRow->stats;
        if (isset($stats->{$entityId})) {
            return $stats->{$entityId};
        }
        return null;
    }

    /**
     * Whether a metric column matches the user's metric filter (id or display/title).
     */
    protected function metricMatchesFilter($metric, array $selectedMetrics)
    {
        if (empty($selectedMetrics)) {
            return true;
        }
        $metricKey = is_object($metric) ? ($metric->metric ?? '') : ($metric['metric'] ?? '');
        $displayKey = is_object($metric) ? ($metric->display ?? '') : ($metric['display'] ?? '');
        if ($metricKey !== '' && in_array($metricKey, $selectedMetrics, true)) {
            return true;
        }
        if ($displayKey !== '' && in_array($displayKey, $selectedMetrics, true)) {
            return true;
        }
        return false;
    }

    /**
     * API prepends a synthetic "Me (...)" row with score/rank only; merge full stats and drop duplicate.
     */
    protected function normalizeLeaderboardMeRow($graph)
    {
        if (!isset($graph->chart) || $graph->chart !== 'leaderboard') {
            return;
        }
        if (!isset($graph->values) || !is_array($graph->values) || count($graph->values) < 1) {
            return;
        }

        $first = $graph->values[0];
        if (!isset($first->user->name) || strpos($first->user->name, 'Me (') !== 0) {
            return;
        }

        $uid = $first->user->id ?? null;
        if (!$uid) {
            return;
        }

        $canonical = null;
        foreach ($graph->values as $val) {
            if (isset($val->user->id) && $val->user->id === $uid && isset($val->stats)) {
                $canonical = $val;
                break;
            }
        }

        if ($canonical) {
            if (!isset($first->stats)) {
                $first->stats = $canonical->stats;
            }
            foreach (['employee_code', 'positions', 'parents', 'designation', 'avatar', 'hierarchy'] as $prop) {
                if ((!isset($first->user->{$prop}) || $first->user->{$prop} === '' || $first->user->{$prop} === '-')
                    && isset($canonical->user->{$prop})) {
                    $first->user->{$prop} = $canonical->user->{$prop};
                }
            }
        }

        $graph->values = array_values(array_filter($graph->values, function ($val, $i) use ($uid) {
            if ($i === 0) {
                return true;
            }
            return ($val->user->id ?? null) !== $uid;
        }, ARRAY_FILTER_USE_BOTH));
    }

    protected function normalizePersonalizationLinkText(string $text): string
    {
        $text = html_entity_decode($text, ENT_QUOTES | ENT_HTML5, 'UTF-8');
        $text = str_replace(
            ["\xE2\x81\x84", "\xE2\x88\x95", "\xEF\xBC\x8F", "\xE2\xA7\xB8", '/', '⁄', '∕'],
            '/',
            $text
        );

        return $text;
    }

    protected function normalizePersonalizationLinkUrl(string $url): string
    {
        $url = trim($this->normalizePersonalizationLinkText($url));
        if ($url === '') {
            return '';
        }
        if (!preg_match('#^https?://#i', $url)) {
            $url = 'https://' . ltrim($url, '/');
        }

        return $url;
    }

    protected function shouldCapturePersonalizationPdfLink(object $formInfo, int $templateIndex, object $pos): bool
    {
        if (!isset($formInfo->createpdf[$templateIndex]) || $formInfo->createpdf[$templateIndex] !== 'yes') {
            return false;
        }
        if (($pos->type ?? '') === 'link') {
            return true;
        }

        return isset($formInfo->addlink[$templateIndex])
            && $formInfo->addlink[$templateIndex] === 'yes'
            && isset($formInfo->linkfield[$templateIndex])
            && $formInfo->linkfield[$templateIndex] === ($pos->field_name ?? '');
    }

    protected function formatPersonalizationText(object $pos, string $text): string
    {
        if (isset($pos->prefix) && !empty($pos->prefix)) {
            $text = $pos->prefix . $text;
        }
        if (($pos->type ?? '') === 'date' && isset($pos->format)) {
            $text = date($pos->format, strtotime($text));
        }
        if (isset($pos->suffix) && !empty($pos->suffix)) {
            $text = $text . $pos->suffix;
        }

        return $text;
    }

    protected function drawPersonalizationMultilineOnImage($outputImage, object $pos, string $text): void
    {
        $fontFile = $pos->font ?? '';
        if ($fontFile === '' || !file_exists(storage_path('app/fonts/'.$fontFile))) {
            $fontFile = 'DejaVuSans.ttf';
        }
        $font = storage_path('app').'/fonts/'.$fontFile;

        $colorParts = explode('-', $pos->color ?? '0-0-0');
        $textColor = imagecolorallocate(
            $outputImage,
            (int) ($colorParts[0] ?? 0),
            (int) ($colorParts[1] ?? 0),
            (int) ($colorParts[2] ?? 0)
        );

        $text = $this->formatPersonalizationText($pos, $text);
        $lineChars = (int) ($pos->linechars ?? 40);
        $lineHeight = (int) ($pos->linehieght ?? $pos->lineheight ?? 20);
        $lines = wordwrap($text, $lineChars, "\n", true);
        $xPosition = (int) $pos->x;
        $yPosition = (int) $pos->y;

        foreach (explode("\n", $lines) as $line) {
            imagettftext($outputImage, (float) $pos->size, 0, $xPosition, $yPosition, $textColor, $font, $line);
            $yPosition += $lineHeight;
        }
    }

    protected function drawPersonalizationTextOnImage($outputImage, object $pos, string $text, bool $isLinkField = false): void
    {
        $fontFile = $pos->font ?? '';
        if ($isLinkField || $fontFile === '' || !file_exists(storage_path('app/fonts/'.$fontFile))) {
            $fontFile = 'DejaVuSans.ttf';
        }
        $font = storage_path('app').'/fonts/'.$fontFile;

        $colorParts = explode('-', $pos->color ?? '0-0-0');
        $textColor = imagecolorallocate(
            $outputImage,
            (int) ($colorParts[0] ?? 0),
            (int) ($colorParts[1] ?? 0),
            (int) ($colorParts[2] ?? 0)
        );

        $text = $this->formatPersonalizationText($pos, $text);

        $angle = isset($pos->angle) ? (float) $pos->angle : 0.0;
        $size = (float) $pos->size;
        if (isset($pos->max_width) && $pos->max_width > 0) {
            $currentSize = $size;
            $box = imagettfbbox($currentSize, $angle, $font, $text);
            $textWidth = abs($box[4] - $box[0]);
            while ($textWidth > $pos->max_width && $currentSize > 5) {
                $currentSize--;
                $box = imagettfbbox($currentSize, $angle, $font, $text);
                $textWidth = abs($box[4] - $box[0]);
            }
            $size = $currentSize;
        }

        $x = $pos->x;
        if (isset($pos->align) && $pos->align === 'center') {
            $box = imagettfbbox($size, 0, $font, $text);
            $xRange = explode('-', (string) $pos->x);
            if (count($xRange) === 2) {
                $x = $xRange[0] + (($xRange[1] - $xRange[0]) - $box[2]) / 2;
            }
        }

        imagettftext($outputImage, $size, $angle, (int) $x, (int) $pos->y, $textColor, $font, $text);
    }

    protected function resolvePersonalizationPdfScript(): string
    {
        if (file_exists('/home/ubuntu/createpdf/testpdf.php')) {
            return '/home/ubuntu/createpdf/testpdf.php';
        }

        return public_path('createpdf/testpdf.php');
    }

    protected function resolvePersonalizationLinkRect(?object $pos): ?array
    {
        if ($pos === null) {
            return null;
        }

        $fontSize = (int) ($pos->size ?? 12);
        $y = (int) ($pos->y ?? 0);
        $x = $pos->x ?? 0;

        if (is_string($x) && strpos($x, '-') !== false) {
            [$x1, $x2] = array_map('intval', explode('-', (string) $x, 2));
            $left = min($x1, $x2);
            $width = max(1, abs($x2 - $x1));
        } else {
            $left = (int) $x;
            $width = max(120, $fontSize * 12);
        }

        $top = max(0, $y - $fontSize);
        $height = max($fontSize + 10, 28);

        return [
            'x' => $left,
            'y' => $top,
            'w' => $width,
            'h' => $height,
        ];
    }

    protected function createPersonalizationPdfWithLink(int $width, int $height, string $imagePath, string $outputPath, string $linkUrl, ?object $linkPosition = null): void
    {
        $script = $this->resolvePersonalizationPdfScript();
        $url = $this->normalizePersonalizationLinkUrl($linkUrl);

        if (!file_exists($script)) {
            Log::warning('Personalization PDF script missing', ['script' => $script]);
            exec('convert '.escapeshellarg($imagePath).' -quality 100 '.escapeshellarg($outputPath));

            return;
        }

        $cmd = 'php '.escapeshellarg($script).' '
            .escapeshellarg((string) $width).' '
            .escapeshellarg((string) $height).' '
            .escapeshellarg($imagePath).' '
            .escapeshellarg($outputPath).' '
            .escapeshellarg($url);

        $linkRect = $this->resolvePersonalizationLinkRect($linkPosition);
        if ($url !== '' && $linkRect !== null) {
            $cmd .= ' '
                .escapeshellarg((string) $linkRect['x']).' '
                .escapeshellarg((string) $linkRect['y']).' '
                .escapeshellarg((string) $linkRect['w']).' '
                .escapeshellarg((string) $linkRect['h']);
        }

        exec($cmd);
        Log::debug($cmd);
    }

    /**
     * Selected user attribute codes when the form is configured to show them.
     */
    protected function userAttributeCodes($form): array
    {
        if (!$form || ($form->show_user_attributes ?? 'no') !== 'yes') {
            return [];
        }
        $raw = $form->user_attributes ?? [];
        if (!is_array($raw)) {
            return [];
        }
        $codes = [];
        foreach ($raw as $code) {
            if (is_object($code)) {
                $code = $code->code ?? '';
            }
            $code = trim((string) $code);
            if ($code !== '') {
                $codes[] = $code;
            }
        }
        return array_values(array_unique($codes));
    }

    protected function userAttributeValue($user, string $attr): string
    {
        if (!$user) {
            return '-';
        }
        $prefixed = 'attribute_' . $attr;
        if (isset($user->{$attr}) && $user->{$attr} !== '') {
            return (string) $user->{$attr};
        }
        if (isset($user->{$prefixed}) && $user->{$prefixed} !== '') {
            return (string) $user->{$prefixed};
        }
        return '-';
    }

    /**
     * Map user attribute codes to display names.
     */
    protected function resolveUserAttributeLabels(array $codes): array
    {
        $labels = [];
        if (empty($codes)) {
            return $labels;
        }

        $map = [];
        try {
            $userAttrs = $this->getlambda('get', 'ums', 'userattribute', 'get_all');
            if (isset($userAttrs->data->items) && is_array($userAttrs->data->items)) {
                foreach ($userAttrs->data->items as $attr) {
                    if (isset($attr->code)) {
                        $map[$attr->code] = $attr->attribute ?? $attr->code;
                    }
                }
            }
        } catch (\Throwable $e) {
            // Fall back to ucwords(code) below
        }

        foreach ($codes as $code) {
            $labels[$code] = $map[$code] ?? ucwords(str_replace('_', ' ', (string) $code));
        }

        return $labels;
    }

}