<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Region;
use App\Models\Prefecture;
use App\Models\City;
use App\Models\TourGuide;
use App\Models\OtherLanguage;
use Illuminate\Support\Facades\Mail;
use App\Mail\TourGuideApplicationMail;

class TourGuideApplicationController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $regions = Region::all();
        $other_languages = OtherLanguage::orderBy('name', 'asc')->get();
        return view('tour_guide_application', compact('regions', 'other_languages'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        // dd($request->all());
        // Validate form data
        $request->validate([
            'region_id' => 'required|exists:regions,id',
            'prefecture_id' => 'required|exists:prefectures,id',
            'city_id' => 'required|exists:cities,id',
            'station' => 'required|string|max:255',
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'japanese_name' => 'required|string|max:255',
            'email' => 'required|email|unique:tour_guides,email',
            'phone' => 'required|string|max:20',
            'dob' => 'required|date',
            'gender' => 'required|string',
            'interpreter_license' => 'required|string',
            'license_number' => 'nullable|string|max:50',
            'certifications' => 'nullable|string',
            'english_fluency' => 'required|integer|min:1|max:5',
            'other_languages' => 'nullable|array',
            'job_experience' => 'required|string',
            'years_of_experience' => 'required|string',
            'number_of_tours' => 'required|string',
            'guide_areas' => 'required|array',
            'guide_areas.*.region' => 'required|exists:regions,id',
            'guide_areas.*.prefecture' => 'required|exists:prefectures,id',
            'guide_areas.*.cities' => 'required|array|min:1',
            'guide_areas.*.cities.*' => 'exists:cities,id',
            'type_of_tours' => 'nullable|array',
            'type_of_tours_other' => 'nullable|string',
            'how_heard' => 'required|string',
            'referred_person' => 'nullable|string',
            'how_heard_other' => 'nullable|string',
            'availability' => 'required|string',
        ]);

        $lastGuide = TourGuide::latest()->first();
        if ($lastGuide && preg_match('/@group_N(\d+)/', $lastGuide->line_group_id, $matches)) {
            $nextNumber = (int)$matches[1] + 1;
        } else {
            $nextNumber = 1; // Pehla group
        }

        // Naya group ID generate karna
        $newGroupId = "@group_N" . $nextNumber;

        // Store data in database
        TourGuide::create([
            'region_id' => $request->region_id,
            'prefecture_id' => $request->prefecture_id,
            'city_id' => $request->city_id,
            'station' => $request->station,
            'first_name' => $request->first_name,
            'last_name' => $request->last_name,
            'japanese_name' => $request->japanese_name,
            'email' => $request->email,
            'phone' => $request->phone,
            'dob' => $request->dob,
            'gender' => $request->gender,
            'interpreter_license' => $request->interpreter_license,
            'license_number' => $request->license_number,
            'certifications' => $request->certifications,
            'english_fluency' => $request->english_fluency,
            'other_languages' => json_encode($request->other_languages),
            'job_experience' => $request->job_experience,
            'years_of_experience' => $request->years_of_experience,
            'number_of_tours' => $request->number_of_tours,
            'guide_areas' => !empty($request->guide_areas) ? json_encode($request->guide_areas, JSON_UNESCAPED_UNICODE) : json_encode([]),
            'type_of_tours' => json_encode($request->type_of_tours),
            'type_of_tours_other' => $request->type_of_tours_other,
            'how_heard' => $request->how_heard,
            'referred_person' => $request->referred_person,
            'how_heard_other' => $request->how_heard_other,
            'availability' => $request->availability,
            'line_group_id' => $newGroupId,
        ]);

        $guideAreas = $request->guide_areas;
        $formattedGuideAreas = [];

        foreach ($guideAreas as $area) {
            $regionName = Region::find($area['region'])->eng_name ?? 'Unknown Region';
            $prefectureName = Prefecture::find($area['prefecture'])->eng_name ?? 'Unknown Prefecture';
            $cityNames = City::whereIn('id', $area['cities'])->pluck('eng_name')->toArray();

            $formattedGuideAreas[] = "{$regionName} - {$prefectureName} (" . implode(', ', $cityNames) . ")";
        }

        $data = [
            'first_name' => $request->first_name,
            'last_name' => $request->last_name,
            'japanese_name' => $request->japanese_name,
            'email' => $request->email,
            'phone' => $request->phone,
            'dob' => $request->dob,
            'gender' => $request->gender,
            'region' => Region::find($request->region_id)->eng_name,
            'prefecture' => Prefecture::find($request->prefecture_id)->eng_name,
            'city' => City::find($request->city_id)->eng_name,
            'station' => $request->station,
            'interpreter_license' => $request->interpreter_license,
            'license_number' => $request->license_number,
            'how_heard' => $request->how_heard,
            'availability' => $request->availability,
            'certifications' => $request->certifications,
            'english_fluency' => $request->english_fluency,
            'job_experience' => $request->job_experience,
            'languages' => OtherLanguage::whereIn('id', $request->other_languages)->pluck('name')->implode(', '),
            'years_of_experience' => $request->years_of_experience,
            'number_of_tours' => $request->number_of_tours,
            'guide_areas' => implode('; ', $formattedGuideAreas),
            'type_of_tours' => $request->type_of_tours,
        ];

        // Send Email
        Mail::to($data['email'])->send(new TourGuideApplicationMail($data));

        return redirect()->back()->with('success', 'Your application has been submitted successfully!');
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}
