<?php

/*
|--------------------------------------------------------------------------
| OwnStore - Build your own online store
| Author: TakfeDev (takfedev@gmail.com)
| All Rights Reserved
|--------------------------------------------------------------------------
*/

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Country;
use App\Models\State;
use App\Models\City;
use Illuminate\Http\Request;
use Inertia\Inertia;

class LocationController extends Controller
{
    public function index(Request $request)
    {
        $tab = $request->query('tab', 'countries');
        $search = $request->query('search', '');

        $countries = [];
        $states = [];
        $cities = [];

        if ($tab === 'countries') {
            $countries = Country::query()
                ->when($search, fn($q) => $q->where('name', 'like', "%$search%")->orWhere('iso2', 'like', "%$search%"))
                ->orderBy('name')
                ->paginate(15)
                ->withQueryString();
        } elseif ($tab === 'states') {
            $states = State::with('country:id,name')
                ->when($search, fn($q) => $q->where('name', 'like', "%$search%")->orWhereHas('country', fn($c) => $c->where('name', 'like', "%$search%")))
                ->orderBy('name')
                ->paginate(15)
                ->withQueryString();
        } elseif ($tab === 'cities') {
            // UPDATED: Advanced search for cities
            $cities = City::with('state.country')
                ->when($search, fn($q) => 
                    $q->where('name', 'like', "%$search%")
                    ->orWhereHas('state', fn($s) => 
                        $s->where('name', 'like', "%$search%")
                        ->orWhereHas('country', fn($c) => $c->where('name', 'like', "%$search%"))
                    )
                )
                ->orderBy('name')
                ->paginate(15)
                ->withQueryString();
        }

        return Inertia::render('cp/Settings/Locations/Index', [
            'tab' => $tab,
            'search' => $search,
            'countriesData' => $countries,
            'statesData' => $states,
            'citiesData' => $cities,
            'allCountries' => Country::where('is_active', true)->orderBy('name')->get(['id', 'name']),
        ]);
    }

    // --- COUNTRY CRUD ---
    public function storeCountry(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'iso2' => 'required|string|size:2|unique:countries,iso2',
            'iso3' => 'nullable|string|size:3',
            'phone_code' => 'nullable|string|max:20',
            'currency' => 'nullable|string|max:3',
            'is_active' => 'boolean',
        ]);
        Country::create($validated);
        return back()->with('success', 'Country added successfully.');
    }

    public function updateCountry(Request $request, Country $country)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'iso2' => 'required|string|size:2|unique:countries,iso2,' . $country->id,
            'iso3' => 'nullable|string|size:3',
            'phone_code' => 'nullable|string|max:20',
            'currency' => 'nullable|string|max:3',
            'is_active' => 'boolean',
        ]);
        $country->update($validated);
        return back()->with('success', 'Country updated successfully.');
    }

    public function destroyCountry(Country $country)
    {
        $country->delete();
        return back()->with('success', 'Country deleted successfully.');
    }

    // --- STATE CRUD ---
    public function storeState(Request $request)
    {
        $validated = $request->validate([
            'country_id' => 'required|exists:countries,id',
            'name' => 'required|string|max:255',
            'is_active' => 'boolean',
        ]);
        State::create($validated);
        return back()->with('success', 'State added successfully.');
    }

    public function updateState(Request $request, State $state)
    {
        $validated = $request->validate([
            'country_id' => 'required|exists:countries,id',
            'name' => 'required|string|max:255',
            'is_active' => 'boolean',
        ]);
        $state->update($validated);
        return back()->with('success', 'State updated successfully.');
    }

    public function destroyState(State $state)
    {
        $state->delete();
        return back()->with('success', 'State deleted successfully.');
    }

    // --- CITY CRUD ---
    public function storeCity(Request $request)
    {
        $validated = $request->validate([
            'state_id' => 'required|exists:states,id',
            'name' => 'required|string|max:255',
            'latitude' => 'nullable|numeric',
            'longitude' => 'nullable|numeric',
            'is_active' => 'boolean',
        ]);
        City::create($validated);
        return back()->with('success', 'City added successfully.');
    }

    public function updateCity(Request $request, City $city)
    {
        $validated = $request->validate([
            'state_id' => 'required|exists:states,id',
            'name' => 'required|string|max:255',
            'latitude' => 'nullable|numeric',
            'longitude' => 'nullable|numeric',
            'is_active' => 'boolean',
        ]);
        $city->update($validated);
        return back()->with('success', 'City updated successfully.');
    }

    public function destroyCity(City $city)
    {
        $city->delete();
        return back()->with('success', 'City deleted successfully.');
    }
}