<?php

namespace App\Http\Controllers\Workflow;

use App\Http\Controllers\Controller;
use App\Models\Workflow;
use App\Models\WorkflowStep;
use App\Helpers\AuditLogger;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class WorkflowStepController extends Controller
{
    public function create($workflowId)
    {
        $workflow = Workflow::findOrFail($workflowId);
        $steps = $workflow->steps()->orderBy('order')->get();
        return view('workflow.steps.create', compact('workflow', 'steps'));
    }

    public function store(Request $request, $workflowId)
    {
        $workflow = Workflow::findOrFail($workflowId);
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'order' => 'nullable|integer',
        ]);
        $validated['workflow_id'] = $workflow->id;
        $validated['created_by'] = Auth::id();
        $validated['order'] = $validated['order'] ?? ($workflow->steps()->max('order') + 1);
    $step = WorkflowStep::create($validated);
    \App\Helpers\AuditLogger::log('step', $step->id, 'created', null, $step->toArray());
        return redirect()->route('workflow.steps.create', $workflow->id)->with('message', 'Step added successfully.');
    }

    public function edit($workflowId, $stepId)
    {
        $workflow = Workflow::findOrFail($workflowId);
        $step = WorkflowStep::where('workflow_id', $workflowId)->findOrFail($stepId);
        return view('workflow.steps.edit', compact('workflow', 'step'));
    }

    public function update(Request $request, $workflowId, $stepId)
    {
        $workflow = Workflow::findOrFail($workflowId);
        $step = WorkflowStep::where('workflow_id', $workflowId)->findOrFail($stepId);
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'order' => 'nullable|integer',
        ]);

        $oldOrder = $step->order;
        $newOrder = $validated['order'] ?? $oldOrder;

        if ($newOrder != $oldOrder) {
            // Ensure newOrder is within valid range
            $stepCount = $workflow->steps()->count();
            $newOrder = max(1, min($newOrder, $stepCount));

            if ($newOrder > $oldOrder) {
                // Move step down: decrement order of steps between oldOrder+1 and newOrder
                WorkflowStep::where('workflow_id', $workflowId)
                    ->where('order', '>', $oldOrder)
                    ->where('order', '<=', $newOrder)
                    ->decrement('order');
            } elseif ($newOrder < $oldOrder) {
                // Move step up: increment order of steps between newOrder and oldOrder-1
                WorkflowStep::where('workflow_id', $workflowId)
                    ->where('order', '>=', $newOrder)
                    ->where('order', '<', $oldOrder)
                    ->increment('order');
            }
            $step->order = $newOrder;
        }
        $step->name = $validated['name'];
    $before = $step->toArray();
    $step->save();
    \App\Helpers\AuditLogger::log('step', $step->id, 'updated', $before, $step->toArray());
        return redirect()->route('workflow.steps.create', $workflowId)->with('message', 'Step updated and reordered successfully.');
    }

    public function destroy($workflowId, $stepId)
    {
        $step = WorkflowStep::where('workflow_id', $workflowId)->findOrFail($stepId);
    $before = $step->toArray();
    $step->delete();
    \App\Helpers\AuditLogger::log('step', $step->id, 'deleted', $before, null);
        return redirect()->route('workflow.steps.create', $workflowId)->with('message', 'Step deleted successfully.');
    }
}
