<?php

namespace App\Console\Commands;

use App\Models\DataGadai;
use App\Models\JobLog;
use App\Models\Level;
use App\Models\CronjobCheck;
use Illuminate\Console\Command;
use  App\Models\Customer;
use  App\Models\Notification;
use Carbon\Carbon;
use Google_Client;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Models\PromoPoint;
use App\Models\VoucherPromoPoint;

class CronJobLog2 extends Command
{

    protected $signature = 'job:notifikasi2';

    protected $description = 'Save job ke table job log untuk promosi';

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

    public function handle()
    {
        try {
            $tanggal_sekarang = Carbon::now()->format('Y-m-d');
            $job_check = DB::table('cronjob_check')->where('keterangan', 'INSERT NOTIFIKASI 2')->first();
            $this->info(Carbon::now()->format('Y-m-d H:i:s').' => Start Processing Notification 2');
			//$promo_point = PromoPoint::where('tgl_selesai_penukaran_point', '<', $tanggal_sekarang)->where('status', 'Aktif')->get();

            if ($job_check->status == 0) {
                DB::table('cronjob_check')->where('keterangan', 'INSERT NOTIFIKASI 2')->update([
                    'status' => 1,
                    'start_at' => Carbon::now()
                ]);

                //$notification = Notification::all();
                $notification = Notification::where(function ($query) {
                    $query->where(DB::raw('COALESCE(schedule_day, NOW())'), '>=', Carbon::now())
                          ->whereIn('type_id', [5]);
                })
                ->orWhereIn('type_id', [1])
                ->orderBy('id', 'desc')
                ->get();
                
                $this->info(Carbon::now()->format('Y-m-d H:i:s').' => Job Notification 2 Notification Collected');
                $customer = Customer::where('fcmtoken_firebase', '!=', null)->get();
                $this->info(Carbon::now()->format('Y-m-d H:i:s').' => Job Notification 2 Customer Collected');
                $promo_point = PromoPoint::where('tgl_selesai_penukaran_point', '<', $tanggal_sekarang)
                    ->where('status', 'Aktif')
                    ->get();
                $this->info(Carbon::now()->format('Y-m-d H:i:s').' => Job Notification 2 Promo Point Collected');
                foreach ($customer as $cs){
                    try {
                        foreach ($notification as $notif){
                            $job = JobLog::where('customer_id', $cs->customer_id)->where('notification_id', $notif->id)->first();
                            $jobSuccess = DB::table('job_log_success')->where('customer_id', $cs->customer_id)->where('notification_id', $notif->id)->first();
                            if ($notif->type_id == 1){
                                $tglLahir = Carbon::parse($cs->tanggal_lahir)->format('m-d');
                                $tahunSekarang = Carbon::now()->year;
                                $schedule = Carbon::parse($notif->schedule)->format('H:i:s');
                                $birthDay = Carbon::createFromFormat('Y-m-d H:i:s', $tahunSekarang. '-'.  $tglLahir. ' '. $schedule);
                                $now = Carbon::now()->format('Y-m-d H:i:s');
                                if (empty($job) && empty($jobSuccess)) {
                                    if ($birthDay < $now){
                                        $birthDay->addYear();
                                    }
                                    $nowLog = Carbon::now()->format('Y-m-d H:i:s');
                                    $this->info($nowLog.' => Processing Notification For Customer = '.$cs->customer_id.' and Notification ID = '. $notif->id.' Notif Type = '.$notif->type_id);
                                    $jobCreate = JobLog::create([
                                        'notification_id' => $notif->id,
                                        'customer_id' => $cs->customer_id,
                                        'created_who' => 'cronjob',
                                        'status' => 0,
                                        'count_sending' => 0,
                                        'tgl_proses' => $birthDay,
                                        'tipe_proses' => 'Birthday'
                                    ]);
                                    $this->info('Job Birthday berhasil dibuat, ID: '. $jobCreate->id);
                                    Log::info('Job Birthday Dibuat, ID: '.$jobCreate->id);
                                } else {
                                    $tglLahir = Carbon::parse($cs->tanggal_lahir)->format('m-d');
                                    $tahunSekarang = Carbon::now()->year;
                                    $schedule = Carbon::parse($notif->schedule)->format('H:i:s');
                                    $birthDay = Carbon::createFromFormat('Y-m-d H:i:s', $tahunSekarang. '-'.  $tglLahir. ' '. $schedule);
                                    $now = Carbon::now()->format('Y-m-d H:i:s');
                                    if (!empty($jobSuccess)){
                                        if ($birthDay < $now){
                                            $birthDay->addYear();
                                        }
                                        if (empty($job)){
                                            $nowLog = Carbon::now()->format('Y-m-d H:i:s');
                                            $this->info($nowLog.' => Create Processing Notification For Customer = '.$cs->customer_id.' and Notification ID = '. $notif->id.' Notif Type = '.$notif->type_id);
                                            $jobCreate = JobLog::create([
                                                'notification_id' => $notif->id,
                                                'customer_id' => $cs->customer_id,
                                                'created_who' => 'cronjob',
                                                'status' => 0,
                                                'count_sending' => 0,
                                                'tgl_proses' => $birthDay,
                                                'tipe_proses' => 'Birthday'
                                            ]);
                                            $this->info('Job Birthday berhasil dibuat, ID: '. $jobCreate->id);
                                            Log::info('Job Birthday Dibuat, ID: '. $jobCreate->id);
                                        }
                                    }
                                    if (!empty($job)){
                                        if ($birthDay < $now){
                                            $birthDay->addYear();
                                        }
                                        if ($job->status == 0){
                                            $nowLog = Carbon::now()->format('Y-m-d H:i:s');
                                            $this->info($nowLog.' => Update Processing Notification For Customer = '.$cs->customer_id.' and Notification ID = '. $notif->id.' Notif Type = '.$notif->type_id);
                                            $job->update([
                                                'notification_id' => $notif->id,
                                                'customer_id' => $cs->customer_id,
                                                'updated_who' => 'cronjob',
                                                'status' => 0,
                                                'count_sending' => 0,
                                                'tgl_proses' => $birthDay,
                                                'tipe_proses' => 'Birthday'
                                            ]);
                                            $this->info('Job Birthday berhasil diupdate');
                                            Log::info('Job Birthday Diupdate');
                                        }
                                    }
                                }
                            } elseif ($notif->type_id == 5){
                                $promosiTime = Carbon::parse($notif->schedule)->format('H:i');
                                $promosiDay = Carbon::parse($notif->schedule_day)->format('Y-m-d');
                                $now = Carbon::now()->format('Y-m-d');
                                if (empty($job) && empty($jobSuccess)){
                                    if ($promosiDay >= $now){
                                        $nowLog = Carbon::now()->format('Y-m-d H:i:s');
                                        $this->info($nowLog.' => Processing Notification For Customer = '.$cs->customer_id.' and Notification ID = '. $notif->id.' Notif Type = '.$notif->type_id);
                                        $jobCreate = JobLog::create([
                                            'notification_id' => $notif->id,
                                            'customer_id' => $cs->customer_id,
                                            'created_who' => 'cronjob',
                                            'status' => 0,
                                            'count_sending' => 0,
                                            'tgl_proses' => $promosiDay.' '.$promosiTime,
                                            'tipe_proses' => 'Promosi'
                                        ]);
                                        $this->info('Job Promosi berhasil dibuat, ID: '. $jobCreate->id);
                                        Log::info('Job Promosi Dibuat, ID: '. $jobCreate->id);
                                    }
                                }
                            }
                        }
                        foreach ($promo_point as $item){
                            $voucher_gb = VoucherPromoPoint::where('promo_point_id', $item->id)->get();
                            foreach ($voucher_gb as $voucher){
                                $customer = Customer::where("last_coupon_id", $voucher->id)->first();
                                if($customer != null){
                                    if($customer->coin > 0 ) {
                                        $customer->update([
                                            'coin'=> 0,
                                            'promo_point_id'=>null,
                                        ]);
                                        $this->info('Data Coin Customer berhasil di update');
                                        Log::info('Data Coin Customer berhasil di update');
                                    }
                                }else{
                                    $this->info('Tidak ada data coin Customer yang di update');
                                    Log::info('Tidak ada data coin Customer yang di update');
                                }
                            }
                        }
                    }catch(Exception $e){
                        Log::error('ERROR UNKNOWN '.$e->getMessage());
                        Log::error('ERROR UNKNOWN '.$e->getTraceAsString());

                        $this->info('ERROR UNKNOWN '.$e->getTraceAsString());
                        continue;
                    }catch(QueryException $e1){
                        Log::error('ERROR UNKNOWN '.$e1->getMessage());
                        Log::error('ERROR UNKNOWN '.$e1->getTraceAsString());

                        $this->info('ERROR UNKNOWN '.$e1->getMessage());
                        $this->info('ERROR UNKNOWN '.$e1->getTraceAsString());
                        continue;
                    }
                }
            }

            $this->info(Carbon::now()->format('Y-m-d H:i:s').' => Finish Processing Notification 2');

        }catch (Exception $e){
            Log::error($e->getMessage());
            Log::error($e->getTraceAsString());

            $this->info($e->getTraceAsString());
        } finally{
            $job_check = DB::table('cronjob_check')->where('keterangan', 'INSERT NOTIFIKASI 2')->first();

            DB::table('cronjob_check')->where('keterangan', 'INSERT NOTIFIKASI 2')->update([
                'status' => 0,
                'start_at' => null
            ]);
        }
    }
}
