<?php

namespace App\Console\Commands;

use App\Model\CompanyDepartment;
use App\Model\Survey;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'This command will enter the log for all the pending surveys so that the survey email will be sent to them.';

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

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

        Log::info('***************** Survey:Log ********************');
        $surveys = Survey::with('department')->where('status', 'Pending')->get();
        $userIds = [];
        if ($surveys) {

            foreach ($surveys as $survey) {
                try {
                    DB::beginTransaction();
                    Log::info('Survey Id ' . $survey->id);
                    $userIds = [];
                    if ($survey->company_department_id != 0) {
                        $userIds = $survey->department->patients->toArray();
                    } else {
                        $departments = CompanyDepartment::whereHas('patients')->where('company_user_id',$surveys->company_id)->get();

                        if ($departments) {
                            foreach ($departments as $department) {
                                if ($department->patients()->count()) {
                                    foreach ($department->patients as $patient) {
                                        $key = array_search($patient->user_id, array_column($userIds, 'user_id'));
                                        if ($key === false) {
                                            array_push($userIds, ['user_id' => $patient->user_id]);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if ($survey->logs()->createMany($userIds)) {
                        $survey->status = 'In-Progress';
                        $survey->save();
                    }
                    DB::commit();
                    Log::info('Survey Log for ' . $survey->id . ' Completed');
                } catch (\Exception $e) {
                    DB::rollBack();
                    Log::alert("Exception: ". $e->getMessage());
                } catch (\Error $er) {
                    DB::rollBack();
                    Log::alert("Error: ". $er->getMessage());
                }
            }
        }
    }
}
