<?php


namespace App\Console\Commands;


use App\Http\Controllers\ParameterGlobalController;
use App\Models\Customer;
use App\Models\DataGadai;
use App\Models\DataGadaiDetail;
use App\Models\JobLog;
use App\Models\JobLogReport;
use App\Models\MasterConfig;
use App\Models\CustomerCoupon;
use App\Models\VoucherPromoPoint;
use App\Models\Notification;
use App\Models\NotificationCustomer;
use Carbon\Carbon;
use Google_Client;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class NotificationJob extends Command
{
    protected $signature = 'job:notifikasiSend';

    protected $description = 'Kirim Notifikasi';

    private function getGoogleAccessToken()
    {

        $credentialsFilePath = 'public/assets/json/raja-gadai-firebase-adminsdk-5ip5v-39f562484d.json'; //replace this with your actual path and file name
        $client = new Google_Client();
        $client->setAuthConfig($credentialsFilePath);
        $client->addScope('https://www.googleapis.com/auth/firebase.messaging');
        $client->refreshTokenWithAssertion();
        //echo 'CLient Token = '.$client
        $token = $client->getAccessToken();
        return $token['access_token'];
    }

    private function sendNotif($message, $log, $id)
    {
        $config = MasterConfig::where('key', 'API_FIREBASE')->first();
        $apiurl = $config->value;
        $headers = [
            'Authorization: Bearer ' . $this->getGoogleAccessToken(),
            'Content-Type: application/json'
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $apiurl);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($message));

        $result = curl_exec($ch);

        if ($result === FALSE) {
            //Failed
            die('Curl failed: ' . curl_error($ch));
        }
        $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);

        Log::info($result);
        JobLogReport::create([
            'job_log_id' => $log->id,
            'status' => $http_status,
            'tgl_proses' => Carbon::now(),
            'response' => $result,
            'request' => json_encode($message),
        ]);
        $this->info('Report berhasil dibuat');
        if ($http_status == 200) {

            $this->info('Berhasil Mengirim Notifikasi Status ' . $http_status);
            $this->info($result);
            Log::channel('mobile')->info('Berhasil Mengirim Notifikasi Status ' . $http_status);
            Log::channel('mobile')->info($result);
        } else {
            $this->error('Permintaan gagal: Status ' . $http_status);
            Log::channel('mobile')->error($result);
        }

        return $http_status;
    }

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        while (true) {
            $now = Carbon::now()->format('Y-m-d H:i');
            $job = JobLog::join('customer as b', 'job_log.customer_id', '=', 'b.customer_id')
                ->whereNotNull('job_log.notification_id')
                ->whereIn('job_log.status', [0, 9])
                ->where('job_log.count_sending', '<', ParameterGlobalController::counter_send_notif())
                ->where('job_log.tgl_proses', '<=', now())
                ->orderBy('job_log.id')
                ->get();
            foreach ($job as $log) {
                try {
                    $sendNotif = Carbon::parse($log->tgl_proses)->format('Y-m-d H:i');
                    $message = [];

                    if ($sendNotif <= $now) {

                        //echo 'Notification = '.$log->customer_id." ";

                        $customer = Customer::where('customer_id', $log->customer_id)->first();
                        if ($customer->fcmtoken_firebase != null) {
                            $notifikasi = Notification::where('id', $log->notification_id)->first();
                            $description = $notifikasi->description;
                            $description = str_replace('&nbsp;', ' ', $description);
                            $description = str_replace("#nama#", $customer->nama_customer, $description);
                            if ($notifikasi->type_id == 8) {
                                Log::error('Notification Masuk 1 = ');
                                $voucher = CustomerCoupon::where('customer_coupon_id', $log->coupon_id)->first();
                                $voucherGB = VoucherPromoPoint::where('id', $voucher->coupon_id)->first();
                                if ($voucherGB) {
                                    $description = str_replace('#status#', $voucher->status_reward_desc, $description);
                                    $description = str_replace('#voucher#', $voucherGB->nama_voucher, $description);
                                    Log::channel('mobile')->info('masuk 2');
                                    $message = [
                                        'message' => [
                                            "token" => $customer->fcmtoken_firebase,
                                            "notification" => [
                                                "body" => strip_tags($description),
                                                "title" => $notifikasi->subject
                                            ],
                                            "data" => [
                                                "id" => (string)$voucherGB->id,
                                                "module" => "Remider Status"
                                            ]
                                        ]
                                    ];
                                    $log->update([
                                        'status' => 2,
                                        'count_sending' => $log->count_sending + 1
                                    ]);
                                    Log::info('status log 2');

                                    $notification = NotificationCustomer::create([
                                        'customer_id' => $customer->customer_id,
                                        'notification_id' => $notifikasi->id,
                                        'read_notification' => false,
                                        'description' => $description,
                                        'created_who' => 'cronjob'
                                    ]);
                                    if ($log->status == 2) {
                                        $this->info('log berhasil diupdate');
                                        Log::info('log berhasil dibuat');
                                        $send = $this->sendNotif($message, $log, $notification->id);
                                        if ($send == 200 || $send == "200") {
                                            $this->info('notif berhasil dipush');
                                            Log::info('Log berhasil dihapus');
                                            $log->delete();
                                        } else {
                                            $log->update([
                                                'status' => 9,
                                            ]);
                                            Log::info('status log 9');
                                            $this->info('Notif gagal dipush');
                                            $inbox = NotificationCustomer::find($notification->id)->delete();
                                        }
                                    } else {
                                        $inbox = NotificationCustomer::find($notification->id)->delete();
                                    }
                                } else {
                                    $this->info('Notif gagal dipush');
                                    $log->update([
                                        'status' => 9
                                    ]);
                                    Log::info('notif gagal di push');
                                }
                            } else if ($notifikasi->type_id == 1) {
                                $tanggal_lahir = Carbon::createFromFormat('Y-m-d', $customer->tanggal_lahir);
                                $sekarang = Carbon::now();
                                $umur = $sekarang->diffInYears($tanggal_lahir);
                                $description = str_replace('#umur#', $umur, $description);
                                $notification = NotificationCustomer::create([
                                    'customer_id' => $customer->customer_id,
                                    'notification_id' => $notifikasi->id,
                                    'read_notification' => false,
                                    'description' => $description,
                                    'created_who' => 'cronjob'
                                ]);
                                $message = [
                                    'message' => [
                                        "token" => $customer->fcmtoken_firebase,
                                        "notification" => [
                                            "body" => strip_tags($description),
                                            "title" => $notifikasi->subject
                                        ],
                                        "data" => [
                                            "id" => (string)$notification->id,
                                            "module" => "Birthday"
                                        ]
                                    ]
                                ];
                                $log->update([
                                    'status' => 2,
                                    'count_sending' => $log->count_sending + 1
                                ]);
                                if ($log->status == 2) {
                                    $this->info('log berhasil diupdate');
                                    Log::info('log berhasil dibuat');
                                    $send = self::sendNotif($message, $log, $notification->id);
                                    if ($send == 200 || $send == "200") {
                                        $log->delete();
                                    } else {
                                        if ($send == 400 || $send == "400" || $send == 404 || $send == "404") {
                                            $customer->update([
                                                'fcmtoken_firebase' => null,
                                                'updated_who' => 'cronjob notifikasi'
                                            ]);
                                        }
                                        $log->update([
                                            'status' => 9
                                        ]);
                                        $inbox = NotificationCustomer::find($notification->id)->delete();
                                    }
                                } else {
                                    $inbox = NotificationCustomer::find($notification->id)->delete();
                                }
                            } else if ($notifikasi->type_id == 2 || $notifikasi->type_id == 3 || $notifikasi->type_id == 4 || $notifikasi->type_id == 6 || $notifikasi->type_id == 7) {
                                $gadai = DataGadai::where('nomor_transaksi', $log->gadai_number)->first();
                                if (!empty($gadai)) {
                                    $tgl_jatuh_tempo = Carbon::parse($gadai->tgl_jatuh_tempo)->format('d-m-Y');
                                    $tgl_lelang = Carbon::parse($gadai->tgl_lelang)->format('d-m-Y');
                                    $description = str_replace('#nomor_transaksi#', $gadai->nomor_transaksi, $description);
                                    $description = str_replace('#tgl_jatuh_tempo#', $tgl_jatuh_tempo, $description);
                                    $description = str_replace('#tgl_lelang#', $tgl_lelang, $description);

                                    if ($notifikasi->type_id == 2) {
                                        $gadaiDetail = DataGadaiDetail::where('data_gadai_id', $gadai->id)->first();
                                        $description = str_replace('#barang#', $gadaiDetail->nama_barang, $description);
                                        $message = [
                                            'message' => [
                                                "token" => $customer->fcmtoken_firebase,
                                                "notification" => [
                                                    "body" => strip_tags($description),
                                                    "title" => $notifikasi->subject
                                                ],
                                                "data" => [
                                                    "id" => (string)$gadai->id,
                                                    "module" => "Gadai Baru"
                                                ]
                                            ]
                                        ];
                                        $log->update([
                                            'status' => 2,
                                            'count_sending' => $log->count_sending + 1
                                        ]);
                                        Log::info('status log 2');
                                        $notification = NotificationCustomer::create([
                                            'customer_id' => $customer->customer_id,
                                            'notification_id' => $notifikasi->id,
                                            'read_notification' => false,
                                            'description' => $description,
                                            'created_who' => 'cronjob'
                                        ]);
                                        if ($log->status == 2) {

                                            $send = $this->sendNotif($message, $log, $notification->id);
                                            if ($send == 200 || $send == "200") {
                                                $log->delete();
                                            } else {
                                                if ($send == 400 || $send == "400" || $send == 404 || $send == "404") {
                                                    $customer->update([
                                                        'fcmtoken_firebase' => null,
                                                        'updated_who' => 'cronjob notifikasi'
                                                    ]);
                                                }
                                                $log->update([
                                                    'status' => 9,
                                                ]);
                                                $inbox = NotificationCustomer::find($notification->id)->delete();
                                            }
                                        } else {
                                            $inbox = NotificationCustomer::find($notification->id)->delete();
                                        }
                                    } elseif ($notifikasi->type_id == 3) {
                                        $notification = NotificationCustomer::create([
                                            'customer_id' => $customer->customer_id,
                                            'notification_id' => $notifikasi->id,
                                            'read_notification' => false,
                                            'description' => $description,
                                            'created_who' => 'cronjob'
                                        ]);
                                        $message = [
                                            'message' => [
                                                "token" => $customer->fcmtoken_firebase,
                                                "notification" => [
                                                    "body" => strip_tags($description),
                                                    "title" => $notifikasi->subject
                                                ],
                                                "data" => [
                                                    "id" => (string)$gadai->id,
                                                    "module" => "Pelunasan"
                                                ]
                                            ]
                                        ];

                                        $log->update([
                                            'status' => 2,
                                            'count_sending' => $log->count_sending + 1
                                        ]);
                                        Log::info('status log 2');
                                        if ($log->status == 2) {
                                            $send = $this->sendNotif($message, $log, $notification->id);
                                            if ($send == 200 || $send == "200") {

                                                $log->delete();
                                            } else {
                                                if ($send == 400 || $send == "400" || $send == 404 || $send == "404") {
                                                    $customer->update([
                                                        'fcmtoken_firebase' => null,
                                                        'updated_who' => 'cronjob notifikasi'
                                                    ]);
                                                }
                                                $log->update([
                                                    'status' => 9,
                                                ]);
                                                $inbox = NotificationCustomer::find($notification->id)->delete();
                                            }
                                        } else {
                                            $inbox = NotificationCustomer::find($notification->id)->delete();
                                        }
                                    } elseif ($notifikasi->type_id == 4 || $notifikasi->type_id == 7) {
                                        $gadaiDetail = DataGadaiDetail::where('data_gadai_id', $gadai->id)->first();
                                        $description = str_replace('#barang#', $gadaiDetail->nama_barang, $description);
                                        $description = str_replace('#hari#', $notifikasi->reminder, $description);
                                        $notification = NotificationCustomer::create([
                                            'customer_id' => $customer->customer_id,
                                            'notification_id' => $notifikasi->id,
                                            'read_notification' => false,
                                            'description' => $description,
                                            'created_who' => 'cronjob'
                                        ]);
                                        $message = [
                                            'message' => [
                                                "token" => $customer->fcmtoken_firebase,
                                                "notification" => [
                                                    "body" => strip_tags($description),
                                                    "title" => $notifikasi->subject
                                                ],
                                                "data" => [
                                                    "id" => (string)$gadai->id,
                                                    "module" => "Reminder"
                                                ]
                                            ]
                                        ];
                                        $log->update([
                                            'status' => 2,
                                            'count_sending' => $log->count_sending + 1
                                        ]);
                                        Log::info('status log 2');
                                        if ($log->status == 2) {
                                            $send = $this->sendNotif($message, $log, $notification->id);
                                            if ($send == 200 || $send == "200") {
                                                $log->delete();
                                            } else {
                                                if ($send == 400 || $send == "400" || $send == 404 || $send == "404") {
                                                    $customer->update([
                                                        'fcmtoken_firebase' => null,
                                                        'updated_who' => 'cronjob notifikasi'
                                                    ]);
                                                }
                                                $log->update([
                                                    'status' => 9,
                                                ]);
                                                $inbox = NotificationCustomer::find($notification->id)->delete();
                                            }
                                        } else {
                                            $inbox = NotificationCustomer::find($notification->id)->delete();
                                        }
                                    } elseif ($notifikasi->type_id == 6) {
                                        $notification = NotificationCustomer::create([
                                            'customer_id' => $customer->customer_id,
                                            'notification_id' => $notifikasi->id,
                                            'read_notification' => false,
                                            'description' => $description,
                                            'created_who' => 'cronjob'
                                        ]);
                                        $message = [
                                            'message' => [
                                                "token" => $customer->fcmtoken_firebase,
                                                "notification" => [
                                                    "body" => strip_tags($description),
                                                    "title" => $notifikasi->subject
                                                ],
                                                "data" => [
                                                    "id" => (string)$gadai->id,
                                                    "module" => "Perpanjang Gadai"
                                                ]
                                            ]
                                        ];
                                        $log->update([
                                            'status' => 2,
                                            'count_sending' => $log->count_sending + 1
                                        ]);
                                        Log::info('status log 2');
                                        if ($log->status == 2) {
                                            $send = $this->sendNotif($message, $log, $notification->id);
                                            if ($send == 200 || $send == "200") {
                                                $log->delete();
                                            } else {
                                                if ($send == 400 || $send == "400" || $send == 404 || $send == "404") {
                                                    $customer->update([
                                                        'fcmtoken_firebase' => null,
                                                        'updated_who' => 'cronjob notifikasi'
                                                    ]);
                                                }
                                                $log->update([
                                                    'status' => 9,
                                                ]);
                                                $inbox = NotificationCustomer::find($notification->id)->delete();
                                            }
                                        } else {
                                            $inbox = NotificationCustomer::find($notification->id)->delete();
                                        }
                                    }
                                }
                            } elseif ($notifikasi->type_id == 5) {
                                $notification = NotificationCustomer::create([
                                    'customer_id' => $customer->customer_id,
                                    'notification_id' => $notifikasi->id,
                                    'read_notification' => false,
                                    'description' => $description,
                                    'created_who' => 'cronjob'
                                ]);
                                $message = [
                                    'message' => [
                                        "token" => $customer->fcmtoken_firebase,
                                        "notification" => [
                                            "body" => strip_tags($description),
                                            "title" => $notifikasi->subject
                                        ],
                                        "data" => [
                                            "id" => (string)$notification->id,
                                            "module" => "Promosi"
                                        ]
                                    ]
                                ];
                                $log->update([
                                    'status' => 2,
                                    'count_sending' => $log->count_sending + 1
                                ]);
                                Log::info('status log 2');
                                if ($log->status == 2) {
                                    $send = $this->sendNotif($message, $log, $notification->id);
                                    if ($send == 200 || $send == "200") {
                                        $log->delete();
                                    } else {
                                        if ($send == 400 || $send == "400" || $send == 404 || $send == "404") {
                                            $customer->update([
                                                'fcmtoken_firebase' => null,
                                                'updated_who' => 'cronjob notifikasi'
                                            ]);
                                        }
                                        $log->update([
                                            'status' => 9,
                                        ]);
                                        $inbox = NotificationCustomer::find($notification->id)->delete();
                                    }
                                } else {
                                    $inbox = NotificationCustomer::find($notification->id)->delete();
                                }
                            }
                        } else {
                            $log->update([
                                'status' => 9,
                                'count_sending' => $log->count_sending + 1
                            ]);
                        }
                    }
                } catch (\Exception $e) {
                    Log::error($e->getMessage());
                    Log::error($e->getTraceAsString());
                }
            }
            sleep(1);
        }
    }
}
