<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Beneficiary;
use App\Models\Monitoring;
use App\Models\Documentation;
use Illuminate\Support\Facades\Auth;

class MonitoringController extends Controller
{
    public function create($beneficiary_id)
    {
        $beneficiary = Beneficiary::with(['horticultures', 'livestocks', 'poultries', 'fish'])->findOrFail($beneficiary_id);
        return view('monitoring.create', compact('beneficiary'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'beneficiary_id' => 'required|exists:beneficiaries,id',
            'notes' => 'required',
            'monitoring_date' => 'required|date',
            'photos.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            'components' => 'sometimes|array'
        ]);

        $firstMonitoring = null;
        $componentMap = [
            'horticultures' => \App\Models\Horticulture::class,
            'livestocks' => \App\Models\Livestock::class,
            'poultries' => \App\Models\Poultry::class,
            'fish' => \App\Models\Fish::class,
        ];

        if ($request->has('components')) {
            foreach ($request->components as $type => $items) {
                foreach ($items as $itemData) {
                    $monitoring = Monitoring::create([
                        'beneficiary_id' => $request->beneficiary_id,
                        'user_id' => Auth::id() ?? 1,
                        'component_type' => $componentMap[$type] ?? null,
                        'component_id' => $itemData['id'],
                        'notes' => $request->notes,
                        'monitoring_date' => $request->monitoring_date,
                        'growth_percentage' => $itemData['growth_percentage'] ?? 0,
                        'health_status' => $itemData['health_status'] ?? 'Sehat',
                        'latitude' => $request->latitude,
                        'longitude' => $request->longitude,
                    ]);

                    if (!$firstMonitoring) {
                        $firstMonitoring = $monitoring;
                    }
                }
            }
        }

        // Jika tidak ada komponen, buat record monitoring umum agar foto bisa dikaitkan
        if (!$firstMonitoring) {
            $firstMonitoring = Monitoring::create([
                'beneficiary_id' => $request->beneficiary_id,
                'user_id' => Auth::id() ?? 1,
                'component_type' => null,
                'component_id' => null,
                'notes' => $request->notes,
                'monitoring_date' => $request->monitoring_date,
                'growth_percentage' => 0,
                'health_status' => 'Umum',
                'latitude' => $request->latitude,
                'longitude' => $request->longitude,
            ]);
        }

        if ($request->hasFile('photos') && $firstMonitoring) {
            foreach ($request->file('photos') as $photo) {
                $path = $photo->store('documentation', 'public');
                Documentation::create([
                    'monitoring_id' => $firstMonitoring->id,
                    'beneficiary_id' => $request->beneficiary_id,
                    'file_path' => $path,
                    'type' => 'monitoring',
                    'latitude' => $request->latitude,
                    'longitude' => $request->longitude,
                ]);
            }
        }

        return redirect()->route('beneficiaries.show', $request->beneficiary_id)
            ->with('success', 'Data monitoring per komponen berhasil disimpan!');
    }
}
