<?php

namespace App\Http\Controllers;

use App\Http\Requests\ProcedureReportRequest;
use App\Http\Traits\Api_Trait;
use App\Models\Procedure;
use App\Models\ProcedureReport;
use App\Models\Report;
use Illuminate\Support\Facades\DB;

class ProcedureReportController extends Controller
{
    use Api_Trait;
    public function index(Report $report)
    {
        $data = $report->procedures;
        return $this->returnData($data, __('messages.procedure_list'));
    }
    public function store(ProcedureReportRequest $request, Report $report)
    {
        $auth = auth()->user();
        DB::transaction(function () use ($report, $request, $auth) {
            $report->procedures()->attach($request->procedure_id, [
                'employee_id' => $auth->id,
                'notes' => $request->notes,
            ]);
            $report->update([
                'procedure_id' => $request->procedure_id
            ]);
        });
        return $this->returnSuccessMessage(__('messages.procedure_attached'));
    }
    public function update(ProcedureReportRequest $request, Report $report, Procedure $procedure)
    {
        $auth = auth()->user();
        $procedureReport = ProcedureReport::where('report_id', $report->id)
            ->where('procedure_id', $procedure->id)
            ->first();
        DB::transaction(function () use ($procedureReport, $auth, $request, $report) {
            $procedureReport->update([
                'employee_id' => $auth->id,
                'procedure_id' => $request->procedure_id,
                'notes' => $request->notes,
            ]);
            $latestReportProcedure = $report->procedures()->orderBy('id', 'Desc')->first();
            if ($latestReportProcedure->id == $procedureReport->procedure_id) {
                $report->update([
                    'procedure_id' => $request->procedure_id
                ]);
            }
        });
        return $this->returnSuccessMessage(__('messages.procedure_updated'));
    }
    public function destroy(Report $report, Procedure $procedure)
    {
        DB::transaction(function () use ($report, $procedure) {
            $report->procedures()->detach($procedure->id);
            $latestReportProcedure = $report->procedures()->orderBy('id', 'Desc')->first();
            if ($latestReportProcedure) {
                $report->update([
                    'procedure_id' => $latestReportProcedure->id
                ]);
            }
        });
        return $this->returnSuccessMessage(__('messages.procedure_detached'));
    }
}
