<?php

namespace App\Http\Controllers\Component1;

use App\Http\Controllers\Controller;
use App\Models\C1Group;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
use App\Imports\GroupsImport;
use Maatwebsite\Excel\Facades\Excel;

class C1GroupController extends Controller
{
    /**
     * Display a listing of the groups.
     */
    public function index(): View
    {
        $groups = C1Group::withCount('members')
                         ->orderBy('name')
                         ->paginate(15);

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

    /**
     * Show the form for creating a new group.
     */
    public function create(): View
    {
        return view('component1.groups.create');
    }

    /**
     * Store a newly created group.
     */
    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'name'                  => 'required|string|max:191',
            'nature'                => 'required|in:new,progressing,matured',
            'state'                 => 'required|string|max:100',
            'county'                => 'required|string|max:100',
            'payam'                 => 'required|string|max:100',
            'establishing_org_name' => 'nullable|string|max:191',
            'establishment_type'    => 'required|in:self,cso,ngo,government',
            'date_formation'        => 'required|date',
            'vsla_registration_date'=> 'nullable|date|after_or_equal:date_formation',
            'leadership'            => 'required|in:adolescent_girl,woman',
            'month'                 => 'required|date_format:Y-m',
            'average_participation' => 'nullable|numeric|min:0|max:100',
            'received_certificate'   => 'required|in:0,1',
        ]);

        C1Group::create($validated);

        return redirect()
            ->route('component1.groups.index')
            ->with('success', 'VSLA/Community Group created successfully.');
    }

    /**
     * Display the specified group.
     */
    public function show(C1Group $group): View
    {
        $group->load(['members' => fn($q) => $q->active()->limit(10)]);
        return view('component1.groups.show', compact('group'));
    }

    /**
     * Show the form for editing the group.
     */
    public function edit(C1Group $group): View
    {
        return view('component1.groups.edit', compact('group'));
    }

    /**
     * Update the specified group.
     */
    public function update(Request $request, C1Group $group): RedirectResponse
    {
        $validated = $request->validate([
            'name'                  => 'required|string|max:191',
            'nature'                => 'required|in:new,progressing,matured',
            'state'                 => 'required|string|max:100',
            'county'                => 'required|string|max:100',
            'payam'                 => 'required|string|max:100',
            'establishing_org_name' => 'nullable|string|max:191',
            'establishment_type'    => 'required|in:self,cso,ngo,government',
            'date_formation'        => 'required|date',
            'vsla_registration_date'=> 'nullable|date|after_or_equal:date_formation',
            'leadership'            => 'required|in:adolescent_girl,woman',
            'month'                 => 'required|date_format:Y-m',
            'average_participation' => 'nullable|numeric|min:0|max:100',
            'received_certificate'   => 'required|in:0,1',
        ]);

        $group->update($validated);

        return redirect()
            ->route('component1.groups.index')
            ->with('success', 'Group updated successfully.');
    }

    /**
     * Remove the specified group (soft delete).
     */
    public function destroy(C1Group $group): RedirectResponse
    {
        if (auth()->user()->role !== 'component_1_supervisor') {
            abort(403, 'Unauthorized action.');
        }

        $group->delete();

        return redirect()
            ->route('component1.groups.index')
            ->with('success', 'Group deleted successfully.');
    }

    public function importForm()
    {
        return view('component1.groups.import');
    }

    public function import(Request $request)
    {
        $request->validate([
            'excel_file' => 'required|file|mimes:xlsx,xls,csv|max:10240',
        ]);

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

    public function downloadTemplate()
    {
        $headers = [
            'Group ID',
            'VSLA Group Name',
            'GPS Coordinates',
            'Category',
            'State',
            'County',
            'Payam',
            'Boma',
            'Average Training',
            'Total Female',
            'Total Male',
            'Adolesent Girls',
            'Total Members',
            'Overall Membership',
            'VSLA Operations, Management, and Leadership',
            'Functional Literacy and Financial Literacy & Management',
            'Business Development and Entrepreneurship',
            'Digital and information literacy',
            'Specialized Training',
            'Average Participation',
            'Received Certificate'
        ];
        
        $callback = function() use ($headers) {
            $file = fopen('php://output', 'w');
            fputcsv($file, $headers);
            
            // Add sample row
            fputcsv($file, [
                'EESN001', 'Sample Group', '', 'New', 'EES', 'Torit', 
                'Ifwotu', 'Gumbo', '11', '25', '5', '8', '38', 
                '38', 'Ongoing', 'Not Started', 'Not Started', 'Not Started', 
                '', '', ''
            ]);
            
            fclose($file);
        };
        
        return response()->stream($callback, 200, [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename="vsla_groups_import_template.csv"',
        ]);
    }
}