<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Beneficiary;

class BeneficiaryController extends Controller
{
    public function index(Request $request)
    {
        $search = $request->input('search');

        $beneficiaries = Beneficiary::accessibleBy(auth()->user())
            ->with(['horticultures', 'livestocks', 'poultries', 'fish'])
            ->when($search, function ($query, $search) {
                return $query->where(function ($q) use ($search) {
                    $q->where('name', 'like', "%{$search}%")
                      ->orWhere('nik', 'like', "%{$search}%")
                      ->orWhere('village', 'like', "%{$search}%")
                      ->orWhere('district', 'like', "%{$search}%")
                      ->orWhere('foster_parent_name', 'like', "%{$search}%");
                });
            })
            ->latest()
            ->paginate(10)
            ->withQueryString();

        return view('beneficiaries.index', compact('beneficiaries'));
    }

    public function create()
    {
        return view('beneficiaries.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'nik' => 'required|string|unique:beneficiaries,nik|max:20',
            'address' => 'nullable|string',
            'village' => 'required|string',
            'district' => 'required|string',
            'foster_parent_name' => 'nullable|string',
            'foster_parent_role' => 'nullable|string',
            'latitude' => 'nullable|numeric',
            'longitude' => 'nullable|numeric',
            'status' => 'required|in:active,inactive,graduated',
            'horticultures' => 'array',
            'horticultures.*.type' => 'nullable|string|max:255',
            'horticultures.*.commodity' => 'nullable|string|max:255',
            'horticultures.*.quantity' => 'nullable|string|max:255',
            'livestocks' => 'array',
            'livestocks.*.type' => 'nullable|string|max:255',
            'livestocks.*.male_count' => 'nullable|integer',
            'livestocks.*.female_count' => 'nullable|integer',
            'poultries' => 'array',
            'poultries.*.type' => 'nullable|string|max:255',
            'poultries.*.quantity' => 'nullable|string|max:255',
            'poultries.*.distribution_date' => 'nullable|date',
            'fish' => 'array',
            'fish.*.type' => 'nullable|string|max:255',
            'fish.*.quantity' => 'nullable|string|max:255',
            'fish.*.distribution_date' => 'nullable|date',
        ]);

        $beneficiary = Beneficiary::create($validated);

        if ($request->has('horticultures')) {
            foreach ($request->input('horticultures') as $horticultureData) {
                if (!empty($horticultureData['type'])) {
                    $beneficiary->horticultures()->create($horticultureData);
                }
            }
        }
        if ($request->has('livestocks')) {
            foreach ($request->input('livestocks') as $livestockData) {
                if (!empty($livestockData['type'])) {
                    $beneficiary->livestocks()->create($livestockData);
                }
            }
        }
        if ($request->has('poultries')) {
            foreach ($request->input('poultries') as $poultryData) {
                if (!empty($poultryData['type'])) {
                    $beneficiary->poultries()->create($poultryData);
                }
            }
        }
        if ($request->has('fish')) {
            foreach ($request->input('fish') as $fishData) {
                if (!empty($fishData['type'])) {
                    $beneficiary->fish()->create($fishData);
                }
            }
        }

        return redirect()->route('beneficiaries.index')->with('success', 'Data penerima berhasil ditambahkan.');
    }

    public function show($id)
    {
        $beneficiary = Beneficiary::with(['horticultures', 'livestocks', 'poultries', 'fish', 'documentations', 'monitorings'])->findOrFail($id);
        return view('beneficiaries.show', compact('beneficiary'));
    }

    public function edit($id)
    {
        $beneficiary = Beneficiary::findOrFail($id);
        return view('beneficiaries.edit', compact('beneficiary'));
    }

    public function update(Request $request, $id)
    {
        $beneficiary = Beneficiary::findOrFail($id);

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'nik' => 'required|string|max:20|unique:beneficiaries,nik,' . $beneficiary->id,
            'address' => 'nullable|string',
            'village' => 'required|string',
            'district' => 'required|string',
            'foster_parent_name' => 'nullable|string',
            'foster_parent_role' => 'nullable|string',
            'latitude' => 'nullable|numeric',
            'longitude' => 'nullable|numeric',
            'status' => 'required|in:active,inactive,graduated',
            'horticultures' => 'array',
            'horticultures.*.id' => 'nullable|exists:horticultures,id',
            'horticultures.*.type' => 'nullable|string|max:255',
            'horticultures.*.commodity' => 'nullable|string|max:255',
            'horticultures.*.quantity' => 'nullable|string|max:255',
            'livestocks' => 'array',
            'livestocks.*.id' => 'nullable|exists:livestocks,id',
            'livestocks.*.type' => 'nullable|string|max:255',
            'livestocks.*.male_count' => 'nullable|integer',
            'livestocks.*.female_count' => 'nullable|integer',
            'poultries' => 'array',
            'poultries.*.id' => 'nullable|exists:poultries,id',
            'poultries.*.type' => 'nullable|string|max:255',
            'poultries.*.quantity' => 'nullable|string|max:255',
            'poultries.*.distribution_date' => 'nullable|date',
            'fish' => 'array',
            'fish.*.id' => 'nullable|exists:fish,id',
            'fish.*.type' => 'nullable|string|max:255',
            'fish.*.quantity' => 'nullable|string|max:255',
            'fish.*.distribution_date' => 'nullable|date',
        ]);

        $beneficiary->update($validated);

        // Sync Horticultures
        $currentHorticultureIds = $beneficiary->horticultures->pluck('id')->toArray();
        $submittedHorticultureIds = [];
        if ($request->has('horticultures')) {
            foreach ($request->input('horticultures') as $horticultureData) {
                if (empty($horticultureData['type'])) continue;
                
                if (isset($horticultureData['id'])) {
                    $beneficiary->horticultures()->where('id', $horticultureData['id'])->update($horticultureData);
                    $submittedHorticultureIds[] = $horticultureData['id'];
                } else {
                    $beneficiary->horticultures()->create($horticultureData);
                }
            }
        }
        $horticulturesToDelete = array_diff($currentHorticultureIds, $submittedHorticultureIds);
        $beneficiary->horticultures()->whereIn('id', $horticulturesToDelete)->delete();

        // Sync Livestocks
        $currentLivestockIds = $beneficiary->livestocks->pluck('id')->toArray();
        $submittedLivestockIds = [];
        if ($request->has('livestocks')) {
            foreach ($request->input('livestocks') as $livestockData) {
                if (empty($livestockData['type'])) continue;

                if (isset($livestockData['id'])) {
                    $beneficiary->livestocks()->where('id', $livestockData['id'])->update($livestockData);
                    $submittedLivestockIds[] = $livestockData['id'];
                } else {
                    $beneficiary->livestocks()->create($livestockData);
                }
            }
        }
        $livestocksToDelete = array_diff($currentLivestockIds, $submittedLivestockIds);
        $beneficiary->livestocks()->whereIn('id', $livestocksToDelete)->delete();

        // Sync Poultries
        $currentPoultryIds = $beneficiary->poultries->pluck('id')->toArray();
        $submittedPoultryIds = [];
        if ($request->has('poultries')) {
            foreach ($request->input('poultries') as $poultryData) {
                if (empty($poultryData['type'])) continue;

                if (isset($poultryData['id'])) {
                    $beneficiary->poultries()->where('id', $poultryData['id'])->update($poultryData);
                    $submittedPoultryIds[] = $poultryData['id'];
                } else {
                    $beneficiary->poultries()->create($poultryData);
                }
            }
        }
        $poultriesToDelete = array_diff($currentPoultryIds, $submittedPoultryIds);
        $beneficiary->poultries()->whereIn('id', $poultriesToDelete)->delete();

        // Sync Fish
        $currentFishIds = $beneficiary->fish->pluck('id')->toArray();
        $submittedFishIds = [];
        if ($request->has('fish')) {
            foreach ($request->input('fish') as $fishData) {
                if (empty($fishData['type'])) continue;

                if (isset($fishData['id'])) {
                    $beneficiary->fish()->where('id', $fishData['id'])->update($fishData);
                    $submittedFishIds[] = $fishData['id'];
                } else {
                    $beneficiary->fish()->create($fishData);
                }
            }
        }
        $fishToDelete = array_diff($currentFishIds, $submittedFishIds);
        $beneficiary->fish()->whereIn('id', $fishToDelete)->delete();

        return redirect()->route('beneficiaries.index')->with('success', 'Data penerima berhasil diperbarui.');
    }
}
