<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreWardRequest;
use App\Http\Requests\UpdateWardRequest;
use App\Models\Ward;
use App\Models\District;
use Illuminate\Http\Request;

class WardController extends Controller
{
    public function index(Request $request)
    {
        $query = Ward::query()
            ->with([
                'district:id,name_bn,name_en',
                'city:id,district_id,name_bn,name_en',
                'upazila:id,district_id,name_bn,name_en',
            ]);

        if ($request->filled('search')) {
            $s = trim($request->string('search')->toString());
            $query->where(function ($q) use ($s) {
                $q->where('name_bn', 'like', "%{$s}%")
                  ->orWhere('name_en', 'like', "%{$s}%")
                  ->orWhere('ward_no', 'like', "%{$s}%")
                  ->orWhereHas('district', fn($dq) => $dq->where('name_bn', 'like', "%{$s}%")->orWhere('name_en', 'like', "%{$s}%"))
                  ->orWhereHas('city', fn($cq) => $cq->where('name_bn', 'like', "%{$s}%")->orWhere('name_en', 'like', "%{$s}%"))
                  ->orWhereHas('upazila', fn($uq) => $uq->where('name_bn', 'like', "%{$s}%")->orWhere('name_en', 'like', "%{$s}%"));
            });
        }

        if ($request->filled('district_id')) {
            $query->where('district_id', $request->integer('district_id'));
        }

        if ($request->filled('parent_type')) {
            // parent_type: city|upazila
            if ($request->parent_type === 'city') {
                $query->whereNotNull('city_id')->whereNull('upazila_id');
            } elseif ($request->parent_type === 'upazila') {
                $query->whereNotNull('upazila_id')->whereNull('city_id');
            }
        }

        $wards = $query->latest('id')->paginate(20)->withQueryString();

        $districts = District::query()
            ->with(['cities:id,district_id,name_bn', 'upazilas:id,district_id,name_bn'])
            ->select('id','name_bn')
            ->orderBy('name_bn')
            ->get();

        return view('wards.index', compact('wards', 'districts'));
    }

    public function create()
    {
        $districts = District::query()
            ->with(['cities:id,district_id,name_bn', 'upazilas:id,district_id,name_bn'])
            ->select('id','name_bn')
            ->orderBy('name_bn')
            ->get();

        return view('wards.create', compact('districts'));
    }

    public function store(StoreWardRequest $request)
    {
        $data = $request->validated();

        if (!empty($data['city_id'])) {
            $data['upazila_id'] = null;
        }
        if (!empty($data['upazila_id'])) {
            $data['city_id'] = null;
        }

        Ward::create($data);

        return redirect()->route('wards.index')
            ->with('success', 'ওয়ার্ড সফলভাবে যোগ করা হয়েছে।');
    }

    public function edit(Ward $ward)
    {
        $districts = District::query()
            ->with(['cities:id,district_id,name_bn', 'upazilas:id,district_id,name_bn'])
            ->select('id','name_bn')
            ->orderBy('name_bn')
            ->get();

        return view('ward.edit', compact('ward', 'districts'));
    }

    public function update(UpdateWardRequest $request, Ward $ward)
    {
        $data = $request->validated();

        if (!empty($data['city_id'])) {
            $data['upazila_id'] = null;
        }
        if (!empty($data['upazila_id'])) {
            $data['city_id'] = null;
        }

        $ward->update($data);

        return redirect()->route('wards.index')
            ->with('success', 'ওয়ার্ড সফলভাবে আপডেট করা হয়েছে।');
    }

    public function destroy(Ward $ward)
    {
        $ward->delete();

        return redirect()->route('wards.index')
            ->with('success', 'ওয়ার্ড সফলভাবে মুছে ফেলা হয়েছে।');
    }
}
