<?php

namespace App\Http\Controllers\Workflow;

use App\Http\Controllers\Controller;
use App\Models\Workflow;
use App\Models\WorkflowStep;
use App\Models\WorkflowTransition;
use App\Helpers\AuditLogger;
use App\Models\User;
use Spatie\Permission\Models\Role;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class WorkflowTransitionController extends Controller
{
    public function edit($workflowId, $transitionId)
    {
        $workflow = Workflow::findOrFail($workflowId);
        $steps = $workflow->steps()->orderBy('order')->get();
        $roles = \Spatie\Permission\Models\Role::all();
        $users = \App\Models\User::all();
        $transition = WorkflowTransition::where('workflow_id', $workflowId)->findOrFail($transitionId);
        return view('workflow.transitions.edit', compact('workflow', 'steps', 'roles', 'users', 'transition'));
    }

    public function update(Request $request, $workflowId, $transitionId)
    {
        $workflow = Workflow::findOrFail($workflowId);
        $transition = WorkflowTransition::where('workflow_id', $workflowId)->findOrFail($transitionId);
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'from_step_id' => 'required|exists:workflow_steps,id',
            'to_step_id' => 'required|exists:workflow_steps,id',
            'role_ids' => 'nullable|array',
            'user_ids' => 'nullable|array',
            'require_comments' => 'nullable|boolean',
            'require_file' => 'nullable|boolean',
        ]);
        if (empty($request->role_ids) && empty($request->user_ids)) {
            return back()->withErrors(['role_ids' => 'At least one of Role(s) or User(s) must be selected.'])->withInput();
        }
        $validated['role_ids'] = $request->role_ids ?: null;
        $validated['user_ids'] = $request->user_ids ?: null;
        $validated['require_comments'] = $request->has('require_comments') ? 1 : 0;
        $validated['require_file'] = $request->has('require_file') ? 1 : 0;
        $validated['is_end'] = $request->has('is_end') ? 1 : 0;
        $before = $transition->toArray();
        $transition->update($validated);
        \App\Helpers\AuditLogger::log('transition', $transition->id, 'updated', $before, $transition->toArray());
        return redirect()->route('workflow.transitions.create', $workflowId)->with('message', 'Transition updated successfully.');
    }
    public function create($workflowId)
    {
        $workflow = Workflow::findOrFail($workflowId);
        $steps = $workflow->steps()->orderBy('order')->get();
        $transitions = $workflow->transitions()->with(['fromStep', 'toStep'])->get();
        $roles = Role::all();
        $users = User::all();
        return view('workflow.transitions.create', compact('workflow', 'steps', 'transitions', 'roles', 'users'));
    }

    public function store(Request $request, $workflowId)
    {
        $workflow = Workflow::findOrFail($workflowId);
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'from_step_id' => 'required|exists:workflow_steps,id',
            'to_step_id' => 'required|exists:workflow_steps,id',
            'role_ids' => 'nullable|array',
            'user_ids' => 'nullable|array',
            'require_comments' => 'nullable|boolean',
            'require_file' => 'nullable|boolean',
        ]);
        if (empty($request->role_ids) && empty($request->user_ids)) {
            return back()->withErrors(['role_ids' => 'At least one of Role(s) or User(s) must be selected.'])->withInput();
        }
        $validated['workflow_id'] = $workflow->id;
        $validated['created_by'] = Auth::id();
        $validated['role_ids'] = $request->role_ids ?: null;
        $validated['user_ids'] = $request->user_ids ?: null;
        $validated['require_comments'] = $request->has('require_comments') ? 1 : 0;
        $validated['require_file'] = $request->has('require_file') ? 1 : 0;
        $validated['is_end'] = $request->has('is_end') ? 1 : 0;
        $transition = WorkflowTransition::create($validated);
        \App\Helpers\AuditLogger::log('transition', $transition->id, 'created', null, $transition->toArray());
        // Set workflow status to active (1) if not already
        if ($workflow->status != 1) {
            $workflow->status = 1;
            $workflow->save();
        }
        if ($request->has('finish')) {
            return redirect()->route('workflow.index')->with('message', 'Workflow and transitions saved successfully.');
        }
        return redirect()->route('workflow.transitions.create', $workflow->id)->with('message', 'Transition added successfully.');
    }
}
