<?php

namespace App\Http\Controllers;

use App\Models\Ward;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class WardController extends Controller
{
    public function index()
    {
        $ward = DB::table('wards')
            ->leftJoin('voters_data', 'wards.ward_number', '=', 'voters_data.ward_no')
            ->select(
                'wards.id',
                'wards.ward_number',
                DB::raw('COUNT(voters_data.id) AS voters_count'),
                DB::raw('SUM(CASE WHEN voters_data.gender = "male" THEN 1 ELSE 0 END) AS males_count'),
                DB::raw('SUM(CASE WHEN voters_data.gender = "female" THEN 1 ELSE 0 END) AS females_count')
            )
            ->groupBy('wards.id', 'wards.ward_number')
            ->get();
          
        return view('admin.ward.index', compact('ward'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'ward_number' => 'required|string|max:255',
        ]);

        Ward::create([
            'ward_number' => $request->ward_number,
        ]);

        return redirect()->route('admin.ward.index')->with('success', 'Ward added successfully!');
    }

    public function destroy(Ward $Ward)
    {
        $Ward->delete();
        return redirect()->route('admin.ward.index')->with('success', 'Ward deleted successfully!');
    }
}
