<?php

namespace App\Http\Controllers\Component1;

use App\Http\Controllers\Controller;
use App\Models\C1Group;
use App\Models\C1Member;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;

class C1MemberController extends Controller
{
    public function index(Request $request): View
    {
        $query = C1Member::with('group')->active();

        // Filter by group if provided
        if ($request->filled('group_id')) {
            $query->where('group_id', $request->group_id);
        }

        // Search by name
        if ($request->filled('search')) {
            $query->where('name', 'like', '%' . $request->search . '%');
        }

        $members = $query->orderBy('name')->paginate(15);
        $groups = C1Group::orderBy('name')->pluck('name', 'id');

        return view('component1.members.index', compact('members', 'groups'));
    }

    public function create(Request $request): View
    {
        $groups = C1Group::orderBy('name')->pluck('name', 'id');
        $selectedGroup = $request->query('group_id');

        return view('component1.members.create', compact('groups', 'selectedGroup'));
    }

    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'group_id'             => 'required|exists:c1_groups,id',
            'serial_no'            => 'required|integer|min:1',
            'name'                 => 'required|string|max:191',
            'gender'               => 'required|in:female,male',
            'age'                  => 'required|integer|min:10|max:100',
            'exec_committee'       => 'sometimes|boolean',
            'disability_status'    => 'sometimes|boolean',
            'marital_status'       => 'nullable|in:married,not_married,divorced,widowed',
            'head_household'       => 'sometimes|boolean',
            'num_hh_members_total' => 'nullable|integer|min:0',
            'num_hh_female_adult'  => 'nullable|integer|min:0',
            'num_hh_female_adol'   => 'nullable|integer|min:0',
            'num_hh_male_adult'    => 'nullable|integer|min:0',
            'num_hh_male_adol'     => 'nullable|integer|min:0',
            'completed_core_1'     => 'sometimes|boolean',
            'completed_core_2'     => 'sometimes|boolean',
            'completed_core_3'     => 'sometimes|boolean',
            'completed_core_4'     => 'sometimes|boolean',
            'received_specialized_1'=> 'sometimes|boolean',
            'specialized_1_details'=> 'nullable|string',
            'received_in_kind'     => 'sometimes|boolean',
            'in_kind_source'       => 'nullable|in:sswseep,others',
            'received_productive_equip' => 'sometimes|boolean',
            'equip_source'         => 'nullable|in:sswseep,others',
            'started_new_business' => 'sometimes|boolean',
            'actively_saving_monthly'=> 'sometimes|boolean',
            'total_savings'        => 'nullable|numeric|min:0',
            'outstanding_loan'     => 'nullable|numeric|min:0',
            'month'                => 'required|date_format:Y-m',
            'category'                 => 'nullable|in:mature,progressive,new',
            'existing_income_activities' => 'nullable|string|max:1000',
            'received_certificate'     => 'required|in:0,1',
        ]);

        // Ensure serial_no is unique per group
        $request->validate([
            'serial_no' => [
                'required',
                'integer',
                function ($attribute, $value, $fail) use ($request) {
                    $exists = C1Member::where('group_id', $request->group_id)
                                      ->where('serial_no', $value)
                                      ->exists();
                    if ($exists) {
                        $fail('Serial number already exists in this group.');
                    }
                },
            ],
        ]);

        C1Member::create($validated);

        return redirect()
            ->route('component1.members.index', ['group_id' => $request->group_id])
            ->with('success', 'Member added successfully.');
    }

    public function show(C1Member $member): View
    {
        $member->load('group');
        return view('component1.members.show', compact('member'));
    }

    public function edit(C1Member $member): View
    {
        $groups = C1Group::orderBy('name')->pluck('name', 'id');
        return view('component1.members.edit', compact('member', 'groups'));
    }

    public function update(Request $request, C1Member $member): RedirectResponse
    {
        $validated = $request->validate([
            'group_id'             => 'required|exists:c1_groups,id',
            'serial_no'            => 'required|integer|min:1',
            'name'                 => 'required|string|max:191',
            'gender'               => 'required|in:female,male',
            'age'                  => 'required|integer|min:10|max:100',
            'exec_committee'       => 'sometimes|boolean',
            'disability_status'    => 'sometimes|boolean',
            'marital_status'       => 'nullable|in:married,not_married,divorced,widowed',
            'head_household'       => 'sometimes|boolean',
            'num_hh_members_total' => 'nullable|integer|min:0',
            'num_hh_female_adult'  => 'nullable|integer|min:0',
            'num_hh_female_adol'   => 'nullable|integer|min:0',
            'num_hh_male_adult'    => 'nullable|integer|min:0',
            'num_hh_male_adol'     => 'nullable|integer|min:0',
            'completed_core_1'     => 'sometimes|boolean',
            'completed_core_2'     => 'sometimes|boolean',
            'completed_core_3'     => 'sometimes|boolean',
            'completed_core_4'     => 'sometimes|boolean',
            'received_specialized_1'=> 'sometimes|boolean',
            'specialized_1_details'=> 'nullable|string',
            'received_in_kind'     => 'sometimes|boolean',
            'in_kind_source'       => 'nullable|in:sswseep,others',
            'received_productive_equip' => 'sometimes|boolean',
            'equip_source'         => 'nullable|in:sswseep,others',
            'started_new_business' => 'sometimes|boolean',
            'actively_saving_monthly'=> 'sometimes|boolean',
            'total_savings'        => 'nullable|numeric|min:0',
            'outstanding_loan'     => 'nullable|numeric|min:0',
            'month'                => 'required|date_format:Y-m',
            'category'                 => 'nullable|in:mature,progressive,new',
            'existing_income_activities' => 'nullable|string|max:1000',
            'received_certificate'     => 'required|in:0,1',
        ]);

        // Unique serial_no per group (except current record)
        $request->validate([
            'serial_no' => [
                'required',
                'integer',
                function ($attribute, $value, $fail) use ($request, $member) {
                    $exists = C1Member::where('group_id', $request->group_id)
                                      ->where('serial_no', $value)
                                      ->where('id', '!=', $member->id)
                                      ->exists();
                    if ($exists) {
                        $fail('Serial number already exists in this group.');
                    }
                },
            ],
        ]);

        $member->update($validated);

        return redirect()
            ->route('component1.members.index', ['group_id' => $member->group_id])
            ->with('success', 'Member updated successfully.');
    }

    public function destroy(C1Member $member): RedirectResponse
    {
        $groupId = $member->group_id;
        $member->delete();

        return redirect()
            ->route('component1.members.index', ['group_id' => $groupId])
            ->with('success', 'Member deleted.');
    }
}