<?php

namespace App\Http\Controllers;

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

class BlockCodeController extends Controller
{
   public function index()
    {
        $block_code = DB::table('block_codes')
            ->leftJoin('voters_data', 'block_codes.block_code', '=', 'voters_data.block_code')
            ->select(
                'block_codes.id',
                'block_codes.block_code',
                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('block_codes.id', 'block_codes.block_code')
            ->get();
    
        return view('admin.block_code.index', compact('block_code'));
    }
    public function store(Request $request)
    {
        $request->validate([
            'block_code' => 'required|string|max:255',
        ]);

        BlockCode::create([
            'block_code' => $request->block_code,
        ]);

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

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