<?php

namespace App\Console\Commands;

use App\Models\Lead;
use Carbon\Carbon;
use Illuminate\Console\Command;

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

	/**
	 * 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() {
		//
		$leads = Lead::query()->where( 'status', Lead::ACTIVE )
		             ->whereNull( 'last_update_status_at' )
		             ->get();

		foreach ( $leads as $lead ) {
			$createdAt = $lead->created_at;
			if ( $createdAt ) {
				if ( Carbon::now()->greaterThan( $createdAt ) ) {
					if ( Carbon::now()->diffInDays( $createdAt ) >= 7 ) {
						$lead->status = Lead::INACTIVE;
						$lead->save();
					}
				}
			}
		}


		$leadUpdates = Lead::query()->where( 'status', Lead::ACTIVE )
		                   ->whereNotNull( 'last_update_status_at' )
		                   ->get();

		foreach ( $leadUpdates as $leadUpdate ) {
			$lastUpdateAt = $leadUpdate->last_update_status_at;
			if ( $lastUpdateAt ) {
				if ( Carbon::now()->greaterThan( $lastUpdateAt ) ) {
					if ( Carbon::now()->diffInDays( $lastUpdateAt ) >= 7 ) {
						$leadUpdate->status = Lead::INACTIVE;
						$leadUpdate->save();
					}
				}
			}
		}
	}
}
