<?php

namespace App\Http\Controllers;

use App\Models\FormDaily48;
use App\Models\User_Detail;
use App\Models\Worker;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class FormDaily48Controller extends Controller
{
    // Display a listing of the workers and staff
    public function index()
{
    $user = auth()->user(); // Retrieve the authenticated user

    if ($user->id_role == 1) { 
        // Superadmin: Can see all workers and staff
        $workers = Worker::all();
        $staffs = User_Detail::all();
    } elseif ($user->id_role == 2) { 
        // Manager: Can see workers and staff submitted by their account or farmers under their account
        $workers = Worker::where('created_by', $user->id)
            ->orWhereHas('createdBy', function ($query) use ($user) {
                $query->where('created_by', $user->id); // Workers submitted by farmers under the manager
            })
            ->get();

        $staffs = User_Detail::where('created_by', $user->id)
            ->orWhereHas('login', function ($query) use ($user) {
                $query->where('created_by', $user->id); // Staff submitted by farmers under the manager
            })
            ->get();
    } else { 
        // Farmer: Can see only workers and staff they submitted
        $workers = Worker::where('created_by', $user->id)->get();
        $staffs = User_Detail::where('created_by', $user->id)->get();
    }

    return view('form.form_48.index48', compact('workers', 'staffs'));
}


    // Show the form to create a new worker
    public function create()
    {
        $staffs = User_Detail::all(); // Pass staff information for dropdowns if needed
        return view('form.form_48.create48', compact('staffs')); // Show form to create a new worker
    }

    // Store a newly created worker in storage
    public function store(Request $request)
    {
        $userId = auth()->id();
        // Validate the request data
        $request->validate([
            'nama_pekerja' => 'required|string|max:255',
            'tarikh_lahir' => 'required|date',
            'no_ic_passport' => 'required|string|max:255',
            'jantina' => 'required|string',
            'negara_asal' => 'required|string|max:255',
            // Training Records
            'training_date.*' => 'nullable|date',
            'jenis_latihan.*' => 'nullable|string|max:255',
            'penganjur_penceramah.*' => 'nullable|string|max:255',
            // Health Check-up Records
            'health_date.*' => 'nullable|date',
            'nama_klinik_hospital.*' => 'nullable|string|max:255',
            'justifikasi_pemeriksaan.*' => 'nullable|string|max:255',
            'rawatan_diperolehi.*' => 'nullable|string|max:255',
        ]);

        // Create a new Worker
        $worker = Worker::create(array_merge(
            $request->only([
                'nama_pekerja',
                'tarikh_lahir',
                'no_ic_passport',
                'jantina',
                'negara_asal',
            ]),
            ['created_by' => $userId] // Add the `created_by` field
        ));

        // Handle Training Records
        if ($request->has('training_date')) {
            foreach ($request->training_date as $index => $training_date) {
                if ($training_date || $request->jenis_latihan[$index] || $request->penganjur_penceramah[$index]) {
                    $worker->trainingRecords()->create([
                        'training_date' => $training_date,
                        'jenis_latihan' => $request->jenis_latihan[$index],
                        'penganjur_penceramah' => $request->penganjur_penceramah[$index],
                        'created_by' => $userId,
                    ]);
                }
            }
        }

        // Handle Health Check-up Records
        if ($request->has('health_date')) {
            foreach ($request->health_date as $index => $health_date) {
                if ($health_date || $request->nama_klinik_hospital[$index] || $request->justifikasi_pemeriksaan[$index] || $request->rawatan_diperolehi[$index]) {
                    $worker->healthCheckupRecords()->create([
                        'health_date' => $health_date,
                        'nama_klinik_hospital' => $request->nama_klinik_hospital[$index],
                        'justifikasi_pemeriksaan' => $request->justifikasi_pemeriksaan[$index],
                        'rawatan_diperolehi' => $request->rawatan_diperolehi[$index],
                        'created_by' => $userId,
                    ]);
                }
            }
        }

        return redirect()->route('form48.daily.index')->with('success', 'Worker information saved successfully.');
    }

    // Display the specified worker details
    public function show($id)
    {
        $user = Auth::user();
        $worker = Worker::findOrFail($id); // Find worker by ID
        return view('form.form_48.show48', compact('worker', 'user')); // Display worker details
    }

    // Show the form for editing the specified worker
    public function edit($id)
    {
        $worker = Worker::with(['trainingRecords', 'healthCheckupRecords'])->findOrFail($id); // Include related records
        $staffs = User_Detail::all(); // Pass staff information if needed
        return view('form.form_48.edit48', compact('worker', 'staffs')); // Display edit form
    }

    // Update the specified worker in storage
    public function update(Request $request, $id)
    {
        // Validate the request data
        $request->validate([
            'nama_pekerja' => 'required|string|max:255',
            'tarikh_lahir' => 'required|date',
            'no_ic_passport' => 'required|string|max:255',
            'jantina' => 'required|string',
            'negara_asal' => 'required|string|max:255',
            // Training Records
            'training_date.*' => 'nullable|date',
            'jenis_latihan.*' => 'nullable|string|max:255',
            'penganjur_penceramah.*' => 'nullable|string|max:255',
            // Health Check-up Records
            'health_date.*' => 'nullable|date',
            'nama_klinik_hospital.*' => 'nullable|string|max:255',
            'justifikasi_pemeriksaan.*' => 'nullable|string|max:255',
            'rawatan_diperolehi.*' => 'nullable|string|max:255',
        ]);

        // Find the worker by ID
        $worker = Worker::findOrFail($id);

        // Update worker details
        $worker->update($request->only([
            'nama_pekerja',
            'tarikh_lahir',
            'no_ic_passport',
            'jantina',
            'negara_asal',
            'nama_operator',
        ]));

        // Update training records
        $worker->trainingRecords()->delete(); // Delete existing records
        if ($request->has('training_date')) {
            foreach ($request->training_date as $index => $date) {
                $worker->trainingRecords()->create([
                    'training_date' => $date,
                    'jenis_latihan' => $request->jenis_latihan[$index],
                    'penganjur_penceramah' => $request->penganjur_penceramah[$index],
                ]);
            }
        }

        // Update health checkup records
        $worker->healthCheckupRecords()->delete(); // Delete existing records
        if ($request->has('health_date')) {
            foreach ($request->health_date as $index => $date) {
                $worker->healthCheckupRecords()->create([
                    'health_date' => $date,
                    'nama_klinik_hospital' => $request->nama_klinik_hospital[$index],
                    'justifikasi_pemeriksaan' => $request->justifikasi_pemeriksaan[$index],
                    'rawatan_diperolehi' => $request->rawatan_diperolehi[$index],
                ]);
            }
        }

        return redirect()->route('form48.daily.index')->with('success', 'Worker information updated successfully.');
    }

    // Remove the specified worker from storage
    public function destroy($id)
    {
        $worker = Worker::findOrFail($id); // Find worker by ID
        $worker->delete(); // Delete worker
        return redirect()->route('form48.daily.index')->with('success', 'Worker deleted successfully.');
    }
}
