<?php

namespace App\Console\Commands;

use App\Components\Functions;
use App\Models\UserPackage;
use App\User;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Str;

class CheckEndDateOwner extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'check:end-date';

    /**
     * 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 mixed
     */
    public function handle()
    {
        //
        $users = User::query()
            ->where('type', User::OWNER)
           // ->where('phone', '0868987355')
            ->get();

        foreach ($users as $user) {
            $isOver = false;
            $userPackage = UserPackage::query()->where('user_id', $user->id)->first();
            if ($userPackage) {
                $endDate = $userPackage->end_date;
                if ($endDate) {

                    if (Carbon::now()->greaterThan($endDate)) {
                        $isOver = true;
                        $user->is_over_date = true;

                        if (Carbon::now()->diffInDays($endDate) >= 5) {
                            $user->payment_status = User::PAYMENT_NOT_USE;
                        } else {
                            $user->payment_status = User::PAYMENT_OVER;
                        }

                    } else {
                        if (in_array(Carbon::now()->diffInDays($endDate->copy()) + 1, [5, 10, 15])) {
                            $ownerPhone = $user->phone;
                            $ownerPhone = ltrim($ownerPhone, '0');
                            $ownerPhone = '84' . $ownerPhone;
                            Functions::sendZns([
                                'template_id' => 205714,
                                'phone' => $ownerPhone,
                                'data' => [
                                    'customer_name' => $user->name,
                                    'expire_date' => $endDate->copy()->format('d/m/Y'),
                                    'remain_date' => Carbon::now()->diffInDays($endDate->copy()) + 1,
                                    'customer_phone' => $user->phone,
                                ]
                            ]);
                            $this->line('Send zns: '.$user->id);
                        }
                    }
                    $user->save();
                }
            }

            $this->line('Done with ' . $user->id . ', is_over_date: ' . $isOver);
        }

    }
}
