<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Models\CandidateEducation;
use App\Models\CandidateExperience;
use App\Models\CandidateInterviewResponse;
use App\Models\CandidateInterviewSchedule;
use App\Models\CandidateInterviewStatus;
use App\Models\CandidateJobApply;
use App\Models\CandidateFeedback;
use App\Models\Job;
use App\Models\Process;
use App\Models\Employer;
use App\Models\Staff;
use App\Models\Skill;
use App\Models\Qualification;
use App\Models\StatusAttributes;
use App\Models\ResumeParseCandidate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use Mail;
use App\Models\EmailTemplate;
use App\Mail\SendMail;
use DateTime;


use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Http;
use App\Models\Candidate;



class ResumeParseController extends Controller
{
    // public function uploadBulkResumes(Request $request)
    // {
    //     // $request->validate([
    //     //     'resumes.*' => 'required|file|mimes:pdf,doc,docx|max:5120'
    //     // ]);

    //     $candidates = [];
    
    //     foreach ($request->file('resumes') as $resume) {
    //         $filePath = $resume->store('resumes');
    
    //         // Parse Resume (Using AI API)
    //         $parsedData = $this->parseResume(storage_path("app/$filePath"));
    //     }
    
    //     return Response(['response' => $parsedData, 'message' => '', 'status' => 200], 200);
    // }
    
    public function uploadBulkResumes(Request $request)
    {
        // Validate multiple file uploads
        $request->validate([
            // 'resumes' => 'required|array',
            // 'resumes.*' => 'required|file|mimes:pdf,doc,docx|max:5120'
        ]);
    
        $parsedData = [];
    
        foreach ($request->file('resumes') as $resume) {
            $filePath = $resume->store('resumes');
    
            // Parse Resume (Using AI API)
            $candidates = $this->parseResume(storage_path("app/$filePath"));
    
            // Append parsed data to array
            $parsedData[] = $candidates;
        }
    
        return response()->json([
            'response' => $parsedData, 
            'message' => 'Resumes processed successfully', 
            'status' => 200
        ], 200);
    }

    
    // public function saveParsedData(Request $request){
    //     $employerId = $request->employer_id;
    //     $validator = Validator::make($request->all(), [
    //         'education' => 'required',
    //         'experience' => 'required',
    //         // 'email' => 'required',
    //         'name' => 'required',
    //         // 'linkedIn' => 'required',
    //         'phone' => 'required',
    //         // 'summary' => 'required',
    //         // 'website' => 'required',
    //         'language' => 'required',
    //         'skills' => 'required',
    //         'designation' => 'required',
    //         // 'date_of_birth' => 'required',
    //     ]);
    //     $validator->setAttributeNames([
    //         'education' => 'education',
    //         'experience' => 'experience',
    //         // 'email' => 'email',
    //         'name' => 'name',
    //         // 'linkedIn' => 'linkedIn',
    //         'phone' => 'phone',
    //         // 'summary' => 'summary',
    //         // 'website' => 'website',
    //         'language' => 'language',
    //         'skills' => 'skills',
    //         'designation' => 'designation',
    //         // 'date_of_birth' => 'date_of_birth',
    //     ]);
    //     if($validator->fails()){
    //         return Response(['response' => $validator->errors(), 'status' => 500], 200);
    //     } else {
            
    //         $savePersonalDetails = ResumeParseCandidate::create([
    //             'employer_id' => $request->employer_id,
    //             'first_name' => $request->name,
    //             'date_of_birth' => $request->date_of_birth,
    //             'education_details' => json_encode($request->education),
    //             'experience_details' => json_encode($request->experience),
    //             'email' => is_array($request->email) ? implode(',', $request->email) : $request->email,
    //             'linkedIn' => $request->linkedIn,
    //             'contact_number' => is_array($request->phone) ? implode(',', $request->phone) : $request->phone,
    //             'summary' => $request->summary,
    //             'website' => is_array($request->website) ? implode(',', $request->website) : $request->website,
    //             'language' => is_array($request->language) ? implode(',', $request->language) : $request->language,
    //             'skills' => json_encode($request->skills),
    //             'designation' => $request->designation,
                    
    //         ]);
            
    //         return Response(['response' => '', 'message' => 'Personal Details Saved Successfully', 'status' => 200], 200);
    //     }
    // }
    
    public function saveParsedData(Request $request)
    {
        $employerId = $request->employer_id;
        $candidates = $request->candidates; // Assuming the request contains an array of candidates
    
        // Ensure 'candidates' is provided and is an array
        if (!is_array($candidates) || empty($candidates)) {
            return response()->json(['response' => 'Invalid or missing candidates data', 'status' => 500], 200);
        }
    
        $savedCandidates = [];
    
        foreach ($candidates as $candidate) {
            // Validate each candidate's data
            $validator = Validator::make($candidate, [
                // 'education' => 'required',
                // 'experience' => 'required',
                'name' => 'required',
                'phone' => 'required',
                'language' => 'required',
                'skills' => 'required',
                // 'designation' => 'required',
            ]);
    
            if ($validator->fails()) {
                return response()->json(['response' => $validator->errors(), 'status' => 400], 200);
            }
    
            // Save each candidate
            $savedCandidate = ResumeParseCandidate::create([
                'employer_id' => $employerId,
                'first_name' => $candidate['name'],
                'date_of_birth' => $candidate['date_of_birth'] ?? null,
                'education_details' => json_encode($candidate['education']),
                'experience_details' => json_encode($candidate['experience']),
                'email' => isset($candidate['email']) ? (is_array($candidate['email']) ? implode(',', $candidate['email']) : $candidate['email']) : null,
                'linkedIn' => $candidate['linkedIn'] ?? null,
                'contact_number' => is_array($candidate['phone']) ? implode(',', $candidate['phone']) : $candidate['phone'],
                'summary' => $candidate['summary'] ?? null,
                'website' => isset($candidate['website']) ? (is_array($candidate['website']) ? implode(',', $candidate['website']) : $candidate['website']) : null,
                'language' => is_array($candidate['language']) ? implode(',', $candidate['language']) : $candidate['language'],
                'skills' => json_encode($candidate['skills']),
                'designation' => $candidate['designation'],
            ]);
    
            $savedCandidates[] = $savedCandidate;
        }
    
        return response()->json([
            'response' => $savedCandidates,
            'message' => count($savedCandidates) . ' Candidates Saved Successfully',
            'status' => 200
        ], 200);
    }

    
    // public function sendParsedData(Request $request){
    //     $employerId = Auth::user()->id;
        
    //     $parsedData = ResumeParseCandidate::where('employer_id', $employerId)->get();
    //     $parsedDetailsData = array();
        
    //     foreach($parsedData as $key => $value){
    //         $parsedDetailsData[$key]['id'] = $value->id;
    //         $parsedDetailsData[$key]['employer_id'] = $value->employer_id;
    //         $parsedDetailsData[$key]['name'] = $value->first_name;
    //         $parsedDetailsData[$key]['date_of_birth'] = $value->date_of_birth;
    //         $parsedDetailsData[$key]['education'] = json_decode($value->education_details);
    //         $parsedDetailsData[$key]['experience'] = json_decode($value->experience_details);
    //         $parsedDetailsData[$key]['email'] = $value->email;
    //         $parsedDetailsData[$key]['linkedIn'] = $value->linkedIn;
    //         $parsedDetailsData[$key]['phone'] = $value->contact_number;
    //         $parsedDetailsData[$key]['summary'] = $value->summary;
    //         $parsedDetailsData[$key]['website'] = $value->website;
    //         $parsedDetailsData[$key]['language'] = $value->language;
    //         $parsedDetailsData[$key]['skills'] = $value->skills;
    //         $parsedDetailsData[$key]['designation'] = $value->designation;
            
    //     }
        
    //     return Response(['response' => $parsedDetailsData, 'message' => '', 'status' => 200], 200);
        
    // }
    
    public function sendParsedData(Request $request){
    $employerId = Auth::user()->id;
    
    // Handle multiple delete functionality
    if ($request->filled('action')) {

                $idList = $request->idList;
                if ($idList) {
                 if ($request->action == 'delete') {
                        ResumeParseCandidate::whereIn('id', explode(',', $idList))->delete();
                    }
                }
                
                return Response(['response' => '', 'message' => 'Record Deleted Successfully', 'status' => 200], 200);
            }
    
    $parsedData = ResumeParseCandidate::where('employer_id', $employerId)->get();
    $parsedDetailsData = array();
    
    foreach($parsedData as $key => $value){
        $parsedDetailsData[$key]['id'] = $value->id;
        $parsedDetailsData[$key]['employer_id'] = $value->employer_id;
        $parsedDetailsData[$key]['name'] = $value->first_name;
        $parsedDetailsData[$key]['date_of_birth'] = $value->date_of_birth;
        $parsedDetailsData[$key]['education'] = json_decode($value->education_details);
        $parsedDetailsData[$key]['experience'] = json_decode($value->experience_details);
        $parsedDetailsData[$key]['email'] = $value->email;
        $parsedDetailsData[$key]['linkedIn'] = $value->linkedIn;
        $parsedDetailsData[$key]['phone'] = $value->contact_number;
        $parsedDetailsData[$key]['summary'] = $value->summary;
        $parsedDetailsData[$key]['website'] = $value->website;
        $parsedDetailsData[$key]['language'] = $value->language;
        $parsedDetailsData[$key]['skills'] = $value->skills;
        $parsedDetailsData[$key]['designation'] = $value->designation;
    }
    
    return response(['response' => $parsedDetailsData, 'message' => '', 'status' => 200], 200);
}
    
    


    private function parseResume($filePath)
    {
        $response = Http::withHeaders([
            'Authorization' => 'Bearer aff_647e4a792866be87c5e754271e8f6c17bfd9a6e6'
        ])->attach(
            'file', file_get_contents($filePath), basename($filePath)
        )->post('https://api.affinda.com/v2/resumes', []);
    
    return $response->json();
    }
    
    public function deleteParsedData(Request $request){
        $id = $request->id;
        $employerId = $request->employer_id;
        
        $record = ResumeParseCandidate::where('employer_id', $employerId)->where('id', $id)->first();
        
        if(!empty($record)){
            ResumeParseCandidate::where('employer_id', $employerId)->where('id', $id)->delete();
            
            return Response(['response' => 'Record Deleted Successfully.', 'message' => 'Record Deleted Successfully.', 'status' => 200], 200);
        } else{
            
            return response(['response' => 'Record not found', 'message' => 'Record not found', 'status' => 500], 200);
            
        }
        
    }
    
    
}