HomeController.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Lib\Backend;
  4. use App\Models\Appointment;
  5. use App\Models\AppSession;
  6. use App\Models\ClientSMS;
  7. use App\Models\Facility;
  8. use App\Models\ProProAccess;
  9. use App\Models\Ticket;
  10. use DateTime;
  11. use App\Models\Client;
  12. use App\Models\Bill;
  13. use App\Models\Measurement;
  14. use App\Models\Note;
  15. use App\Models\Pro;
  16. use App\Models\ProTransaction;
  17. use GuzzleHttp\Cookie\CookieJar;
  18. use Illuminate\Http\Request;
  19. use Illuminate\Support\Facades\Cookie;
  20. use Illuminate\Support\Facades\DB;
  21. use Illuminate\Support\Facades\Http;
  22. class HomeController extends Controller
  23. {
  24. public function confirmSmsAuthToken(Request $request)
  25. {
  26. return view('app/confirm_sms_auth_token');
  27. }
  28. public function setPassword(Request $request)
  29. {
  30. return view('app/set_password');
  31. }
  32. public function setSecurityQuestions(Request $request)
  33. {
  34. return view('app/set_security_questions');
  35. }
  36. public function postConfirmSmsAuthToken(Request $request)
  37. {
  38. try {
  39. $url = config('stag.backendUrl') . '/session/confirmSmsAuthToken';
  40. $data = [
  41. 'cellNumber' => $request->input('cellNumber'),
  42. 'token' => $request->input('token'),
  43. ];
  44. $response = Http::asForm()
  45. ->withHeaders(['sessionKey' => $request->cookie('sessionKey')])
  46. ->post($url, $data)
  47. ->json();
  48. if (!isset($response['success']) || !$response['success']) {
  49. $message = 'API error';
  50. if (isset($response['error'])) {
  51. $message = $response['error'];
  52. if (isset($response['path'])) $message .= ': ' . $response['path'];
  53. } else if (isset($response['message'])) $message = $response['message'];
  54. return redirect('/confirm_sms_auth_token')
  55. ->withInput()
  56. ->with('message', $message);
  57. }
  58. return redirect('/');
  59. } catch (\Exception $e) {
  60. return redirect()->back()
  61. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  62. ->withInput($request->input());
  63. }
  64. }
  65. public function resendSmsAuthToken(Request $request)
  66. {
  67. try {
  68. $url = config('stag.backendUrl') . '/session/resendSmsAuthToken';
  69. $data = [];
  70. $response = Http::asForm()
  71. ->withHeaders(['sessionKey' => $request->cookie('sessionKey')])
  72. ->post($url, $data)
  73. ->json();
  74. if (!isset($response['success']) || !$response['success']) {
  75. $message = 'API error';
  76. if (isset($response['error'])) {
  77. $message = $response['error'];
  78. if (isset($response['path'])) $message .= ': ' . $response['path'];
  79. } else if (isset($response['message'])) $message = $response['message'];
  80. return redirect('/confirm_sms_auth_token')
  81. ->withInput()
  82. ->with('message', $message);
  83. }
  84. return redirect()->back()->withInput()->with('message', "SMS Auth Token sent.");
  85. } catch (\Exception $e) {
  86. return redirect()->back()
  87. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  88. ->withInput($request->input());
  89. }
  90. }
  91. public function postSetPassword(Request $request)
  92. {
  93. try {
  94. $url = config('stag.backendUrl') . '/pro/selfPutPassword';
  95. $data = [
  96. 'newPassword' => $request->input('newPassword'),
  97. 'newPasswordConfirmation' => $request->input('newPasswordConfirmation'),
  98. ];
  99. $response = Http::asForm()
  100. ->withHeaders(['sessionKey' => $request->cookie('sessionKey')])
  101. ->post($url, $data)
  102. ->json();
  103. if (!isset($response['success']) || !$response['success']) {
  104. $message = 'API error';
  105. if (isset($response['error'])) {
  106. $message = $response['error'];
  107. if (isset($response['path'])) $message .= ': ' . $response['path'];
  108. } else if (isset($response['message'])) $message = $response['message'];
  109. return redirect('/set_password')
  110. ->withInput()
  111. ->with('message', $message);
  112. }
  113. return redirect('/');
  114. } catch (\Exception $e) {
  115. return redirect()->back()
  116. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  117. ->withInput($request->input());
  118. }
  119. }
  120. public function postSetSecurityQuestions(Request $request)
  121. {
  122. try {
  123. $url = env('BACKEND_URL', 'http://localhost:8080/api') . '/pro/selfPutSecurityQuestions';
  124. $data = [
  125. 'securityQuestion1' => $request->input('securityQuestion1'),
  126. 'securityAnswer1' => $request->input('securityAnswer1'),
  127. 'securityQuestion2' => $request->input('securityQuestion2'),
  128. 'securityAnswer2' => $request->input('securityAnswer2'),
  129. ];
  130. $response = Http::asForm()
  131. ->withHeaders(['sessionKey' => $request->cookie('sessionKey')])
  132. ->post($url, $data)
  133. ->json();
  134. if (!isset($response['success']) || !$response['success']) {
  135. $message = 'API error';
  136. if (isset($response['error'])) {
  137. $message = $response['error'];
  138. if (isset($response['path'])) $message .= ': ' . $response['path'];
  139. } else if (isset($response['message'])) $message = $response['message'];
  140. return redirect('/set_password')
  141. ->withInput()
  142. ->with('message', $message);
  143. }
  144. return redirect('/');
  145. } catch (\Exception $e) {
  146. return redirect()->back()
  147. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  148. ->withInput($request->input());
  149. }
  150. }
  151. public function dashboard(Request $request)
  152. {
  153. //patients where performer is the mcp
  154. $performer = $this->performer();
  155. $performerProID = $performer->pro->id;
  156. $isAdmin = ($performer->pro->pro_type === 'ADMIN');
  157. $keyNumbers = [];
  158. $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
  159. $keyNumbers['totalPatients'] = $queryClients->count();
  160. // patientNotSeenYet
  161. $patientNotSeenYet = $queryClients
  162. ->where(function ($query) use ($performer) { // own patient and primary OB visit pending
  163. $query->where('mcp_pro_id', $performer->pro->id)
  164. ->where('has_mcp_done_onboarding_visit', '!=', 'YES');
  165. })
  166. ->orWhere(function ($query) { // mcp of any client program and program OB pending
  167. $query->where(function ($_query) {
  168. $_query->select(DB::raw('COUNT(id)'))
  169. ->from('client_program')
  170. ->whereColumn('client_id', 'client.id')
  171. ->where('has_mcp_done_onboarding_visit', '!=', 'YES');
  172. }, '>=', 1);
  173. })->count();
  174. $keyNumbers['patientsNotSeenYet'] = $patientNotSeenYet;
  175. $pendingBillsToSign = Bill::where(function ($query) use ($performerProID) {
  176. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false);
  177. })
  178. ->orWhere(function ($query) use ($performerProID) {
  179. $query->where('cm_pro_id', $performerProID)->where('is_signed_by_cm', false)->where('is_cancelled', false);;
  180. })->orWhere(function ($query) use ($performerProID) {
  181. $query->where('rme_pro_id', $performerProID)->where('is_signed_by_rme', false)->where('is_cancelled', false);;
  182. })->orWhere(function ($query) use ($performerProID) {
  183. $query->where('rmm_pro_id', $performerProID)->where('is_signed_by_rmm', false)->where('is_cancelled', false);;
  184. })->count();
  185. $keyNumbers['pendingBillsToSign'] = $pendingBillsToSign;
  186. $pendingNotesToSign = Note::where(function ($query) use ($performerProID) {
  187. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false);;
  188. })
  189. ->orWhere(function ($query) use ($performerProID) {
  190. $query->where('ally_pro_id', $performerProID)->where('is_signed_by_ally', false)->where('is_cancelled', false);;
  191. })->count();
  192. $keyNumbers['pendingNotesToSign'] = $pendingNotesToSign;
  193. // open tickets
  194. $keyNumbers['numOpenTickets'] = Ticket::where('is_open', true)
  195. ->where(function ($q) use ($performerProID) {
  196. $q->where('assigned_pro_id', $performerProID)
  197. ->orWhere('manager_pro_id', $performerProID)
  198. ->orWhere('ordering_pro_id', $performerProID)
  199. ->orWhere('initiating_pro_id', $performerProID);
  200. })
  201. ->count();
  202. // num measurements that need stamping
  203. $keyNumbers['measurementsToBeStamped'] = ($this->performer()->pro->pro_type === 'ADMIN' ? '-' : count($this->performer()->pro->getMeasurements(true)));
  204. $reimbursement = [];
  205. $reimbursement["currentBalance"] = $performer->pro->balance;
  206. $reimbursement["nextPaymentDate"] = '--';
  207. $lastPayment = ProTransaction::where('pro_id', $performerProID)->where('plus_or_minus', 'PLUS')->orderBy('created_at', 'DESC')->first();
  208. if ($lastPayment) {
  209. $reimbursement["lastPayment"] = $lastPayment->amount;
  210. $reimbursement["lastPaymentDate"] = $lastPayment->created_at;
  211. } else {
  212. $reimbursement["lastPayment"] = '--';
  213. $reimbursement["lastPaymentDate"] = '--';
  214. }
  215. //if today is < 15th, next payment is 15th, else nextPayment is
  216. $today = strtotime(date('Y-m-d'));
  217. $todayDate = date('j', $today);
  218. $todayMonth = date('m', $today);
  219. $todayYear = date('Y', $today);
  220. if ($todayDate < 15) {
  221. $nextPaymentDate = new DateTime();
  222. $nextPaymentDate->setDate($todayYear, $todayMonth, 15);
  223. $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
  224. } else {
  225. $nextPaymentDate = new \DateTime();
  226. $lastDayOfMonth = date('t', $today);
  227. $nextPaymentDate->setDate($todayYear, $todayMonth, $lastDayOfMonth);
  228. $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
  229. }
  230. //expectedPay
  231. $expectedForHcp = DB::select(DB::raw("SELECT coalesce(SUM(hcp_expected_payment_amount),0) as expected_pay FROM bill WHERE hcp_pro_id = :performerProID AND has_hcp_been_paid = false AND is_signed_by_hcp IS TRUE AND is_cancelled = false"), ['performerProID' => $performerProID])[0]->expected_pay;
  232. $expectedForCm = DB::select(DB::raw("SELECT coalesce(SUM(cm_expected_payment_amount),0) as expected_pay FROM bill WHERE cm_pro_id = :performerProID AND has_cm_been_paid = false AND is_signed_by_cm IS TRUE AND is_cancelled = false"), ['performerProID' => $performerProID])[0]->expected_pay;
  233. $expectedForRme = DB::select(DB::raw("SELECT coalesce(SUM(rme_expected_payment_amount),0) as expected_pay FROM bill WHERE rme_pro_id = :performerProID AND has_rme_been_paid = false AND is_signed_by_rme IS TRUE AND is_cancelled = false"), ['performerProID' => $performerProID])[0]->expected_pay;
  234. $expectedForRmm = DB::select(DB::raw("SELECT coalesce(SUM(rmm_expected_payment_amount),0) as expected_pay FROM bill WHERE rmm_pro_id = :performerProID AND has_rmm_been_paid = false AND is_signed_by_rmm IS TRUE AND is_cancelled = false"), ['performerProID' => $performerProID])[0]->expected_pay;
  235. $expectedForNa = DB::select(DB::raw("SELECT coalesce(SUM(na_expected_payment_amount),0) as expected_pay FROM bill WHERE na_pro_id = :performerProID AND has_na_been_paid = false AND is_signed_by_hcp IS TRUE AND is_cancelled = false"), ['performerProID' => $performerProID])[0]->expected_pay;
  236. $totalExpectedAmount = $expectedForHcp + $expectedForCm + $expectedForRme + $expectedForRmm + $expectedForNa;
  237. $reimbursement['nextPaymentAmount'] = $totalExpectedAmount;
  238. $milliseconds = strtotime(date('Y-m-d')) . '000';
  239. $measurements = $performer->pro->getMeasurements();
  240. return view('app/dashboard', compact('keyNumbers', 'reimbursement', 'milliseconds', 'measurements'));
  241. }
  242. public function dashboardAppointments(Request $request, $from, $to) {
  243. $performer = $this->performer();
  244. $performerProID = $performer->pro->id;
  245. $isAdmin = ($performer->pro->pro_type === 'ADMIN');
  246. $appointments = Appointment::where("start_time", '>=', $from)->where("start_time", '<=', $to.' 23:59:00+00');
  247. if(!$isAdmin) {
  248. $appointments = $appointments->where("pro_id", $performerProID);
  249. }
  250. $appointments = $appointments
  251. ->orderBy('start_time', 'asc')
  252. ->get();
  253. foreach ($appointments as $appointment) {
  254. $date = explode(" ", $appointment->start_time)[0];
  255. $appointment->milliseconds = strtotime($date) . '000';
  256. $appointment->newStatus = $appointment->status;
  257. $appointment->dateYMD = date('Y-m-d', strtotime($appointment->raw_date));
  258. $appointment->clientName = $appointment->client->displayName();
  259. $appointment->clientInitials = substr($appointment->client->name_first, 0, 1) . substr($appointment->client->name_last, 0, 1);
  260. $appointment->proInitials = substr($appointment->pro->name_first, 0, 1) . substr($appointment->pro->name_last, 0, 1);
  261. $appointment->friendlyStartTime = friendly_time($appointment->raw_start_time);
  262. $appointment->friendlyEndTime = friendly_time($appointment->raw_end_time);
  263. $appointment->clientSummary = friendly_date_time($appointment->client->dob, false) . ' (' .
  264. $appointment->client->age_in_years . ' y.o' .
  265. ($appointment->client->sex ? ' ' . $appointment->client->sex : '') .
  266. ')';
  267. $appointment->started = false;
  268. $appointment->inHowManyHours = date_diff(date_create('now'), date_create($appointment->start_time), false)
  269. ->format('%R%h h, %i m');
  270. if ($appointment->inHowManyHours[0] === '-') {
  271. $appointment->inHowManyHours = substr($appointment->inHowManyHours, 1) . ' ago';
  272. $appointment->started = true;
  273. } else {
  274. $appointment->inHowManyHours = 'Appt. in ' . substr($appointment->inHowManyHours, 1);
  275. }
  276. $appointment->clientUid = $appointment->client->uid;
  277. $appointment->proUid = $appointment->pro->uid;
  278. $appointment->proName = $appointment->pro->displayName();
  279. }
  280. return json_encode($appointments);
  281. }
  282. public function dashboardMeasurements(Request $request, $filter) {
  283. $measurements = $this->performer()->pro->getMeasurements($filter === 'NEED_ACK');
  284. return json_encode($measurements);
  285. }
  286. public function patients(Request $request, $filter = '')
  287. {
  288. $performer = $this->performer();
  289. $query = $performer->pro->getAccessibleClientsQuery();
  290. switch ($filter) {
  291. case 'not-yet-seen':
  292. $query = $query
  293. ->where(function ($query) use ($performer) {
  294. $query
  295. ->where(function ($query) use ($performer) { // own patient and primary OB visit pending
  296. $query->where('mcp_pro_id', $performer->pro->id)
  297. ->where('has_mcp_done_onboarding_visit', '<>', 'YES');
  298. })
  299. ->orWhere(function ($query) use ($performer) { // mcp of any client program and program OB pending
  300. $query->select(DB::raw('COUNT(id)'))
  301. ->from('client_program')
  302. ->whereColumn('client_id', 'client.id')
  303. ->where('mcp_pro_id', $performer->pro->id)
  304. ->where('has_mcp_done_onboarding_visit', '<>', 'YES');
  305. }, '>=', 1);
  306. });
  307. break;
  308. // more cases can be added as needed
  309. default:
  310. break;
  311. }
  312. $patients = $query->orderBy('id', 'desc')->paginate(500);
  313. return view('app/patients', compact('patients', 'filter'));
  314. }
  315. public function patientsSuggest(Request $request)
  316. {
  317. $pro = $this->pro;
  318. $term = $request->input('term') ? trim($request->input('term')) : '';
  319. if (empty($term)) return '';
  320. $clientQuery= Client::where(function ($q) use ($term) {
  321. $q->where('name_first', 'ILIKE', '%' . $term . '%')
  322. ->orWhere('name_last', 'ILIKE', '%' . $term . '%')
  323. ->orWhere('cell_number', 'ILIKE', '%' . $term . '%');
  324. });
  325. if($pro->pro_type != 'ADMIN'){
  326. $clientQuery->whereIn('id', $pro->getMyClientIds());
  327. }
  328. $clients = $clientQuery->get();
  329. return view('app/patient-suggest', compact('clients'));
  330. }
  331. public function pharmacySuggest(Request $request)
  332. {
  333. $term = $request->input('term') ? trim($request->input('term')) : '';
  334. if (empty($term)) return '';
  335. $term = strtolower($term);
  336. $pharmacies = Facility::where('facility_type', 'Pharmacy')
  337. ->where(function ($q) use ($term) {
  338. $q->orWhereRaw('LOWER(name::text) LIKE ?', ['%' . $term . '%'])
  339. ->orWhereRaw('LOWER(address_line1::text) LIKE ?', ['%' . $term . '%'])
  340. ->orWhereRaw('LOWER(address_line2::text) LIKE ?', ['%' . $term . '%'])
  341. ->orWhereRaw('LOWER(address_city::text) LIKE ?', ['%' . $term . '%'])
  342. ->orWhereRaw('LOWER(address_state::text) LIKE ?', ['%' . $term . '%'])
  343. ->orWhereRaw('LOWER(phone::text) LIKE ?', ['%' . $term . '%'])
  344. ->orWhereRaw('LOWER(address_zip::text) LIKE ?', ['%' . $term . '%']);
  345. })
  346. ->orderBy('name', 'asc')
  347. ->orderBy('address_line1', 'asc')
  348. ->orderBy('address_city', 'asc')
  349. ->orderBy('address_state', 'asc')
  350. ->get();
  351. return view('app/pharmacy-suggest', compact('pharmacies'));
  352. }
  353. public function proSuggest(Request $request, $format = 'html') {
  354. $term = $request->input('term') ? trim($request->input('term')) : '';
  355. if (empty($term)) return '';
  356. $term = strtolower($term);
  357. $pros = Pro::where(function ($q) use ($term) {
  358. $q->orWhereRaw('LOWER(name_first::text) LIKE ?', ['%' . $term . '%'])
  359. ->orWhereRaw('LOWER(name_last::text) LIKE ?', ['%' . $term . '%'])
  360. ->orWhereRaw('cell_number LIKE ?', ['%' . $term . '%']);
  361. });
  362. if($this->performer->pro && $this->performer->pro->pro_type != 'ADMIN'){
  363. $accessiblePros = ProProAccess::where('owner_pro_id', $this->performer->pro->id);
  364. $accessibleProIds = [];
  365. foreach($accessiblePros as $accessiblePro){
  366. $accessibleProIds[] = $accessiblePro->id;
  367. }
  368. $accessibleProIds[] = $this->performer->pro->id;
  369. $pros->whereIn('id', $accessibleProIds);
  370. }
  371. $suggestedPros = $pros->orderBy('name_last')->orderBy('name_first')->get();
  372. $response = '';
  373. if($format === 'html') {
  374. $response = view('app/pro-suggest', compact('suggestedPros'));
  375. }
  376. else if($format === 'json') {
  377. $output = [];
  378. foreach ($suggestedPros as $sPro) {
  379. $output[] = [
  380. "id" => $sPro->id,
  381. "uid" => $sPro->uid,
  382. "text" => $sPro->displayName(),
  383. "initials" => $sPro->initials(),
  384. ];
  385. }
  386. $response = json_encode($output);
  387. }
  388. return $response;
  389. }
  390. public function proDisplayName(Request $request, Pro $pro) {
  391. return $pro ? $pro->displayName() : '';
  392. }
  393. public function unmappedSMS(Request $request, $filter = '')
  394. {
  395. $proID = $this->performer()->pro->id;
  396. if ($this->performer()->pro->pro_type === 'ADMIN') {
  397. $query = Client::where('id', '>', 0);
  398. } else {
  399. $query = Client::where(function ($q) use ($proID) {
  400. $q->where('mcp_pro_id', $proID)
  401. ->orWhere('cm_pro_id', $proID)
  402. ->orWhere('rmm_pro_id', $proID)
  403. ->orWhere('rme_pro_id', $proID)
  404. ->orWhereRaw('id IN (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = ?)', [$proID]);
  405. });
  406. }
  407. $patients = $query->orderBy('name_last', 'asc')->orderBy('name_first', 'asc')->get();
  408. $unmappedSMS = ClientSMS::where('client_id', null)->where('incoming_or_outgoing', 'INCOMING')->get();
  409. return view('app/unmapped-sms', compact('unmappedSMS', 'patients'));
  410. }
  411. public function newPatient(Request $request)
  412. {
  413. return view('app/new-patient');
  414. }
  415. public function mc(Request $request, $fragment = "")
  416. {
  417. $page = "/";
  418. if ($fragment) {
  419. $page = '/' . $fragment;
  420. }
  421. return view('app/mc', compact('page'));
  422. }
  423. public function blank(Request $request)
  424. {
  425. return view('app/blank');
  426. }
  427. public function noteTemplateSet(Request $request, $section, $template)
  428. {
  429. return view('app/patient/note/_template', [
  430. "sectionInternalName" => $section,
  431. "templateName" => $template
  432. ]);
  433. }
  434. public function noteExamTemplateSet(Request $request, $exam, $template)
  435. {
  436. return view('app/patient/note/_template-exam', [
  437. "exam" => $exam,
  438. "sectionInternalName" => 'exam-' . $exam . '-detail',
  439. "templateName" => $template
  440. ]);
  441. }
  442. public function logInAs(Request $request)
  443. {
  444. if($this->pro->pro_type != 'ADMIN'){
  445. return redirect()->to(route('dashboard'));
  446. }
  447. $pros = Pro
  448. ::where('pro_type', '!=', 'ADMIN')
  449. ->orWhereNull('pro_type')
  450. ->orderBy('name_last', 'asc')
  451. ->orderBy('name_first', 'asc')
  452. ->get();
  453. return view('app/log-in-as', compact('pros'));
  454. }
  455. public function processLogInAs(Request $request)
  456. {
  457. $api = new Backend();
  458. try {
  459. $apiResponse = $api->post('session/proLogInAs', [
  460. 'proUid' => $request->post('proUid')
  461. ],
  462. [
  463. 'sessionKey'=>$this->performer()->session_key
  464. ]);
  465. $data = json_decode($apiResponse->getContents());
  466. if (!property_exists($data, 'success') || !$data->success) {
  467. return redirect()->to(route('log-in-as'))->with('message', $data->message)
  468. ->withInput($request->input());
  469. }
  470. Cookie::queue('sessionKey', $data->data->sessionKey);
  471. return redirect('/mc');
  472. } catch (\Exception $e) {
  473. return redirect()->to(route('log-in-as'))
  474. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  475. ->withInput($request->input());
  476. }
  477. }
  478. public function backToAdminPro(Request $request){
  479. $adminPerformerId = $this->performer->logged_in_as_pro_from_admin_pro_app_session_id;
  480. $adminPerformer = AppSession::where('id', $adminPerformerId)->first();
  481. $url = "/session/pro_log_in_with_session_key/".$adminPerformer->session_key;
  482. $api = new Backend();
  483. try {
  484. $apiResponse = $api->post($url, []);
  485. $data = json_decode($apiResponse->getContents());
  486. if (!property_exists($data, 'success') || !$data->success) {
  487. return redirect()->to(route('logout'));
  488. }
  489. Cookie::queue('sessionKey', $data->data->sessionKey);
  490. return redirect(route('dashboard'));
  491. } catch (\Exception $e) {
  492. return redirect(route('dashboard'));
  493. }
  494. }
  495. }