<?php

namespace App\Http\Controllers;

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\Applicant;
use App\Models\ApplicantProcessHistory;
use App\Models\Employee;
use App\Models\Mrf;
use App\Notifications\JobApplication;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;
use PHPUnit\Event\Code\Throwable;
use Illuminate\Support\Str;

class ApplicantController extends Controller
{
    
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $keyword = $request->input('keyword', '');
        $perPage = $request->input('per_page',PHP_INT_MAX);
        $sortBy = $request->input('sortBy', '');
        $sortType = $request->input('sortType', '');
        // $data = Applicant::with(
        //     ['job' => function () {
                
        //     }, 'jobtitle'])
        // ->where(function ($query) use ($keyword) {
        $data = Applicant::with(['job', 'job.jobtitle', 'process_history'])->where(function ($query) use ($keyword) {
            $keyword = str_replace(" ", "%", $keyword);
            $query->where('firstname', 'like', '%' . $keyword . '%');
            $query->orWhere('middlename', 'like', '%' . $keyword . '%');
            $query->orWhere('lastname', 'like', '%' . $keyword . '%');
        })->where('blocklist', 0);

        if (!empty($sortBy) && !empty($sortType)) {
            $data = $data->orderBy($sortBy, $sortType);
        }

        $data = $data->paginate($perPage);
        
        return response()->json($data);
    }

    public function store(Request $request)
    {
        // Validation rules
        $validator = Validator::make($request->all(), [
            // Personal Information
            'firstname' => 'required|string|max:150',
            'middlename' => 'nullable|string|max:150',
            'lastname' => 'required|string|max:150',
            'suffix' => 'nullable|string|max:10',
            'birthdate' => 'required|date|before:today',
            'contact_number' => 'required|string|max:20',
            'email' => 'required|email|max:100',
            
            // Current Address
            'region' => 'required',
            'province' => 'required',
            'city_municipality' => 'required',
            'barangay' => 'required',
            'current_address' => 'required|string|max:250',
            
            // Permanent Address
            'permanent_region' => 'required',
            'permanent_province' => 'required',
            'permanent_city_municipality' => 'required',
            'permanent_barangay' => 'required',
            'permanent_address' => 'required|string|max:250',
            
            // Provincial Address (optional)
            'provincial_region' => 'nullable',
            'provincial_province' => 'nullable',
            'provincial_city_municipality' => 'nullable',
            'provincial_barangay' => 'nullable',
            'provincial_address' => 'nullable|string|max:250',
            
            // Work Preferences
            'work_schedule' => 'required|in:WFH,Hybrid,Onsite',
            
            // Professional Background
            'last_position' => 'nullable|string|max:150',
            'last_salary' => 'nullable|string|max:20',
            'second_position' => 'nullable|string|max:150',
            'second_salary' => 'nullable|string|max:20',
            'cover_letter' => 'required|string',
            
            // Documents
            'picture' => 'required|image|mimes:jpg,jpeg,png,gif,webp|max:5120', // 5MB max
            'resume' => 'required|mimes:pdf,doc,docx|max:10240', // 10MB max
            
            // HR Questions & Privacy
            'hr_questions' => 'required|json',
            'data_privacy_accepted' => 'required|accepted',
        ]);

        // If validation fails return with error message
        if ($validator->fails()) {
            $errors = $validator->errors();
            $first = $errors->getMessages();
            return response()->json([
                'status'  => false,
                'message' => (reset($first))[0],
                'errors'  => $errors
            ], Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        DB::connection()->beginTransaction();
        try {
            // Handle picture upload
            $picture_name = null;
            if ($request->hasFile('picture')) {
                $picture = $request->file('picture');
                $picture_name = time() . '_picture_' . $picture->getClientOriginalName();
                $picture_path = "applicant/pictures/" . $picture_name;
                
                if (!Storage::disk('local')->put($picture_path, file_get_contents($picture))) {
                    throw new \Exception('Failed to upload profile picture');
                }
            }

            // Handle resume upload
            $resume_name = null;
            if ($request->hasFile('resume')) {
                $resume = $request->file('resume');
                $resume_name = time() . '_resume_' . $resume->getClientOriginalName();
                $resume_path = "applicant/resumes/" . $resume_name;
                
                if (!Storage::disk('local')->put($resume_path, file_get_contents($resume))) {
                    throw new \Exception('Failed to upload resume');
                }
            }

            // Calculate age from birthdate
            $age = null;
            if ($request->birthdate) {
                $birthdate = new \DateTime($request->birthdate);
                $today = new \DateTime();
                $age = $today->diff($birthdate)->y;
            }

            // Get label values from the request (assuming they're sent as objects with 'value' and 'label')
            // If they're sent as just values, use them directly
            $regionLabel = is_array($request->region) ? ($request->region['label'] ?? null) : $request->region;
            $provinceLabel = is_array($request->province) ? ($request->province['label'] ?? null) : $request->province;
            $cityLabel = is_array($request->city_municipality) ? ($request->city_municipality['label'] ?? null) : $request->city_municipality;
            $barangayLabel = is_array($request->barangay) ? ($request->barangay['label'] ?? null) : $request->barangay;
            
            $permanentRegionLabel = is_array($request->permanent_region) ? ($request->permanent_region['label'] ?? null) : $request->permanent_region;
            $permanentProvinceLabel = is_array($request->permanent_province) ? ($request->permanent_province['label'] ?? null) : $request->permanent_province;
            $permanentCityLabel = is_array($request->permanent_city_municipality) ? ($request->permanent_city_municipality['label'] ?? null) : $request->permanent_city_municipality;
            $permanentBarangayLabel = is_array($request->permanent_barangay) ? ($request->permanent_barangay['label'] ?? null) : $request->permanent_barangay;
            
            $provincialRegionLabel = is_array($request->provincial_region) ? ($request->provincial_region['label'] ?? null) : $request->provincial_region;
            $provincialProvinceLabel = is_array($request->provincial_province) ? ($request->provincial_province['label'] ?? null) : $request->provincial_province;
            $provincialCityLabel = is_array($request->provincial_city_municipality) ? ($request->provincial_city_municipality['label'] ?? null) : $request->provincial_city_municipality;
            $provincialBarangayLabel = is_array($request->provincial_barangay) ? ($request->provincial_barangay['label'] ?? null) : $request->provincial_barangay;

            // Create applicant record
            $applicant = Applicant::create([
                'job_id' => $request->job_id,
                
                // Personal Information
                'firstname' => $request->firstname,
                'middlename' => $request->middlename,
                'lastname' => $request->lastname,
                'suffix' => $request->suffix,
                'birthdate' => $request->birthdate,
                'age' => $age,
                'contact_number' => $request->contact_number,
                'email' => $request->email,
                'picture' => $picture_name,
                
                // Current Address
                'region' => $regionLabel,
                'province' => $provinceLabel,
                'city_municipality' => $cityLabel,
                'barangay' => $barangayLabel,
                'current_address' => $request->current_address,
                
                // Permanent Address
                'permanent_region' => $permanentRegionLabel,
                'permanent_province' => $permanentProvinceLabel,
                'permanent_city_municipality' => $permanentCityLabel,
                'permanent_barangay' => $permanentBarangayLabel,
                'permanent_address' => $request->permanent_address,
                
                // Provincial Address (optional)
                'provincial_region' => $provincialRegionLabel,
                'provincial_province' => $provincialProvinceLabel,
                'provincial_city_municipality' => $provincialCityLabel,
                'provincial_barangay' => $provincialBarangayLabel,
                'provincial_address' => $request->provincial_address,
                
                // Work Preferences
                'work_schedule' => $request->work_schedule,
                
                // Professional Background
                'last_position' => $request->last_position,
                'last_salary' => $request->last_salary,
                'second_position' => $request->second_position,
                'second_salary' => $request->second_salary,
                'cover_letter' => $request->cover_letter,
                
                // Documents
                'resume' => $resume_name,
                
                // HR Questions & Privacy
                'hr_questions' => $request->hr_questions, // Already JSON string from frontend
                'data_privacy_accepted' => $request->data_privacy_accepted ? true : false,
                
                // Status
                'status' => 0,
            ]);

            // Get MRF details for email notification
            $mrf = Mrf::with('company:id,email', 'jobtitle:id,name')
                ->select('company_id', 'job_title')
                ->where('id', $request->job_id)
                ->first();

            // Prepare data for email
            $dataForEmail = $applicant;
            $dataForEmail['position'] = $mrf->jobtitle->name;
            $dataForEmail['full_name'] = trim($request->firstname . ' ' . ($request->middlename ?? '') . ' ' . $request->lastname . ' ' . ($request->suffix ?? ''));

            // Get the company email
            $companyEmail = $mrf->company->email;

            // Send the notification directly to the email address
            Notification::route('mail', $companyEmail)->notify(new JobApplication($dataForEmail));

            DB::connection()->commit();

            return response()->json([
                'status'  => true,
                'message' => 'Application submitted successfully!',
                'data'    => $applicant
            ], 201);

        } catch (\Throwable $e) {
            DB::connection()->rollback();

            // Clean up uploaded files if transaction fails
            if (isset($picture_name)) {
                Storage::disk('local')->delete("applicant/pictures/" . $picture_name);
            }
            if (isset($resume_name)) {
                Storage::disk('local')->delete("applicant/resumes/" . $resume_name);
            }

            return response()->json([
                'status'  => false,
                'message' => 'Unable to process request. Please try again.',
                'error'   => config('app.debug') ? $e->getMessage() : 'An error occurred'
            ], 500);
        }
    }

    // public function store(Request $request)
    // {
    //     // Validate the incoming request data
    //     $validator = Validator::make($request->all(), [
    //         'name' => [
    //             'required',
    //         ]
    //     ]);

    //     /** If validation fails return with error message */
    //     if ($validator->fails()) {
    //         $errors = $validator->errors();
    //         $first = $errors->getMessages();
    //         return response()->json([
    //             'status'  => false,
    //             'message' => (reset($first))[0],
    //             'errors'  => $errors
    //         ], Response::HTTP_UNPROCESSABLE_ENTITY);
    //     }

    //     DB::connection()->beginTransaction();

    //     try {

    //         $data = Applicant::create($request->all());

    //         DB::connection()->commit();

    //         return response()->json([
    //             'message' => 'Record Successfully added!',
    //             'status' => 'success',
    //         ],201);

    //     } catch (Throwable $e) {
    //         DB::connection()->rollback();
    //         return response()->json([
    //             'status'  => false,
    //             'message' => 'Unable to process request. Please try again.',
    //             'data'    => $e->getMessage()
    //         ]);
    //     }
    // }

    public function update(Request $request, int $id)
    {
        $data = Applicant::withTrashed()->where('id', $id)->first();

        if (!$data) {
            return response()->json(['messages' => 'No data found.'], 404);
        }

        $validator = Validator::make($request->all(),
            [
                // 'name' => [
                //     'required',
                //     'min:2',
                //     Rule::unique('applicants')->ignore($id)->whereNull('deleted_at')
                // ]
            ]
        );

        /** If validation fails return with error message */
        if ($validator->fails()) {
            $errors = $validator->errors();
            $first = $errors->getMessages();
            return response()->json([
                'status'  => false,
                'message' => (reset($first))[0],
                'errors'  => $errors
            ], Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        DB::connection()->beginTransaction();

        try {
            $request['deleted_at'] = null;

            // Fill other attributes
            $data->fill($request->except('deleted_at'));

            // Explicitly set deleted_at to null
            $data->deleted_at = null;

            $data->save();

            $data->touch();

            DB::connection()->commit();

            return response()->json([
                'message' => 'Record Successfully updated!',
                'status' => 'success',
                'data' => $data,
            ],201);

        } catch (Throwable $e) {
            DB::connection()->rollback();
            return response()->json([
                'status'  => false,
                'message' => 'Unable to process request. Please try again.',
                'data'    => $e->getMessage()
            ]);
        }
    }

    public function updateStatus(Request $request, int $id)
    {
        // dd($request->all());
        $data = Applicant::where('id', $id)->first();

        $applicant_history = ApplicantProcessHistory::create([
            'applicant_id' => $id,
            'action_id' => $request->status,
            'action_made' => date('Y-m-d')
        ]);
        
        if (!$data) {
            return response()->json(['messages' => 'No data found.'], 404);
        }

        $validator = Validator::make($request->all(),
            [
                // 'name' => [
                //     'required',
                //     'min:2',
                //     Rule::unique('applicants')->ignore($id)->whereNull('deleted_at')
                // ]
            ]
        );

        /** If validation fails return with error message */
        if ($validator->fails()) {
            $errors = $validator->errors();
            $first = $errors->getMessages();
            return response()->json([
                'status'  => false,
                'message' => (reset($first))[0],
                'errors'  => $errors
            ], Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        DB::connection()->beginTransaction();

        try {
            if($request->status == 4){
                $request['offered_date'] = date("Y-m-d");
            }

            if($request->status == 6){
                $request['status'] = 0;
                $request['blocklist'] = 1;
                $request['blocklisted_date'] = date("Y-m-d");
            }

            $data->fill($request->all());
            $data->save();

            $data->touch();

            DB::connection()->commit();

            return response()->json([
                'message' => 'Record Successfully updated!',
                'status' => 'success',
                'data' => $data,
            ],201);

        } catch (Throwable $e) {
            DB::connection()->rollback();
            return response()->json([
                'status'  => false,
                'message' => 'Unable to process request. Please try again.',
                'data'    => $e->getMessage()
            ]);
        }
    }

    public function blocklist(Request $request, int $id)
    {
        $data = Applicant::where('id', $id)->first();

        if (!$data) {
            return response()->json(['messages' => 'No data found.'], 404);
        }

        $validator = Validator::make($request->all(),
            [
                // 'name' => [
                //     'required',
                //     'min:2',
                //     Rule::unique('applicants')->ignore($id)->whereNull('deleted_at')
                // ]
            ]
        );

        /** If validation fails return with error message */
        if ($validator->fails()) {
            $errors = $validator->errors();
            $first = $errors->getMessages();
            return response()->json([
                'status'  => false,
                'message' => (reset($first))[0],
                'errors'  => $errors
            ], Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        DB::connection()->beginTransaction();

        try {
            $request['blocklist'] = 1;
            $request['blocklisted_date'] = date("Y-m-d");

            // dd($request->all());

            $data->fill($request->all());
            $data->save();

            $data->touch();

            DB::connection()->commit();

            return response()->json([
                'message' => 'Record Successfully updated!',
                'status' => 'success',
                'data' => $data,
            ],201);

        } catch (Throwable $e) {
            DB::connection()->rollback();
            return response()->json([
                'status'  => false,
                'message' => 'Unable to process request. Please try again.',
                'data'    => $e->getMessage()
            ]);
        }
    }

    public function destroy(int $id)
    {
        dd($id);
        $data = Applicant::find($id);
        if(!$data)
        {
            return response()->json(['message' => "Record not found!"],204);
        }
        DB::connection()->beginTransaction();
        $data->delete();
        DB::connection()->commit();
        return response()->json(['message' => "Record successfully deleted!"],201);
    }

    public function newEmployee(string $employee_id){
        $user = Employee::where('employee_id', $employee_id);

        
    }
}
