<?php

namespace App\Http\Controllers;

use App\Models\FormDaily47;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\Farm_section;
use App\Models\Task; // Ensure this is included

class FormDaily47Controller extends Controller
{
    /**
     * Display a list of submitted forms.
     */
    public function index()
    {
        $user = auth()->user(); // Retrieve the authenticated user
        $query = FormDaily47::with('farmSection', 'createdBy'); // Base query with relationships
    
        if ($user->id_role == 1) { 
            // Superadmin: Can see all submissions
            $submissions = $query->orderBy('created_at', 'desc')->get();
        } elseif ($user->id_role == 2) { 
            // Manager: Can see submissions they created, submissions from farmers they created, and submissions from farm sections linked to farms they created
            $submissions = $query
                ->where('created_by', $user->id) // Submissions created by the manager
                ->orWhereHas('createdBy', function ($query) use ($user) {
                    $query->where('created_by', $user->id); // Submissions from farmers created by the manager
                })
                ->orWhereHas('farmSection', function ($query) use ($user) {
                    $query->whereHas('farm', function ($subQuery) use ($user) {
                        $subQuery->where('login_id', $user->id); // Submissions from farm sections linked to farms created by the manager
                    });
                })
                ->orderBy('created_at', 'desc')
                ->get();
        } else { 
            // Farmer: Can only see submissions they created
            $submissions = $query
                ->where('created_by', $user->id) 
                ->orderBy('created_at', 'desc')
                ->get();
        }
    
        return view('form.form_47.index47', compact('submissions'));
    }
    

    /**
     * Show the form for creating a new entry.
     */
    public function create()
    {
        // Fetch all form sections to populate the dropdown
        $user = Auth::user(); // Get the logged-in user
        $role = $user->role->name; // Assuming the role relationship is set and has a `name` field
        $sections = [];

        if ($role === 'Superadmin') {
            // Superadmin: Display all sections
            $sections = Farm_Section::all();
        } elseif ($role === 'Manager') {
            // Manager: Display sections created by the manager
            $sections = Farm_Section::where('id_farm', $user->id)->get();
            // Replace `created_by` with the actual column tracking the creator's ID
        } elseif ($role === 'Farmer') {
            // Farmer: Display sections from tasks assigned to this account
            $sections = Task::where('task_assigned_to', $user->id)
                ->with('section') // Load the related section
                ->get()
                ->pluck('section') // Extract the related sections
                ->unique('id') // Remove duplicates
                ->filter(); // Remove null sections if any
        }

        // Pass sections to the view
        return view('form.form_47.create47', compact('sections'));
    }

    /**
     * Store a newly created entry in storage.
     */
    public function store(Request $request)
    {
        // Validate the incoming request
        $request->validate([
            'id_farm_section' => 'required|exists:farm_section,id',
            'jenis_tanaman' => 'required|string',
            'Blok_Lokasi ' => 'required|string',
            'justifikasi_rawatan' => 'required|string',
            'jenis_rawatan' => 'required|string',
            'bahan_aktif_kadar' => 'required|string',
            'tempoh_rawatan' => 'required|string',
        ]);

        // Create the new entry
        FormDaily47::create([
            'id_farm_section' => $request->id_farm_section,
            'created_by' => Auth::id(), // Get the currently logged-in user ID
            'jenis_tanaman' => $request->jenis_tanaman,
            'Blok_Lokasi'=> $request->Blok_Lokasi,
            'justifikasi_rawatan' => $request->justifikasi_rawatan,
            'jenis_rawatan' => $request->jenis_rawatan,
            'bahan_aktif_kadar' => $request->bahan_aktif_kadar,
            'tempoh_rawatan' => $request->tempoh_rawatan,
            'nama_operator' => Auth::user()->username, // Automatically assign the operator's name
        ]);

        // Redirect back to the index with success message
        return redirect()->route('form47.daily.index')->with('success', 'Entry created successfully!');
    }

    /**
     * Display the specified entry.
     */
    public function show($id)
    {
        // Find the submitted entry by ID
        $submission = FormDaily47::with('farmSection', 'createdBy')->findOrFail($id);

        // Pass the submission to the view
        return view('form.form_47.show47', compact('submission'));
    }

    /**
     * Show the form for editing the specified entry.
     */
    public function edit($id)
    {
        // Find the submitted entry by ID
        $submission = FormDaily47::findOrFail($id);

        // Fetch all form sections to populate the dropdown
        $user = Auth::user(); // Get the logged-in user
        $role = $user->role->name; // Assuming the role relationship is set and has a `name` field
        $sections = [];

        if ($role === 'Superadmin') {
            // Superadmin: Display all sections
            $sections = Farm_Section::all();
        } elseif ($role === 'Manager') {
            // Manager: Display sections created by the manager
            $sections = Farm_Section::where('id_farm', $user->id)->get();
            // Replace `created_by` with the actual column tracking the creator's ID
        } elseif ($role === 'Farmer') {
            // Farmer: Display sections from tasks assigned to this account
            $sections = Task::where('task_assigned_to', $user->id)
                ->with('section') // Load the related section
                ->get()
                ->pluck('section') // Extract the related sections
                ->unique('id') // Remove duplicates
                ->filter(); // Remove null sections if any
        }
        
        // Pass submission and sections to the view
        return view('form.form_47.edit47', compact('submission', 'sections'));
    }

    /**
     * Update the specified entry in storage.
     */
    public function update(Request $request, $id)
    {
        // Validate the incoming request
        $request->validate([
            'id_farm_section' => 'required|exists:farm_section,id',
            'jenis_tanaman' => 'required|string',
            'Blok_Lokasi ' => 'required|string',
            'justifikasi_rawatan' => 'required|string',
            'jenis_rawatan' => 'required|string',
            'bahan_aktif_kadar' => 'required|string',
            'tempoh_rawatan' => 'required|string',
        ]);

        // Find the entry by ID
        $submission = FormDaily47::findOrFail($id);

        // Update the entry with the new data
        $submission->update([
            'id_farm_section' => $request->id_farm_section,
            'jenis_tanaman' => $request->jenis_tanaman,
            'Blok_Lokasi'=> $request->Blok_Lokasi,
            'justifikasi_rawatan' => $request->justifikasi_rawatan,
            'jenis_rawatan' => $request->jenis_rawatan,
            'bahan_aktif_kadar' => $request->bahan_aktif_kadar,
            'tempoh_rawatan' => $request->tempoh_rawatan,
        ]);

        // Redirect back to the index with success message
        return redirect()->route('form47.daily.index')->with('success', 'Entry updated successfully!');
    }

    /**
     * Remove the specified entry from storage.
     */
    public function destroy($id)
    {
        // Find the entry by ID
        $submission = FormDaily47::findOrFail($id);

        // Delete the entry
        $submission->delete();

        // Redirect back to the index with success message
        return redirect()->route('form47.daily.index')->with('success', 'Entry deleted successfully!');
    }
}
