<?php

namespace App\Console\Commands;

use App\Helpers\CommonHelper;
use App\Model\SurveyLogsForCron;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'This command will execute the pending survey logs and send survey email to user(s).';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle() {
        Log::info('************************************* survey:execute-logs *************************************');
        $logs = SurveyLogsForCron::with('user')->where('status', 'Pending')->get();
        if ($logs) {
            foreach ($logs as $log) {
                Log::info('Log for id ' . $log->id);
                $user = $log->user;
                if ($user) {
                    $email = $user->email;
                    Log::info('User Id ' . $user->id);

                    try {
                        DB::beginTransaction();

                        $mail_params['USER_NAME'] = $user->name;
                        $mail_params['SURVEY_LINK'] = env('B2B_APP_URL') . '/survey/submit/' . base64_encode($log->survey_id);
                        Log::info($mail_params);
                        CommonHelper::__sendMail('survey', $email, $mail_params);
                        $log->status = 'Sent';
                        $log->save();

                        $log->survey()->update([
                            'sent_at' => Carbon::now(),
                            'status' => 'Completed'
                        ]);

                        DB::commit();

                    } catch (\Exception $e) {
                        DB::rollBack();
                        Log::alert('Exception: ' . $e->getMessage());
                    }
                }
            }
        }
    }
}
