Untitled

mail@pastecode.io avatar
unknown
php
8 months ago
16 kB
2
Indexable
Never
public function checkWhatsappVerification($whatsappVerificationId, FlasherInterface $flasher, Request $request)
    {
        // if useragent from whatsapp return 200
        if (strpos($request->header('User-Agent'), 'WhatsApp') !== false) {
            return response()->json(['status' => 'success'], 200);
        }

        $whatsappVerification = whatsapp_verification::where('id', $whatsappVerificationId)->first();
        if ($whatsappVerification) {
            $whatsapp = $whatsappVerification->phone_number;
            $insertData = json_decode($whatsappVerification->biodata, true);

            // update placement test status
            Placement_tests::where('whatsapp', $whatsapp)->update(['status' => 'registered']);

            // collect required data
            $schedule = $insertData['student_schedule'];
            $payment = $insertData['student_payment'];
            $class = $insertData['student_class'];

            // get package data id
            if ($payment == 'cash') {
                $package = Package_list::where('package_name', strtoupper($class))->where('package_installment_period', '=', 1)->first()->toArray();
            } else {
                $package = Package_list::where('package_name', strtoupper($class))->where('package_installment_period', '!=', 1)->first()->toArray();
            }

            // get batch registration id
            // TODO : check code again prevent error
            // $batchRegistration = Batch_registration::where('id', $schedule)->where('package_id', $package['package_id'])->first()->toArray();
            $batchRegistration = Batch_registration::where([
                ['batch_date', '=', $schedule],
                ['package_id', '=', $package['package_id']]
            ])->first()->toArray();

            // unset unnecessary data
            unset($insertData['student_schedule']);
            unset($insertData['student_payment']);
            unset($insertData['student_class']);


            // dd($schedule, $payment, $class, $package, $batchRegistration);

            // save to database
            // create student biodata
            // try {
            // dd($insertData);
            try {
                $student = Student::create($insertData);
            } catch (\Throwable $th) {
                \Log::error('Error create student', [$th->getMessage()]);
                $flasher->addError('Terjadi kesalahan saat menyimpan data, silahkan coba lagi.');
                return redirect(route('register.view'));
            }

            // create installment data
            try {
                // get first month installment by batch date
                // TODO : check code again prevent error
                $BatchDate = $batchRegistration;
                $BatchDate = Carbon::parse($BatchDate['batch_date'])->format('Y-m-d');

                // Loop installment period by package installment period
                for ($i = 0; $i < $package['package_installment_period']; $i++) {
                    $nextMonth = Carbon::parse($BatchDate)->addMonths($i + 1);
                    $firstMonday = $nextMonth->firstOfMonth(Carbon::MONDAY);

                    // Check if the first day is not Monday, add 1 week
                    if ($firstMonday->dayOfWeek !== Carbon::MONDAY) {
                        $firstMonday = $firstMonday->next(Carbon::MONDAY);
                    }
                    $hit = $i + 1;

                    $installment[$i] = Installment::create([
                        'student_id' => $student->student_id,
                        'batch_registration_id' => $batchRegistration['id'],
                        'installment_price' => $batchRegistration['batch_price'],
                        'installment_discount' => $batchRegistration['batch_discount'],
                        'installment_discount_time' => 0,
                        'installment_desc' => "Pembayaran ke-$hit Wkwk Japanese Course",
                        'installment_period' => $hit,
                        'installment_due_date' => $firstMonday,
                        'installment_unix_due_date' => $firstMonday->timestamp,
                    ]);
                }
            } catch (\Throwable $th) {
                throw $th;
                $flasher->addError('Gagal membuat data cicilan');
                return die("Something went wrong");
            }
            // $flasher->addSuccess('Sukses insert data');
            // $flasher->addSuccess('UUID : '.$student->student_id);
            // Xendit::setApiKey(env("XENDIT_DEMO_SECRET_KEY"));
            // Xendit::setApiKey(env("XENDIT_PRODUCTION_SECRET_KEY"));
            // if env is production, use this
            if (env('APP_ENV') == 'production') {
                Xendit::setApiKey(env("XENDIT_PRODUCTION_SECRET_KEY"));
            } else {
                Xendit::setApiKey(env("XENDIT_DEMO_SECRET_KEY"));
            }
            $params = [
                "external_id" => $installment[0]->installment_id,
                "payer_email" => $student->student_email,
                "description" => $installment[0]->installment_desc,
                'callback_url' => url(''),
                "amount" => $installment[0]->installment_price,
            ];

            $createInvoice = \Xendit\Invoice::create($params);
            // save data trx to SQL
            $xendit_payment = [
                'id' => $createInvoice['id'],
                'external_id' => $createInvoice['external_id'],
                'student_id' => $student->student_id,
                'user_id' => $createInvoice['user_id'],
                'payer_email' => $createInvoice['payer_email'],
                'description' => $createInvoice['description'],
                'amount' => $createInvoice['amount'],
                'invoice_url' => $createInvoice['invoice_url'],
                'status' => $createInvoice['status'],
                'expiry_date' => $createInvoice['expiry_date'],
                'currency' => 'IDR',
            ];

            XenditPayment::create($xendit_payment);
            //     return redirect($createInvoice['invoice_url']);

            // } catch (\Illuminate\Database\QueryException $e) {
            //     $errorCode = $e->errorInfo[1];
            //     if ($errorCode == '1062') {
            //         $flasher->addError("Data sudah terdaftar!");
            //     } else {
            //         // return response()->json(['database'=>$e->errorInfo,'postForm'=>$request->all()],400);
            //     }

            // }

            // convert iso8601 to readable date
            // $createInvoice['expiry_date'] = Carbon::parse($createInvoice['expiry_date'])->setTimezone('UTC');
            // $createInvoice['expiry_date']->setTimezone('Asia/Jakarta');
            // $createInvoice['expiry_date']->locale('id')->settings(['formatFunction' => 'translatedFormat'])->format('l, j F Y');

            // send payment link to whatsapp
            $message = "Berikut kami sertakan link pembayaran yang berada di paling bawah pesan ini, harap di ingat link pembayaran ini hanya berlaku sampai " . Carbon::parse($createInvoice['expiry_date'])->locale('id')->settings(['formatFunction' => 'translatedFormat'])->format('l, j F Y h:i A') . ". Jika link pembayaran sudah kadaluwarsa mohon hubungi aku kembali yaa\n\n" . $createInvoice['invoice_url'];
            sendWhatsapp($whatsapp, $message);

            // delete record from whatsapp_verification
            $whatsappVerification->delete();

            // delete session package_reff
            $request->session()->forget('package_reff');

            // dd($whatsapp,$insertData);

            return redirect($createInvoice['invoice_url']);
            // return redirect()->back();
        } else {
            $flasher->addError('Data sudah diinputkan kedalam database.');
            return redirect(route('register.view'));
        }
    }public function checkWhatsappVerification($whatsappVerificationId, FlasherInterface $flasher, Request $request)
    {
        // if useragent from whatsapp return 200
        if (strpos($request->header('User-Agent'), 'WhatsApp') !== false) {
            return response()->json(['status' => 'success'], 200);
        }

        $whatsappVerification = whatsapp_verification::where('id', $whatsappVerificationId)->first();
        if ($whatsappVerification) {
            $whatsapp = $whatsappVerification->phone_number;
            $insertData = json_decode($whatsappVerification->biodata, true);

            // update placement test status
            Placement_tests::where('whatsapp', $whatsapp)->update(['status' => 'registered']);

            // collect required data
            $schedule = $insertData['student_schedule'];
            $payment = $insertData['student_payment'];
            $class = $insertData['student_class'];

            // get package data id
            if ($payment == 'cash') {
                $package = Package_list::where('package_name', strtoupper($class))->where('package_installment_period', '=', 1)->first()->toArray();
            } else {
                $package = Package_list::where('package_name', strtoupper($class))->where('package_installment_period', '!=', 1)->first()->toArray();
            }

            // get batch registration id
            // TODO : check code again prevent error
            // $batchRegistration = Batch_registration::where('id', $schedule)->where('package_id', $package['package_id'])->first()->toArray();
            $batchRegistration = Batch_registration::where([
                ['batch_date', '=', $schedule],
                ['package_id', '=', $package['package_id']]
            ])->first()->toArray();

            // unset unnecessary data
            unset($insertData['student_schedule']);
            unset($insertData['student_payment']);
            unset($insertData['student_class']);


            // dd($schedule, $payment, $class, $package, $batchRegistration);

            // save to database
            // create student biodata
            // try {
            // dd($insertData);
            try {
                $student = Student::create($insertData);
            } catch (\Throwable $th) {
                \Log::error('Error create student', [$th->getMessage()]);
                $flasher->addError('Terjadi kesalahan saat menyimpan data, silahkan coba lagi.');
                return redirect(route('register.view'));
            }

            // create installment data
            try {
                // get first month installment by batch date
                // TODO : check code again prevent error
                $BatchDate = $batchRegistration;
                $BatchDate = Carbon::parse($BatchDate['batch_date'])->format('Y-m-d');

                // Loop installment period by package installment period
                for ($i = 0; $i < $package['package_installment_period']; $i++) {
                    $nextMonth = Carbon::parse($BatchDate)->addMonths($i + 1);
                    $firstMonday = $nextMonth->firstOfMonth(Carbon::MONDAY);

                    // Check if the first day is not Monday, add 1 week
                    if ($firstMonday->dayOfWeek !== Carbon::MONDAY) {
                        $firstMonday = $firstMonday->next(Carbon::MONDAY);
                    }
                    $hit = $i + 1;

                    $installment[$i] = Installment::create([
                        'student_id' => $student->student_id,
                        'batch_registration_id' => $batchRegistration['id'],
                        'installment_price' => $batchRegistration['batch_price'],
                        'installment_discount' => $batchRegistration['batch_discount'],
                        'installment_discount_time' => 0,
                        'installment_desc' => "Pembayaran ke-$hit Wkwk Japanese Course",
                        'installment_period' => $hit,
                        'installment_due_date' => $firstMonday,
                        'installment_unix_due_date' => $firstMonday->timestamp,
                    ]);
                }
            } catch (\Throwable $th) {
                throw $th;
                $flasher->addError('Gagal membuat data cicilan');
                return die("Something went wrong");
            }
            // $flasher->addSuccess('Sukses insert data');
            // $flasher->addSuccess('UUID : '.$student->student_id);
            // Xendit::setApiKey(env("XENDIT_DEMO_SECRET_KEY"));
            // Xendit::setApiKey(env("XENDIT_PRODUCTION_SECRET_KEY"));
            // if env is production, use this
            if (env('APP_ENV') == 'production') {
                Xendit::setApiKey(env("XENDIT_PRODUCTION_SECRET_KEY"));
            } else {
                Xendit::setApiKey(env("XENDIT_DEMO_SECRET_KEY"));
            }
            $params = [
                "external_id" => $installment[0]->installment_id,
                "payer_email" => $student->student_email,
                "description" => $installment[0]->installment_desc,
                'callback_url' => url(''),
                "amount" => $installment[0]->installment_price,
            ];

            $createInvoice = \Xendit\Invoice::create($params);
            // save data trx to SQL
            $xendit_payment = [
                'id' => $createInvoice['id'],
                'external_id' => $createInvoice['external_id'],
                'student_id' => $student->student_id,
                'user_id' => $createInvoice['user_id'],
                'payer_email' => $createInvoice['payer_email'],
                'description' => $createInvoice['description'],
                'amount' => $createInvoice['amount'],
                'invoice_url' => $createInvoice['invoice_url'],
                'status' => $createInvoice['status'],
                'expiry_date' => $createInvoice['expiry_date'],
                'currency' => 'IDR',
            ];

            XenditPayment::create($xendit_payment);
            //     return redirect($createInvoice['invoice_url']);

            // } catch (\Illuminate\Database\QueryException $e) {
            //     $errorCode = $e->errorInfo[1];
            //     if ($errorCode == '1062') {
            //         $flasher->addError("Data sudah terdaftar!");
            //     } else {
            //         // return response()->json(['database'=>$e->errorInfo,'postForm'=>$request->all()],400);
            //     }

            // }

            // convert iso8601 to readable date
            // $createInvoice['expiry_date'] = Carbon::parse($createInvoice['expiry_date'])->setTimezone('UTC');
            // $createInvoice['expiry_date']->setTimezone('Asia/Jakarta');
            // $createInvoice['expiry_date']->locale('id')->settings(['formatFunction' => 'translatedFormat'])->format('l, j F Y');

            // send payment link to whatsapp
            $message = "Berikut kami sertakan link pembayaran yang berada di paling bawah pesan ini, harap di ingat link pembayaran ini hanya berlaku sampai " . Carbon::parse($createInvoice['expiry_date'])->locale('id')->settings(['formatFunction' => 'translatedFormat'])->format('l, j F Y h:i A') . ". Jika link pembayaran sudah kadaluwarsa mohon hubungi aku kembali yaa\n\n" . $createInvoice['invoice_url'];
            sendWhatsapp($whatsapp, $message);

            // delete record from whatsapp_verification
            $whatsappVerification->delete();

            // delete session package_reff
            $request->session()->forget('package_reff');

            // dd($whatsapp,$insertData);

            return redirect($createInvoice['invoice_url']);
            // return redirect()->back();
        } else {
            $flasher->addError('Data sudah diinputkan kedalam database.');
            return redirect(route('register.view'));
        }
    }