<?php

namespace App\Console\Commands;

use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Yajny\Member\Models\Member;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Deactivate the old users';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $oneYear = Carbon::now()->subYear(1)->format('Y-m-d');
        $user_ids = DB::select(
            DB::raw(
                "SELECT user_id FROM yajny.users where active = 1 and user_id not in (SELECT distinct(user_id) FROM analytics.analytics_events where created_at > '" . $oneYear . "' and user_id is not null) LIMIT 0,5000;"
            ));
        foreach ($user_ids as $user_id) {
            $user = Member::find($user_id->user_id);
            if ($user->created_at > $oneYear) continue;
            DB::table('deleted_users')->insert([
                "user_id" => $user->user_id,
                "user_email" => $user->email,
                "mobile_number" => $user->phone_number,
                "reason" => 'inactive user',
                "deleted_at" => now()
            ]);
            $user->delete();
        }
    }
}
