<?php

namespace App\Console\Commands;

use App\Models\Laboratory;
use App\Models\Publication;
use App\Models\PublicationReceiver;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class NotifyExpireLab extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'notify:send';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        try{
           $labs = Laboratory::query()->where('record_status_id', 1)
                ->whereNotNull('end_date')
                ->whereRaw("DATEDIFF(end_date, CURDATE())=7")->get();
                
                Log::channel('jobs')->info($labs);

            foreach ($labs as $lab){

                $date= date_create(date('Y-m-d', strtotime($lab->end_date)));
                date_add($date,date_interval_create_from_date_string("7 days"));
                $_disable_date = date_format($date,"d-M-Y");

                $publication = Publication::query()->create([
                    'title_en' => "License Expiry Alert",
                    'title_kh' => "សេចក្តីជូនដំណឹងអំពីការផុតសុំពលភាពនៃការប្រើប្រាស់ប្រព័ន្ធ Labonak",
                    'start_date' => date('Y-m-d'),
                    'end_date' => date('Y-m-d', strtotime($lab->end_date)),
                    'description' => "គណនីប្រើប្រាស់ប្រព័ន្ធរបស់លោកអ្នកនឹងផ្អាកប្រើប្រាស់ជាបណ្ណោះអាសន្ននៅថ្ងៃ " . $_disable_date . " សូមទំនាក់ទំនងទៅកាន់ System Administrator ដើម្បីបន្តសុពលភាព។ សូមអរគុណ!"
                ]);

                PublicationReceiver::query()->create([
                    'publication_id' => $publication->id,
                    'lab_id' => $lab->id,
                    'created_by' => 1
                ]);
            }

        } catch (\Exception $e){
            Log::channel('jobs')->error($e->getMessage());
        }
    }
}
