<?php

namespace App\Services;

use App\Models\FormInstance;
use App\Models\FormWorkflow;
use App\Models\FormActivityLog;
use Illuminate\Support\Facades\Auth;

class FormWorkflowService
{
    public function performAction(FormInstance $instance, string $action)
    {
        $transition = FormWorkflow::where([
            'form_template_id' => $instance->form_template_id,
            'current_status' => $instance->current_status,
            'action_label' => $action
        ])->firstOrFail();

        // Role check
        if ($transition->allowed_role !== Auth::user()->role) {
            abort(403, 'Action not allowed');
        }

        $oldStatus = $instance->current_status;
        $instance->current_status = $transition->next_status;
        $instance->save();

        FormActivityLog::create([
            'form_instance_id' => $instance->id,
            'action' => $action,
            'from_status' => $oldStatus,
            'to_status' => $transition->next_status,
            'performed_by' => Auth::id()
        ]);
    }

    

}

