<?php

namespace App\Http\Controllers;

use App\Exports\VotingTablesExport;
use App\Models\VotingTable;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class VotingTableController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $tables = VotingTable::with(['votingLocation.district.province.department'])
            ->atLocation($request->input('voting_location_id'))
            ->when(!$request->filled('voting_location_id'), function ($q) use ($request) {
                $q->inDistrict($request->input('district_id'))
                  ->when(!$request->filled('district_id'), function ($q2) use ($request) {
                      $q2->inProvince($request->input('province_id'))
                        ->when(!$request->filled('province_id'), function ($q3) use ($request) {
                            $q3->inDepartment($request->input('department_id'));
                        });
                  });
            })
            ->search($request->input('search'))
            ->orderBy('voting_location_id')
            ->orderBy('table_number')
            ->paginate($request->integer('per_page', 15));

        return response()->json($tables);
    }

    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'voting_location_id' => 'required|exists:voting_locations,id',
            'table_number' => 'required|integer|min:1',
            'voter_count' => 'nullable|integer|min:0',
        ]);

        $exists = VotingTable::where('voting_location_id', $data['voting_location_id'])
            ->where('table_number', $data['table_number'])
            ->exists();

        if ($exists) {
            return response()->json([
                'message' => 'Ya existe una mesa con ese número en este local.',
                'errors' => ['table_number' => ['El número de mesa ya existe en este local.']],
            ], 422);
        }

        $table = VotingTable::create($data);
        $table->load('votingLocation.district.province.department');

        return response()->json($table, 201);
    }

    public function show(VotingTable $votingTable): JsonResponse
    {
        $votingTable->load('votingLocation.district.province.department');

        return response()->json($votingTable);
    }

    public function update(Request $request, VotingTable $votingTable): JsonResponse
    {
        $data = $request->validate([
            'voting_location_id' => 'required|exists:voting_locations,id',
            'table_number' => 'required|integer|min:1',
            'voter_count' => 'nullable|integer|min:0',
        ]);

        $exists = VotingTable::where('voting_location_id', $data['voting_location_id'])
            ->where('table_number', $data['table_number'])
            ->where('id', '!=', $votingTable->id)
            ->exists();

        if ($exists) {
            return response()->json([
                'message' => 'Ya existe una mesa con ese número en este local.',
                'errors' => ['table_number' => ['El número de mesa ya existe en este local.']],
            ], 422);
        }

        $votingTable->update($data);
        $votingTable->load('votingLocation.district.province.department');

        return response()->json($votingTable);
    }

    public function destroy(VotingTable $votingTable): JsonResponse
    {
        $votingTable->delete();

        return response()->json(null, 204);
    }

    public function export()
    {
        return Excel::download(new VotingTablesExport, 'mesas_votacion.xlsx');
    }
}
