<?php

namespace Mtc\Plugins\NHS\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Mtc\Modules\Members\Models\Member;

/**
 * Examples:
 *    php artisan delete_stale_members --dry-run
 */


class DeleteStaleMembers extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'delete_stale_members {--dry-run}';

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

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $is_dry_run = $this->option('dry-run');

        $stale_members = Member::query()
            ->where('is_external', 0)
            ->where('is_activated', 0)
            ->whereNull('referrer_member_id')
            ->whereRaw(DB::raw('DATEDIFF(NOW(), created_at) > 0'))
            ->get()
        ;

        if ($stale_members->count()) {

            if ($is_dry_run) {

                $this->info('You are about to delete the following members:');
                foreach ($stale_members as $stale_member) {
                    $this->info(" - id:{$stale_member->id} ({$stale_member->email})");
                }

            } else {

                $this->info('Deleting members:');
                foreach ($stale_members as $stale_member) {
                    $this->info(" - id:{$stale_member->id} ({$stale_member->email})");
                    $stale_member->delete();
                }
                $this->info('Done.');

            }

        }
    }

}
