<?php

namespace App\Http\Controllers;

use App\Models\City;
use App\Models\Continent;
use App\Models\Country;
use App\Models\Tradefair;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class TradefairController extends Controller
{
    public function index(Request $request)
    {
        $query = Tradefair::with(['fairContinent', 'fairCountry']);

        if ($request->filled('f_continent_id')) {
            $continent = Continent::find($request->f_continent_id);
            if ($continent) {
                $query->where('contient', $continent->name);
            }
        }

        if ($request->filled('f_country_id')) {
            $country = Country::find($request->f_country_id);
            if ($country) {
                $query->where('country', $country->name)->where('contient', $country->continent);
            }
        }

        if ($request->filled('f_city_id')) {
            $city = City::find($request->f_city_id);
            if ($city) {
                $parentCountry = Country::find($city->country_id);
                if ($parentCountry) {
                    $query->where('eventvenue', $city->name)
                        ->where('country', $parentCountry->name)
                        ->where('contient', $parentCountry->continent);
                }
            }
        }

        $tradefairs = $query->orderBy('fair_name')->get();

        $continents = Continent::active()->orderBy('name')->get();

        $filterCountries = $request->filled('f_continent_id')
            ? Country::where('continent', optional(Continent::find($request->f_continent_id))->name)
                ->active()
                ->orderBy('name')
                ->get()
            : collect();

        $filterCities = $request->filled('f_country_id')
            ? City::where('country_id', $request->f_country_id)->active()->orderBy('name')->get()
            : collect();

        return view('tradefairs.index', compact(
            'tradefairs',
            'continents',
            'filterCountries',
            'filterCities'
        ));
    }

    public function create()
    {
        $continents = Continent::active()->orderBy('name')->get();

        return view('tradefairs.create', compact('continents'));
    }

    public function store(Request $request)
    {
        $validated = $this->validatedAttributes($request);
        $validated['status'] = $validated['status'] ?? '1';

        $validated['created_by'] = auth()->id();
        $validated['updated_by'] = auth()->id();

        $tradefair = Tradefair::create($validated);

        if ($request->expectsJson()) {
            return response()->json([
                'id' => $tradefair->id,
                'fair_name' => $tradefair->fair_name,
                'country' => $tradefair->country,
                'eventvenue' => $tradefair->eventvenue,
            ]);
        }

        return redirect()->route('tradefairs.index')->with('success', 'Trade fair created.');
    }

    public function edit(Tradefair $tradefair)
    {
        $continents = Continent::active()->orderBy('name')->get();

        $continentName = $tradefair->contient;
        $countries = Country::where('continent', $continentName)->active()->orderBy('name')->get();

        $countryRow = Country::where('name', $tradefair->country)
            ->where('continent', $continentName)
            ->first();

        $cities = $countryRow
            ? City::where('country_id', $countryRow->id)->active()->orderBy('name')->get()
            : collect();

        $selectedContinentId = optional(Continent::where('name', $continentName)->first())->id;
        $selectedCountryId = optional($countryRow)->id;
        $selectedCityId = null;
        if ($countryRow) {
            $cityMatch = City::where('country_id', $countryRow->id)->where('name', $tradefair->eventvenue)->first();
            $selectedCityId = $cityMatch ? $cityMatch->id : null;
        }

        return view('tradefairs.edit', compact(
            'tradefair',
            'continents',
            'countries',
            'cities',
            'selectedContinentId',
            'selectedCountryId',
            'selectedCityId'
        ));
    }

    public function update(Request $request, Tradefair $tradefair)
    {
        $validated = $this->validatedAttributes($request);
        $validated['updated_by'] = auth()->id();

        $tradefair->update($validated);

        return redirect()->route('tradefairs.index')->with('success', 'Trade fair updated.');
    }

    public function destroy(Tradefair $tradefair)
    {
        $tradefair->deleted_by = auth()->id();
        $tradefair->save();
        $tradefair->delete();

        return redirect()->route('tradefairs.index')->with('success', 'Trade fair deleted.');
    }

    private function validatedAttributes(Request $request): array
    {
        $validated = $request->validate([
            'fair_name' => 'required|string|max:120',
            'fair_logo' => 'nullable|string',
            'continent_id' => 'required|exists:continents,id',
            'country_id' => [
                'required',
                Rule::exists('countries', 'id')->where(function ($query) use ($request) {
                    $continent = Continent::find($request->continent_id);
                    if ($continent) {
                        $query->where('continent', $continent->name);
                    }
                }),
            ],
            'city_id' => [
                'required',
                Rule::exists('cities', 'id')->where(function ($query) use ($request) {
                    $query->where('country_id', $request->country_id);
                }),
            ],
            'event_start_date' => 'nullable|date',
            'event_end_date' => 'nullable|date|after_or_equal:event_start_date',
            'status' => 'nullable|in:0,1',
        ]);

        $continent = Continent::findOrFail($validated['continent_id']);
        $country = Country::findOrFail($validated['country_id']);
        $city = City::findOrFail($validated['city_id']);

        return [
            'fair_name' => $validated['fair_name'],
            'fair_logo' => $validated['fair_logo'] ?? null,
            'contient' => $continent->name,
            'country' => $country->name,
            'eventvenue' => $city->name,
            'event_start_date' => $validated['event_start_date'] ?? null,
            'event_end_date' => $validated['event_end_date'] ?? null,
            'status' => $validated['status'] ?? '1',
        ];
    }
}
