<?php

namespace App\Console\Commands;

use App\Helpers\SourceCodeHelper;
use App\Models\Candidate;
use App\Models\Firm;
use App\Models\ReviewCandidate;
use App\Services\CandidateService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class checkNotAtEmpoyer extends Command
{
    /** /checkNotAtEmployer
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'check-not-at-employer';

    protected $octaparseApiService;

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'automatically check candidates who are not at their employer anymore';

    /**
     * Execute the console command.
     */
    public function handle(CandidateService $candidateService)
    {
        $candidates = $this->getCandidatesFromReview();
        // if(count($candidates) == 0) {
        //     $candidates = $this->getNotUpdatedCandidates();
        // }
        if(count($candidates) > 0) {
            foreach ($candidates as $candidate) {
                $notAtEmployer = false;
                $firm = Firm::select('id','name','url','not_found_page_404_header','not_found_page_title')->where('id',$candidate->firm_id)->get()->first();
                $response = SourceCodeHelper::getSourceCodeFromUrl($candidate->url,true);
                if($firm->not_found_page_404_header == 1) {
                    $notFoundByHeader = SourceCodeHelper::checkNotFoundPageWith404Header($response);
                    if($notFoundByHeader) {
                        Log::channel('not_at_employer')->info("Not found page found by header for: " . $candidate->url);
                        $notAtEmployer = true;
                    }
                }
                if(!$notAtEmployer) {
                    $notFoundByTitle = SourceCodeHelper::checkNotFoundPageWithTitle($response,$firm,true);
                    if($notFoundByTitle) {
                        Log::channel('not_at_employer')->info("Not found page found by title for: " . $candidate->url);
                        $notAtEmployer = true;
                    }
                }
                if($notAtEmployer) {
                    ReviewCandidate::where('candidate_id',$candidate->id)->update(['status'=>config('constants.status.review_candidates.approved'),'reviewed_by'=>null]);
                    $candidateService->updateCandidate($candidate->id,array('validation'=>config('constants.validation.not_at_employer'), 'not_at_employer_check' => now()));
                }
                else {
                    if($response->status() == 200) {
                        if($candidate->url == $response->headers()['sa-final-url'][0]) { // candidate existed but not in octaprse scraped sheet
                            Log::channel('not_at_employer')->info("This page exists: " . $candidate->url);
                            ReviewCandidate::where('candidate_id',$candidate->id)->update(['status'=>config('constants.status.review_candidates.rejected'),'reviewed_by'=>null]);
                        } else {
                            $checkCandidate = Candidate::where('url',$response->headers()['sa-final-url'][0])->first();
                            if($checkCandidate) { // already exists
                                Log::channel('not_at_employer')->info("deleted the new candidate: " .$response->headers()['sa-final-url'][0]);
                                $candidateService->deleteCandidate($checkCandidate->id);
                                Log::channel('not_at_employer')->info("updated candidate with url: " .$response->headers()['sa-final-url'][0]);
                                $candidateService->updateCandidate($candidate->id,array('url'=>$response->headers()['sa-final-url'][0]));
                                Log::channel('not_at_employer')->info("This page exists: " . $candidate->url);
                                ReviewCandidate::where('candidate_id',$candidate->id)->update(['status'=>config('constants.status.review_candidates.rejected'),'reviewed_by'=>null]);
                            } else {
                                $notFoundByTitleExactMatch = SourceCodeHelper::checkNotFoundPageWithTitleExactMatch($response,$firm,true);
                                if($notFoundByTitleExactMatch) {
                                    Log::channel('not_at_employer')->info("Not found page found by title exact match for: " . $candidate->url);
                                    ReviewCandidate::where('candidate_id',$candidate->id)->update(['status'=>config('constants.status.review_candidates.approved'),'reviewed_by'=>null]);
                                    $candidateService->updateCandidate($candidate->id,array('validation'=>config('constants.validation.not_at_employer'), 'not_at_employer_check' => now()));
                                }
                            }
                        }
                    } else {
                        ReviewCandidate::where('candidate_id',$candidate->id)->update(['status'=>config('constants.status.review_candidates.script_checked_pending'),'reviewed_by'=>null]);
                        Log::channel('not_at_employer')->info("Not able to check this page (status code ".$response->status()."): " . $candidate->url);
                    }
                }
            }
        }
    }

    private function getCandidatesFromReview()
    {
        $candidateIds = ReviewCandidate::where('status',0)
                                        ->limit(2)
                                        ->orderBy('created_at','desc')
                                        ->pluck('candidate_id')
                                        ->toArray();
        if(!empty($candidateIds)) {
            return Candidate::select('id','firm_id','url')->whereIn('id',$candidateIds)->get();
        }
        return [];
    }

    public function getNotUpdatedCandidates()
    {
        return Candidate::where('validation','!=',config('constants.validation.not_at_employer'))
                                        ->select('id','firm_id','url')
                                        ->where('not_at_employer_check','<=',now()->subDays(1))
                                        ->limit(2)
                                        ->get();
    }
}
