<?php

namespace App\Console\Commands;

use App\Models\SubscriptionServicePackage;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class InvoiceGenerate extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'invoice:generate';
    protected $users;

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

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->getUpcomingExpireUsers();
        if (!$this->users)
            return;

        $this->checkPendingInvoice();

        foreach ($this->users as $user) {
            $this->generateInvoice($user);
        }
    }

    protected function getUpcomingExpireUsers()
    {
        $this->users = User::whereDate('sub_end_date', now()->addDays(config('invoice.invoice_create_before_days')))->get();
        Log::info('Upcoming expire users found: ' . $this->users->pluck('id'));
    }

    protected function checkPendingInvoice()
    {
        $already_pending_invoice = SubscriptionServicePackage::whereIn('client_id', $this->users->pluck('id'))->whereNull('payment_date')->get();
        if ($already_pending_invoice->count() > 0) {
            Log::info('Already pending invoice found for user: ' . $already_pending_invoice->pluck('client_id'));
            $this->users = $this->users->whereNotIn('id', $already_pending_invoice->pluck('client_id'));
        }
    }

    protected function generateInvoice($user)
    {
        $last_subscription = SubscriptionServicePackage::where('client_id', $user->id)->latest()->first();
        SubscriptionServicePackage::create([
            'spac_id' => $last_subscription->spac_id,
            'client_id' => $user->id,
            'client_temp_id' => $user->user_id,
            'price' => $last_subscription->price,
            'discount' => $last_subscription->discount,
            'no_of_month' => $last_subscription->no_of_month,
            'payable_amount' => $last_subscription->payable_amount,
            'invoice_number' => 'INV' . time() . rand(1000, 9999),
        ]);

        Log::info('Invoice generated for user: ' . $user->id);
    }
}
