<?php

namespace App\Http\Controllers\Employee;

use App\Http\Controllers\Controller;
use App\Models\PlannedTask;
use App\Models\Harvest;
use App\Models\Treatment;
use Illuminate\Http\Request;

class TaskController extends Controller
{
    /**
     * Display employee tasks dashboard.
     */
    public function index()
    {
        // Get planned treatments (Watering, Fertilization, Spraying, Pruning)
        $treatments = PlannedTask::whereIn('taskable_type', [
            'App\Models\Watering',
            'App\Models\Fertilization',
            'App\Models\Spraying',
            'App\Models\Pruning',
        ])
        ->whereNull('execution_date')
        ->orderBy('planned_date', 'asc')
        ->get();

        // Load the parent Treatment records with vineyard row data
        foreach ($treatments as $task) {
            if ($task->taskable) {
                $task->treatment = Treatment::with(['vineyardRow.varietyVariation.grapeVariety'])
                    ->find($task->taskable->treatment_id);
            }
        }

        // Get planned harvests
        $harvests = PlannedTask::where('taskable_type', 'App\Models\Harvest')
            ->with(['taskable', 'taskable.vineyardRow', 'taskable.vineyardRow.varietyVariation', 'taskable.vineyardRow.varietyVariation.grapeVariety'])
            ->whereNull('execution_date')
            ->orderBy('planned_date', 'asc')
            ->get();

        return view('employee.tasks.index', compact('treatments', 'harvests'));
    }

    /**
     * Mark treatment as done.
     */
    public function completeTreatment(PlannedTask $task)
    {
        if (!in_array($task->taskable_type, [
            'App\Models\Watering',
            'App\Models\Fertilization',
            'App\Models\Spraying',
            'App\Models\Pruning',
        ])) {
            return back()->with('error', 'Invalid task type.');
        }

        $task->update(['execution_date' => now()]);

        return back()->with('success', 'Treatment marked as done.');
    }

    /**
     * Mark harvest as complete.
     */
    public function completeHarvest(Request $request, PlannedTask $task)
    {
        if ($task->taskable_type !== 'App\Models\Harvest') {
            return back()->with('error', 'Invalid task type.');
        }

        // Validate harvest completion data
        $validated = $request->validate([
            'sugar' => 'required|numeric|min:0',
            'weight' => 'required|numeric|min:0',
            'user_id' => 'required|exists:users,id',
            'quality' => 'required|in:excellent,good,fair,poor',
        ]);

        // Update the harvest record with additional data
        $task->taskable->update([
            'sugar_content' => $validated['sugar'],
            'weight' => $validated['weight'],
            'user_id' => $validated['user_id'],
            'quality' => $validated['quality'],
        ]);

        // Mark task as executed
        $task->update(['execution_date' => now()]);

        return back()->with('success', 'Harvest completed successfully with all details.');
    }
}
