<?php

namespace App\Http\Controllers;

use App\Models\NdrtOfficer;
use App\Models\Branch;
use App\Models\Training;
use App\Models\TrainingGrading;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class NdrtOfficerController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index(Request $request)
    {
        $query = NdrtOfficer::with('branch');

        // Search functionality
        if ($request->has('search')) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('first_name', 'like', "%{$search}%")
                  ->orWhere('surname', 'like', "%{$search}%")
                  ->orWhere('id_number', 'like', "%{$search}%");
            });
        }

        // Filter by availability
        if ($request->has('availability')) {
            $query->where('available_for_deployment', $request->availability);
        }

        // Filter by branch
        if ($request->has('branch')) {
            $query->where('branch_id', $request->branch);
        }

        $officers = $query->orderBy('created_at', 'desc')->paginate(20);
        $branches = Branch::where('is_active', true)->get();

        return view('ndrt.index', compact('officers', 'branches'));
    }

    public function create()
    {
        // $branches = Branch::where('is_active', true)->get();
        // Get branches sorted alphabetically WITHOUT the word 'Branch'
        $branches = Branch::select('*')
        ->orderByRaw("REPLACE(name, 'Branch', '') ASC")
        ->get()
        ->map(function ($item) {
            $item->clean_name = trim(str_replace('Branch', '', $item->name));
            return $item;
        });

        // Get units and append label (so they come after branches)
        $units = Branch::select('*')
        ->orderBy('name', 'ASC')
        ->get()
        ->map(function ($item) {
            $item->clean_name = $item->name . ' (Unit)';
            return $item;
        });

        // Merge branches first, units second
        // $locations = $branches->concat($units);
        $locations = $branches;

        return view('ndrt.create', compact('locations'));
    }

    public function store(Request $request)
    {
        if ($request->has('languages_spoken')) {
            $request->merge([
                'languages_spoken' => json_decode($request->languages_spoken, true)
            ]);
        }
        
        $validated = $request->validate([
            'first_name' => 'required|string|max:255',
            'middle_name' => 'nullable|string|max:255',
            'surname' => 'required|string|max:255',
            'id_type' => 'required|in:ID,Passport,Staff ID,Volunteer ID',
            'id_number' => 'required|string|unique:ndrt_officers,id_number',
            'gender' => 'required|in:Male,Female',
            'date_of_birth' => 'required|date|before:today',
            'physical_address' => 'nullable|string',
            'location_type' => 'required|in:HQ,Branch',
            'branch_id' => 'required_if:location_type,Branch|nullable|exists:branches,id',
            'unit' => 'nullable|string|max:255',
            'photo' => 'nullable|image|mimes:jpeg,jpg,png|max:2048',
            'phone_1' => 'required|string|max:20',
            'phone_2' => 'nullable|string|max:20',
            'email' => 'nullable|email|max:255',
            'emergency_contact_name' => 'required|string|max:255',
            'emergency_contact_relation' => 'required|string|max:255',
            'emergency_contact_phone_1' => 'required|string|max:20',
            'emergency_contact_phone_2' => 'nullable|string|max:20',
            'emergency_contact_address' => 'nullable|string',
            'blood_group' => 'nullable|in:A+,A-,B+,B-,O+,O-,AB+,AB-',
            'languages_spoken' => 'nullable|array|max:5',
            'health_conditions' => 'nullable|string',
            'has_disability' => 'boolean',
            'disability_details' => 'nullable|string',
            'education_level' => 'nullable|in:No formal education,Primary School,Secondary,Certificates,Diplomas,Degrees,Masters,PhD',
            'area_of_study' => 'nullable|string|max:255',
            'work_experience' => 'nullable|array|max:3',
            'competencies' => 'nullable|array',
            'available_for_deployment' => 'boolean',
            'deployment_months' => 'nullable|array',
            'deployment_months.*' => 'string',
            'training_sector' => 'nullable|string|max:255',
        ]);

        $validated['deployment_months'] = $validated['available_for_deployment']
        ? json_encode($request->input('deployment_months', [])) : null;

        // Handle photo upload
        if ($request->hasFile('photo')) {
            $validated['photo_path'] = $request->file('photo')->store('ndrt-photos', 'public');
        }

        $officer = NdrtOfficer::create($validated);

        return redirect()->route('ndrt.show', $officer)
            ->with('success', 'NDRT Officer profile created successfully.');
    }

    public function show(NdrtOfficer $ndrt)
    {
        $ndrt->load(['branch', 'trainings', 'deployments']);
        return view('ndrt.show', compact('ndrt'));
    }

    public function edit(NdrtOfficer $ndrt)
    {
        $branches = Branch::where('is_active', true)->get();
        return view('ndrt.edit', compact('ndrt', 'branches'));
    }

    public function update(Request $request, NdrtOfficer $ndrt)
    {
        if ($request->has('languages_spoken')) {
            $request->merge([
                'languages_spoken' => json_decode($request->languages_spoken, true)
            ]);
        }
        $validated = $request->validate([
            'first_name' => 'required|string|max:255',
            'middle_name' => 'nullable|string|max:255',
            'surname' => 'required|string|max:255',
            'id_type' => 'required|in:ID,Passport,Staff ID,Volunteer ID',
            'id_number' => 'required|string|unique:ndrt_officers,id_number,' . $ndrt->id,
            'gender' => 'required|in:Male,Female',
            'date_of_birth' => 'required|date|before:today',
            'physical_address' => 'nullable|string',
            'location_type' => 'required|in:HQ,Branch',
            'branch_id' => 'required_if:location_type,Branch|nullable|exists:branches,id',
            'unit' => 'nullable|string|max:255',
            'photo' => 'nullable|image|mimes:jpeg,jpg,png|max:2048',
            'phone_1' => 'required|string|max:20',
            'phone_2' => 'nullable|string|max:20',
            'email' => 'nullable|email|max:255',
            'emergency_contact_name' => 'required|string|max:255',
            'emergency_contact_relation' => 'required|string|max:255',
            'emergency_contact_phone_1' => 'required|string|max:20',
            'emergency_contact_phone_2' => 'nullable|string|max:20',
            'emergency_contact_address' => 'nullable|string',
            'blood_group' => 'nullable|in:A+,A-,B+,B-,O+,O-,AB+,AB-',
            'languages_spoken' => 'nullable|array|max:5',
            'health_conditions' => 'nullable|string',
            'has_disability' => 'boolean',
            'disability_details' => 'nullable|string',
            'education_level' => 'nullable|in:No formal education,Primary School,Secondary,Certificates,Diplomas,Degrees,Masters,PhD',
            'area_of_study' => 'nullable|string|max:255',
            'work_experience' => 'nullable|array|max:3',
            'competencies' => 'nullable|array',
            'available_for_deployment' => 'boolean',
            'deployment_months' => 'nullable|array',
            'deployment_months.*' => 'string',
            'training_sector' => 'nullable|string|max:255',
        ]);

        $validated['deployment_months'] = $validated['available_for_deployment']
        ? json_encode($request->input('deployment_months', [])) : null;

        // Handle photo upload
        if ($request->hasFile('photo')) {
            // Delete old photo
            if ($ndrt->photo_path) {
                Storage::disk('public')->delete($ndrt->photo_path);
            }
            $validated['photo_path'] = $request->file('photo')->store('ndrt-photos', 'public');
        }

        $ndrt->update($validated);

        return redirect()->route('ndrt.show', $ndrt)
            ->with('success', 'NDRT Officer profile updated successfully.');
    }

    public function destroy(NdrtOfficer $ndrt)
    {
        if ($ndrt->photo_path) {
            Storage::disk('public')->delete($ndrt->photo_path);
        }
        
        $ndrt->delete();

        return redirect()->route('ndrt.index')
            ->with('success', 'NDRT Officer profile deleted successfully.');
    }

    public function gradeTraining(Request $request, NdrtOfficer $ndrt, Training $training)
    {
        // Validate that the officer is a participant in this training
        $participants = $training->participants ?? [];
        if (!in_array((string)$ndrt->id, $participants)) {
            return redirect()->route('ndrt.show', $ndrt)
                ->with('error', 'This officer is not a participant in this training.');
        }

        // Validate the grade
        $validated = $request->validate([
            'grade' => 'required|in:1-Needs further training,2-Deploy with Support,3-Strong',
        ]);

        // Update or create the grade
        TrainingGrading::updateOrCreate(
            [
                'ndrt_officer_id' => $ndrt->id,
                'training_id' => $training->id,
            ],
            [
                'grade' => $validated['grade'],
            ]
        );

        return redirect()->route('ndrt.show', $ndrt)
            ->with('success', 'Training grade saved successfully.');
    }
}