<?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;
use App\Imports\MembersImport;
use Maatwebsite\Excel\Facades\Excel;

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
    {
        if (auth()->user()->role !== 'component_1_supervisor') {
            abort(403, 'Unauthorized action.');
        }

        $groupId = $member->group_id;
        $member->delete();

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

    public function importForm(Request $request)
    {
        $groups = C1Group::orderBy('name')->pluck('name', 'id');
        $selectedGroup = $request->query('group_id');
        
        return view('component1.members.import', compact('groups', 'selectedGroup'));
    }

    public function import(Request $request)
    {
        $request->validate([
            'excel_file' => 'required|file|mimes:xlsx,xls,csv|max:10240',
            'group_id' => 'nullable|exists:c1_groups,id',
            'month' => 'nullable|date_format:Y-m',
        ]);

        try {
            $month = $request->month;
            $import = new MembersImport($month);
            Excel::import($import, $request->file('excel_file'));
            
            $message = "Import completed! ";
            $message .= "New members: " . $import->getImportedCount() . ". ";
            $message .= "Updated members: " . $import->getUpdatedCount() . ". ";
            $message .= "Skipped: " . $import->getSkippedCount() . ". ";
            
            if (count($import->getErrors()) > 0) {
                $message .= " Warnings: " . implode('; ', array_slice($import->getErrors(), 0, 3));
            }
            
            $redirectRoute = $request->group_id 
                ? route('component1.members.index', ['group_id' => $request->group_id])
                : route('component1.members.index');
            
            return redirect($redirectRoute)
                ->with('success', $message);
                
        } catch (\Exception $e) {
            return redirect()->back()
                ->with('error', 'Import failed: ' . $e->getMessage());
        }
    }

    public function downloadTemplate()
    {
        $headers = [
            'Individual ID',
            'Name of VSLA Member',
            'Category',
            'Group Name',
            'State',
            'County',
            'Payam',
            'Boma',
            'Age',
            'Gender',
            'Benefited from training',
            'VSLA Operations, Management, and Leadership',
            'Functional Literacy and Financial Literacy & Management',
            'Business Development and Entrepreneurship',
            'Digital and information literacy',
            'Specialized Training',
            'Existing Main Income Generation Activities',
            'Received Certificate',
            'Starter Kits received',
            'New Business Created and Operational as a result of SSWSEEP',
            'Type of New Business Created'
        ];
        
        $callback = function() use ($headers) {
            $file = fopen('php://output', 'w');
            fputcsv($file, $headers);
            
            // Add sample row
            fputcsv($file, [
                '1', 'Sample Member', 'New', 'Sample Group', 'EES', 'Torit', 
                'Ifwotu', 'Gumbo', '30', 'Female', 'Yes', 'Completed', 
                'Completed', 'Not Started', 'Not Started', '', 'Farming', 
                'Yes', '', '', ''
            ]);
            
            fclose($file);
        };
        
        return response()->stream($callback, 200, [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename="vsla_members_import_template.csv"',
        ]);
    }
}