<?php

namespace App\Console\Commands;

use App\Models\User;
use Illuminate\Console\Command;

class FixEmployeeId extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:fix-employee-id';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = "Fix employee IDs whose length is 5 by adding 0 as a first character.";

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {

        $users = User::has('employeeMetaInfo')->without([
            'currentRole',
            'roles',
            'permissions',
            'storage',
            'employeeMetaInfo',
            'supervisor',
            'user_supervisor',
            'exitInterview',
            'userProfilePicture',
            'profileBasicInfo'
        ])->get();

        $date = date('Y-m-d');
        $fixEmployeeIdCsv = fopen(public_path("fixed-employee-id-{$date}.csv"), 'w');

        foreach ($users as $user) {
            $employeeId = $user->employeeMetaInfo->employee_id;

            if (strlen($employeeId) <= 5) {
                $fixEmployeeId = sprintf("%06d", $employeeId);
                $this->info("{$employeeId} to {$fixEmployeeId} - {$user->name} fixing...");
                $user->employeeMetaInfo()->update([
                    'employee_id' => $fixEmployeeId,
                ]);
                $this->info("{$employeeId} to {$fixEmployeeId} - {$user->name} fixed");

                fputcsv($fixEmployeeIdCsv, [$employeeId, $fixEmployeeId, $user->name]);
            }
        }

        fclose($fixEmployeeIdCsv);
    }
}
