<?php

namespace App\Http\Controllers\Component4;

use App\Http\Controllers\Controller;
use App\Models\Component4\C4Participant;
use App\Models\Component4\C4Indicator;
use Illuminate\Http\Request;
use App\Exports\C4ParticipantsExport;
use Maatwebsite\Excel\Facades\Excel;
use PDF; // We'll add this later for reports

class C4ParticipantController extends Controller
{
    // 1. Dashboard + Index
    public function index()
    {
        $query = C4Participant::query();

        if (request('state')) {
            $query->where('state_province', request('state'));
        }
        if (request('gender')) {
            $query->where('gender', request('gender'));
        }
        if (request('module')) {
            $field = match(request('module')) {
                'gbv' => 'trained_gbv_programming',
                'gender_eq' => 'trained_gender_equality',
                'project_mgt' => 'trained_project_management',
                default => null
            };
            if ($field) $query->where($field, true);
        }

        $participants = $query->latest()->paginate(15)->withQueryString();

        // Stats recalculated based on filtered data
        $stats = [
            'total_participants' => $query->count(),
            'total_female'       => $query->clone()->where('gender', 'female')->count(),
            'total_male'         => $query->clone()->where('gender', 'male')->count(),
            'trained_male'       => $query->clone()->where('gender', 'male')->where('trained_gbv_programming', true)->count(),
            'trained_female'     => $query->clone()->where('gender', 'female')->where('trained_gbv_programming', true)->count(),
            'trained_gbv'        => $query->clone()->where('trained_gbv_programming', true)->count(),
            'trained_gender_eq'  => $query->clone()->where('trained_gender_equality', true)->count(),
            'completed_all'      => $query->clone()->where([
                ['trained_project_management', true],
                ['trained_grm', true],
                ['trained_monitoring_evaluation', true],
                ['trained_gbv_programming', true],
                ['trained_gender_equality', true],
                ['trained_resource_mobilization', true],
                ['trained_leadership_management', true],
            ])->count(),
        ];

        return view('component4.index', compact('participants', 'stats'));
    }

    // 2. Show registration form
    public function create()
    {
        return view('component4.create');
    }

    // 3. Store new participant
    public function store(Request $request)
    {
        $validated = $request->validate([
            'serial_no'          => 'nullable|integer',
            'name'               => 'required|string|max:191',
            'organization'       => 'nullable|string|max:191',
            'designation'        => 'nullable|string|max:191',
            'gender'             => 'required|in:female,male,other',
            'state_province'     => 'required|string|max:191',
            'start_date'         => 'nullable|date',
            'completion_date'    => 'nullable|date',
            'comment'            => 'nullable|string',

            // Training checkboxes
            'trained_project_management'     => 'sometimes|boolean',
            'trained_grm'                    => 'sometimes|boolean',
            'trained_monitoring_evaluation'  => 'sometimes|boolean',
            'trained_gbv_programming'        => 'sometimes|boolean',
            'trained_gender_equality'        => 'sometimes|boolean',
            'trained_resource_mobilization'  => 'sometimes|boolean',
            'trained_leadership_management' => 'sometimes|boolean',
        ]);

        // Laravel auto-converts checkboxes to boolean when using `sometimes|boolean`
        C4Participant::create($validated);

        return redirect()->route('component4.index')
            ->with('success', 'Participant registered successfully!');
    }

    // 4. Edit form
    public function edit(C4Participant $participant)
    {
        return view('component4.edit', compact('participant'));
    }

    // 5. Update participant
    public function update(Request $request, C4Participant $participant)
    {
        $validated = $request->validate([
            'serial_no'          => 'nullable|integer',
            'name'               => 'required|string|max:191',
            'organization'       => 'nullable|string|max:191',
            'designation'        => 'nullable|string|max:191',
            'gender'             => 'required|in:female,male,other',
            'state_province'     => 'required|string|max:191',
            'start_date'         => 'nullable|date',
            'completion_date'    => 'nullable|date',
            'comment'            => 'nullable|string',

            'trained_project_management'     => 'sometimes|boolean',
            'trained_grm'                    => 'sometimes|boolean',
            'trained_monitoring_evaluation'  => 'sometimes|boolean',
            'trained_gbv_programming'        => 'sometimes|boolean',
            'trained_gender_equality'        => 'sometimes|boolean',
            'trained_resource_mobilization'  => 'sometimes|boolean',
            'trained_leadership_management' => 'sometimes|boolean',
        ]);

        $participant->update($validated);

        return redirect()->route('component4.index')
            ->with('success', 'Participant updated successfully!');
    }

    // 6. Delete participant
    public function destroy(C4Participant $participant)
    {
        $participant->delete();

        return back()->with('success', 'Participant deleted successfully!');
    }
    public function export()
    {
        $filename = 'Component4_Training_Participants_' . now()->format('Y-m-d') . '.xlsx';
        return Excel::download(new C4ParticipantsExport, $filename);
    }
}