<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreVoterAreaRequest;
use App\Http\Requests\UpdateVoterAreaRequest;
use App\Models\VoterArea;
use App\Models\Seat;
use App\Models\District;
use Illuminate\Http\Request;

class VoterAreaController extends Controller
{
    public function index(Request $request)
    {
        $query = VoterArea::query()
            ->with([
                'seat:id,name_bn,name_en',
                'district:id,name_bn',
                'upazila:id,name_bn',
                'city:id,name_bn',
                'ward:id,ward_no,name_bn',
            ]);

        if ($request->filled('search')) {
            $s = trim($request->string('search')->toString());
            $query->where(function ($q) use ($s) {
                $q->where('area_name_bn', 'like', "%{$s}%")
                  ->orWhere('area_name_en', 'like', "%{$s}%")
                  ->orWhere('area_code', 'like', "%{$s}%")
                  ->orWhere('postal_code', 'like', "%{$s}%")
                  ->orWhereHas('seat', fn($sq) => $sq->where('name', 'like', "%{$s}%")->orWhere('constituency', 'like', "%{$s}%"));
            });
        }

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

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

        if ($request->filled('status')) {
            $query->where('status', $request->string('status')->toString());
        }

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

        $seats = Seat::select('id','name_bn','name_en')->orderBy('name_bn')->get();
        $districts = District::select('id','name_bn')->orderBy('name_bn')->get();

        return view('voter_area.index', compact('voterAreas', 'seats', 'districts'));
    }

    public function create()
    {
        $seats = Seat::select('id','name_bn','name_en','district_id','upazila_id','city_id')
    ->orderBy('name_bn')
    ->get();


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

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

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

        // If total not given -> auto sum
        $male = (int)($data['male_voters'] ?? 0);
        $female = (int)($data['female_voters'] ?? 0);
        $other = (int)($data['other_voters'] ?? 0);

        if (!isset($data['total_voters']) || $data['total_voters'] === null || $data['total_voters'] === '') {
            $data['total_voters'] = $male + $female + $other;
        }

        VoterArea::create($data);

        return redirect()->route('voter-areas.index')
            ->with('success', 'ভোটার এলাকা সফলভাবে যোগ করা হয়েছে।');
    }

    public function edit(VoterArea $voter_area)
    {
        $seats = Seat::select('id','name_bn','name_en')->orderBy('name_bn')->get();

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

        return view('voter_area.edit', [
            'voterArea' => $voter_area,
            'seats' => $seats,
            'districts' => $districts,
        ]);
    }

    public function update(UpdateVoterAreaRequest $request, VoterArea $voter_area)
    {
        $data = $request->validated();

        $male = (int)($data['male_voters'] ?? 0);
        $female = (int)($data['female_voters'] ?? 0);
        $other = (int)($data['other_voters'] ?? 0);

        if (!isset($data['total_voters']) || $data['total_voters'] === null || $data['total_voters'] === '') {
            $data['total_voters'] = $male + $female + $other;
        }

        $voter_area->update($data);

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

    public function destroy(VoterArea $voter_area)
    {
        $voter_area->delete();

        return redirect()->route('voter-areas.index')
            ->with('success', 'ভোটার এলাকা সফলভাবে মুছে ফেলা হয়েছে।');
    }
}
