<?php

namespace App\Console\Commands;

use App\Models\User;
use App\Models\User_details;
use App\Models\Employee;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class DeactiveNonPaymentGatewayUsersCommand extends Command
{
    /**
     * Emails that are allowed (payment gateway / demo users) - these will be skipped.
     *
     * @var array
     */
    protected $allowedEmails = [
        'user@bkashcom',
        'user@bkash.com',
        'account@bkash.com',
        'Bkash-Online@demo.com',
        'rokibulhasan.356@gmail.com',
        'limitedyetfix@gmail.com',
        'admin@gmail.com',
        'support@yetfix.com',
        'user@nagadcom',
        'user@nagad.com',
        'Nagad-Online@demo.com',
        'SSL-Commerz@demo.com',
        'user@upay.com',
    ];

    /**
     * Employee names that are allowed (payment gateway) - these will NOT be set to pending.
     *
     * @var array
     */
    protected $allowedEmployeeNames = [
        'Bkash-Online',
        'bkash',
        'Nagad-Online',
        'nagad',
        'SSL-Commerz',
        'upay',
        'System',
        'Support'
    ];

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'users:deactive-non-payment-gateway';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Deactive users (and related employees) whose email is not in the payment gateway list; rewrite email as id_user mail, set user_status to deactive, employee status to pending';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->info('Finding users whose email is NOT in the allowed payment gateway list...');

        $users = User::whereNotIn('email', $this->allowedEmails)->get();

        $this->info('Found ' . $users->count() . ' user(s) to update.');

        if ($users->isEmpty()) {
            $this->info('Nothing to do.');
            return Command::SUCCESS;
        }

        $updatedUsers = 0;
        $updatedEmployees = 0;
        $errors = 0;

        foreach ($users as $user) {
            try {
                DB::beginTransaction();

                // Rewrite email as id_user mail only once (e.g. 5_john@gmail.com); skip if already in id_ format
                $prefix = $user->id . '_';
                if (strpos($user->email, $prefix) !== 0) {
                    $newEmail = $prefix . $user->email;
                    $user->update(['email' => $newEmail]);
                } else {
                    $newEmail = $user->email;
                }
                $updatedUsers++;

                // Set user_status to deactive in user_details
                User_details::where('user_id', $user->id)->update(['user_status' => 'deactive']);

                // Set related employees (name not in payment gateway list) status to pending
                $count = Employee::where('admin_user_id', $user->id)
                    ->orWhereNotIn('name', $this->allowedEmployeeNames)
                    ->update(['status' => 'pending']);
                $updatedEmployees += $count;

                DB::commit();

                $this->line("User id {$user->id}: email -> {$newEmail}, user_status -> deactive, employees updated: {$count}");
            } catch (\Exception $e) {
                DB::rollBack();
                $this->error("Error for user id {$user->id}: " . $e->getMessage());
                $errors++;
            }
        }

        $this->info("\n=== Summary ===");
        $this->info("Users updated (email + user_status): {$updatedUsers}");
        $this->info("Related employees set to pending: {$updatedEmployees}");
        $this->info("Errors: {$errors}");

        return $errors > 0 ? Command::FAILURE : Command::SUCCESS;
    }
}
