<?php

namespace App\Http\Controllers\Workflow;

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

class WorkflowController extends Controller
{
    /**
     * Show the audit history page for workflows, steps, and transitions.
     */
    public function auditHistory(Request $request)
    {
        $query = WorkflowAudit::query()->with('user');

        if ($request->filled('entity_type')) {
            $query->where('entity_type', $request->string('entity_type'));
        }

        if ($request->filled('user')) {
            $userSearch = $request->string('user');
            $query->whereHas('user', function ($q) use ($userSearch) {
                $q->where('name', 'like', '%' . $userSearch . '%')
                    ->orWhere('email', 'like', '%' . $userSearch . '%');
            });
        }

        if ($request->filled('action')) {
            $query->where('action', $request->string('action'));
        }

        if ($request->filled('from_date')) {
            $query->whereDate('created_at', '>=', $request->date('from_date'));
        }

        if ($request->filled('to_date')) {
            $query->whereDate('created_at', '<=', $request->date('to_date'));
        }

        $audits = $query->orderByDesc('created_at')->paginate(30)->withQueryString();

        return view('workflow.audit', compact('audits'));
    }
    public function index()
    {
        $workflows = Workflow::with(['createdBy', 'steps', 'transitions.fromStep', 'transitions.toStep'])->paginate(15);
        // Attach users to each transition (using the accessor)
        foreach ($workflows as $workflow) {
            foreach ($workflow->transitions as $transition) {
                // This will trigger the getUsersAttribute accessor
                $transition->setRelation('users', $transition->users);
            }
        }
        return view('workflow.index', compact('workflows'));
    }

    public function create()
    {
        return view('workflow.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255|unique:workflows,name',
            'description' => 'nullable|string',
        ]);
    $validated['created_by'] = Auth::id();
    $validated['status'] = 0;
    $workflow = Workflow::create($validated);
    \App\Helpers\AuditLogger::log('workflow', $workflow->id, 'created', null, $workflow->toArray());
        if ($request->ajax()) {
            return response()->json(['id' => $workflow->id]);
        }
        return redirect()->route('workflow.steps.create', $workflow->id)->with('message', 'Workflow created successfully.');
    }

    public function edit(Workflow $workflow)
    {
        return view('workflow.edit', compact('workflow'));
    }

    public function update(Request $request, Workflow $workflow)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255|unique:workflows,name,' . $workflow->id,
            'description' => 'nullable|string',
            'status' => 'required|in:1,0',
        ]);
    $before = $workflow->toArray();
    $workflow->update($validated);
    \App\Helpers\AuditLogger::log('workflow', $workflow->id, 'updated', $before, $workflow->toArray());
        return redirect()->route('workflow.index')->with('message', 'Workflow updated successfully.');
    }

    public function destroy(Workflow $workflow)
    {
    $before = $workflow->toArray();
    $workflow->delete();
    \App\Helpers\AuditLogger::log('workflow', $workflow->id, 'deleted', $before, null);
        return redirect()->route('workflow.index')->with('message', 'Workflow deleted successfully.');
    }

    /**
     * Display the specified workflow and its details.
     */
    public function show(Workflow $workflow)
    {
        $workflow->load(['steps', 'transitions', 'tasks']);
        return view('workflow.show', compact('workflow'));
    }
}
