<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Foundation\Auth\User;

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

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $users = User::whereNotNull('tenant_host')
            ->whereNotNull('tenant_database')
            ->whereNotNull('tenant_username')
            ->whereNotNull('tenant_password')
            ->get([
                'id',
                'tenant_host',
                'tenant_database',
                'tenant_username',
                'tenant_password',
            ]);

        if ($users->isEmpty()) {
            $this->warn('Nessun utente con info di database trovata.');
            return Command::SUCCESS;
        }

        $tenants = $users->unique(function ($u) {
            return $u->tenant_host . '|' . $u->tenant_database . '|' . $u->tenant_username;
        });

        foreach ($tenants as $userTenant) {
            $this->info("Processo tenant db={$userTenant->tenant_database} (user id={$userTenant->id})");

            app(\App\Http\Middleware\TenantMiddleware::class)->setupTenantConnection($userTenant);

            $expire_date = date("Y-m-d", strtotime("+1 month"));
            $expire_date_it = date("d/m/Y", strtotime("+1 month"));
            $certificates = \App\Models\MemberCertificate::where('expire_date', $expire_date)->get();
            foreach ($certificates as $certificate) {
                $new = \App\Models\MemberCertificate::where('expire_date', '>', $expire_date)->where('member_id', $certificate->member_id)->count();
                if ($new == 0) {
                    $phone = $certificate->member->phone;
                    $message = 'Ciao ' . $certificate->member->first_name . ', ci risulta che il tuo certificato medico scade il ' . $expire_date_it . '. Per continuare ad allenarti senza problemi, ricordati di rinnovarlo in tempo. Ti aspettiamo in campo!';
                    $params = array(
                        'to'            => '+39' . $phone,
                        'from'          => env('SMS_FROM', 'Leezard'),
                        'message'       => $message,
                        'format'        => 'json',
                    );
                    $r = sms_send($params);
                    Log::info("SMS");
                    Log::info($r);
                    sleep(1);
                }
            }

            $expire_date = date("Y-m-d", strtotime("+15 days"));
            $expire_date_it = date("d/m/Y", strtotime("+15 days"));
            $certificates = \App\Models\MemberCertificate::where('expire_date', $expire_date)->get();
            foreach ($certificates as $certificate) {
                $new = \App\Models\MemberCertificate::where('expire_date', '>', $expire_date)->where('member_id', $certificate->member_id)->count();
                if ($new == 0) {
                    $phone = $certificate->member->phone;
                    $message = 'Ciao ' . $certificate->member->first_name . ', ci risulta che il tuo certificato medico scade il ' . $expire_date_it . '. Per continuare ad allenarti senza problemi, ricordati di rinnovarlo in tempo. Ti aspettiamo in campo!';
                    $params = array(
                        'to'            => '+39' . $phone,
                        'from'          => env('SMS_FROM', 'Leezard'),
                        'message'       => $message,
                        'format'        => 'json',
                    );
                    $r = sms_send($params);
                    Log::info("SMS");
                    Log::info($r);
                    sleep(1);
                }
            }
        }

        return Command::SUCCESS;
    }
}
