@push('styles')
<link rel="stylesheet" href="{{ asset('assets/css/workflow-actions.css') }}">
<link rel="stylesheet" href="{{ asset('assets/css/folder-management.css') }}">
<!-- Mermaid.js CDN -->
@endpush
@extends('admin.admin_master')

@section('admin')
<div class="page-content">
    <div class="container-fluid">
        <!-- Enhanced Page Header with Navigation (copied from folder template) -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="page-header-card">
                    <div class="page-header-content">
                        <div class="d-flex align-items-center justify-content-between">
                            <div class="d-flex align-items-center">
                                <div class="page-icon me-3">
                                    <div class="avatar-md">
                                        <div class="avatar-title bg-primary-subtle text-primary rounded-circle">
                                            <i class="ri-list-check-2 font-size-24"></i>
                                        </div>
                                    </div>
                                </div>
                                <div class="flex-grow-1">
                                    <h4 class="page-title mb-1">Workflow Management</h4>
                                    <nav aria-label="breadcrumb">
                                        <ol class="breadcrumb mb-0">
                                            <li class="breadcrumb-item">
                                                <a href="{{ route('workflow.index') }}" class="text-primary">
                                                    <i class="ri-home-4-line me-1"></i>
                                                </a>
                                            </li>
                                            <!-- Add dynamic breadcrumb items here if needed -->
                                        </ol>
                                    </nav>
                                </div>
                            </div>

<div class="d-flex gap-2">
                                                <button type="button" class="btn btn-outline-secondary btn-sm" onclick="location.reload()" data-bs-toggle="tooltip" aria-label="Refresh Folders" data-bs-original-title="Refresh Folders">
                            <i class="ri-refresh-line font-size-12"></i>
                        </button>
                        <a href="{{ route('workflow.create') }}">
                            <button type="button" class="btn btn-primary btn-sm d-flex align-items-center" data-bs-toggle="modal" data-bs-target="#createFolderModal" title="Create New Folder">
                                <i class="ri-folder-add-line font-size-14 me-1"></i>
                                <span>Create Workflow</span>
                            </button>
                        </a>
                    </div>



                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Search and Filter Section (copied from folder template) -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card shadow-sm border-0 search-filter-card">
                    <div class="card-body p-3">
                        <div class="row g-3 align-items-center">
                            <div class="col-md-4">
                                <div class="input-group">
                                    <span class="input-group-text bg-white border-end-0">
                                        <i class="ri-search-line text-muted"></i>
                                    </span>
                                    <input type="text" class="form-control border-start-0" id="workflowSearchInput" placeholder="Search workflows...">
                                </div>
                            </div>
                           
                        </div>
                    </div>
                </div>
            </div>
        </div>
        @if(session('message'))
            <div class="alert alert-success">{{ session('message') }}</div>
        @endif
        @if($errors->any())
            <div class="alert alert-danger">
                <ul class="mb-0">
                    @foreach($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif
        <div class="card">
            <div class="card-body">
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Description</th>
                            <th>Initiated By</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($workflows as $workflow)
                        <tr>
                            <td>{{ $workflow->name }}</td>
                            <td>{{ $workflow->description }}</td>
                            <td>
                                @if($workflow->createdBy)
                                    {{ $workflow->createdBy->first_name }} {{ $workflow->createdBy->last_name }}
                                @else
                                    -
                                @endif
                            </td>
                            <td>
                               
                                <span class="badge bg-{{ $workflow->status == 1 ? 'success' : 'warning' }}">
                                    {{ $workflow->status == 1 ? 'Active' : 'Draft' }}
                                </span>
                            </td>
                            <td>
                                <div class="dropdown">
                                    <button class="btn btn-sm btn-light" type="button" id="dropdownMenuButton{{ $workflow->id }}" data-bs-toggle="dropdown" aria-expanded="false">
                                        <span style="font-size: 1.5em; vertical-align: middle;">&#8942;</span>
                                    </button>
                                    <ul class="dropdown-menu workflow-actions-dropdown" aria-labelledby="dropdownMenuButton{{ $workflow->id }}">
                                            <li>
                                                @can('View Workflows')
                                                <a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#viewWorkflowModal{{ $workflow->id }}">
                                                    <i class="ri-eye-line me-2 text-primary"></i> View Workflow
                                                </a>
                                                @endcan
                                            </li>
                                        <li>
                                                @can('Edit Workflows')
                                                <a class="dropdown-item" href="{{ route('workflow.edit', $workflow) }}">
                                                    <i class="ri-pencil-line me-2 text-warning"></i> Edit Workflow
                                                </a>
                                                @endcan
                                        </li>
                                        <li>
                                                @can('Delete Workflows')
                                                <form action="{{ route('workflow.destroy', $workflow) }}" method="POST" style="display:inline-block">
                                                    @csrf
                                                    @method('DELETE')
                                                    <button type="submit" class="dropdown-item text-danger" onclick="return confirm('Delete this workflow?')">
                                                        <i class="ri-delete-bin-line me-2"></i> Delete Workflow
                                                    </button>
                                                </form>
                                                @endcan
                                        </li>
                                    </ul>
                                </div>
                            </td>
                        </tr>
                        <!-- Modal for viewing workflow info -->
                                                <div class="modal fade" id="viewWorkflowModal{{ $workflow->id }}" tabindex="-1" aria-labelledby="viewWorkflowModalLabel{{ $workflow->id }}" aria-hidden="true">
                                                    <div class="modal-dialog modal-xl">
                                                        <div class="modal-content">
                                                            <div class="modal-header bg-primary text-white">
                                                                <h5 class="modal-title" id="viewWorkflowModalLabel{{ $workflow->id }}">
                                                                    <i class="ri-flow-chart me-2"></i> Workflow Details
                                                                </h5>
                                                                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                                                            </div>
                                                                                            <div class="modal-body">
                                                                                                                                <div class="row g-4">
                                                                                                                                    <!-- Column 1: Initial Details -->
                                                                                                                                    <div class="col-md-4">
                                                                                                                                        <div class="mb-3">
                                                                                                                                            <label class="fw-bold">Name:</label>
                                                                                                                                            <div>{{ $workflow->name }}</div>
                                                                                                                                        </div>
                                                                                                                                        <div class="mb-3">
                                                                                                                                            <label class="fw-bold">Description:</label>
                                                                                                                                            <div>{{ $workflow->description }}</div>
                                                                                                                                        </div>
                                                                                                                                        <div class="mb-3">
                                                                                                                                            <label class="fw-bold">Initiated By:</label>
                                                                                                                                            <div>
                                                                                                                                                @if($workflow->createdBy)
                                                                                                                                                    {{ $workflow->createdBy->first_name }} {{ $workflow->createdBy->last_name }}
                                                                                                                                                @else
                                                                                                                                                    -
                                                                                                                                                @endif
                                                                                                                                            </div>
                                                                                                                                        </div>
                                                                                                                                        <div class="mb-3">
                                                                                                                                            <label class="fw-bold">Status:</label>
                                                                                                                                            <span>Status: </span><span class="badge bg-{{ $workflow->status == 'complete' ? 'success' : 'secondary' }}">{{ ucfirst($workflow->status) }}</span>
                                                                                                                                        </div>
                                                                                                                                        <div class="mb-3">
                                                                                                                                            <label class="fw-bold">Created At:</label>
                                                                                                                                            <div>{{ $workflow->created_at }}</div>
                                                                                                                                        </div>
                                                                                                                                        <div class="mb-3">
                                                                                                                                            <label class="fw-bold">Updated At:</label>
                                                                                                                                            <div>{{ $workflow->updated_at }}</div>
                                                                                                                                        </div>
                                                                                                                                        <div class="mb-3">
                                                                                                                                            <label class="fw-bold">History:</label>
                                                                                                                                            <div style="max-height:180px;overflow:auto;">
                                                                                                                                                @php
                                                                                                                                                    $audits = \App\Models\WorkflowAudit::where('entity_type', 'workflow')->where('entity_id', $workflow->id)->orderByDesc('created_at')->with('user')->get();
                                                                                                                                                @endphp
                                                                                                                                                <ul class="list-group">
                                                                                                                                                    @forelse($audits as $audit)
                                                                                                                                                        <li class="list-group-item small">
                                                                                                                                                            <span class="fw-bold">{{ ucfirst($audit->action) }}</span>
                                                                                                                                                            by {{ $audit->user ? ($audit->user->name ?? ($audit->user->first_name . ' ' . $audit->user->last_name)) : 'System' }}
                                                                                                                                                            <span class="text-muted">at {{ $audit->created_at->format('Y-m-d H:i') }}</span>
                                                                                                                                                            @if($audit->action === 'updated')
                                                                                                                                                                <br><span class="text-info">Changed:</span>
                                                                                                                                                                @foreach(array_diff_assoc($audit->after ?? [], $audit->before ?? []) as $key => $val)
                                                                                                                                                                    <span class="text-warning">{{ $key }}</span>: <span class="text-success">{{ $val }}</span><br>
                                                                                                                                                                @endforeach
                                                                                                                                                            @endif
                                                                                                                                                        </li>
                                                                                                                                                    @empty
                                                                                                                                                        <li class="list-group-item text-muted">No history found.</li>
                                                                                                                                                    @endforelse
                                                                                                                                                </ul>
                                                                                                                                            </div>
                                                                                                                                        </div>
                                                                                                                                    </div>
                                                                                                                                    <!-- Column 2: Steps & Transitions -->
                                                                                                                                    <div class="col-md-4">
                                                                                                                                        <div class="mb-3">
                                                                                                                                            <label class="fw-bold">Steps:</label>
                                                                                                                                            <ol class="ps-3">
                                                                                                                                                @foreach($workflow->steps as $step)
                                                                                                                                                    <li><span class="fw-semibold">{{ $step->order }}.</span> {{ $step->name }}</li>
                                                                                                                                                @endforeach
                                                                                                                                            </ol>
                                                                                                                                        </div>
                                                                                                                                        <div class="mb-3">
                                                                                                                                            <label class="fw-bold">Transitions:</label>
                                                                                                                                            <div class="d-flex flex-column gap-3">
                                                                                                                                                @foreach($workflow->transitions as $transition)
                                                                                                                                                    <div class="card p-3 shadow-sm border-0 bg-white transition-card">
                                                                                                                                                        <h6 class="mb-2 fw-bold transition-title">{{ $transition->name }}</h6>
                                                                                                                                                        <div class="d-flex align-items-center mb-2">
                                                                                                                                                            <span class="fw-semibold text-primary" style="font-size:1.1em;">{{ $transition->fromStep->name ?? '-' }}</span>
                                                                                                                                                            <i class="ri-arrow-right-line mx-2 text-secondary" style="font-size:1.5em;"></i>
                                                                                                                                                            <span class="fw-semibold text-success" style="font-size:1.1em;">{{ $transition->toStep->name ?? '-' }}</span>
                                                                                                                                                        </div>
                                                                                                                                                        @if($transition->users && count($transition->users))
                                                                                                                                                            <div class="d-flex align-items-center ms-4">
                                                                                                                                                                <i class="ri-user-3-line me-2 text-muted"></i>
                                                                                                                                                                <span class="text-muted small">Assigned Users:</span>
                                                                                                                                                                <div class="ms-2 d-flex flex-wrap gap-1">
                                                                                                                                                                    @foreach($transition->users as $user)
                                                                                                                                                                        <span class="badge bg-secondary">{{ $user->first_name ?? '' }} {{ $user->last_name ?? $user->name ?? '' }}</span>
                                                                                                                                                                    @endforeach
                                                                                                                                                                </div>
                                                                                                                                                            </div>
                                                                                                                                                        @else
                                                                                                                                                            <div class="d-flex align-items-center ms-4">
                                                                                                                                                                <i class="ri-user-3-line me-2 text-muted"></i>
                                                                                                                                                                <span class="text-muted small">No users assigned</span>
                                                                                                                                                            </div>
                                                                                                                                                        @endif
                                                                                                                                                    </div>
                                                                                                                                                @endforeach
                                                                                                                                            </div>
                                                                                                                                            <style>
                                                                                                                                                .transition-card { border-left: 4px solid #38f9d7; border-radius: 8px; }
                                                                                                                                                .transition-card .badge.bg-info { background: linear-gradient(90deg,#43e97b,#38f9d7)!important; color: #fff; }
                                                                                                                                            </style>
                                                                                                                                        </div>
                                                                                                                                    </div>
                                                                                                                                    <!-- Column 3: Flowchart -->
<div class="col-md-4">
<div class="mb-3">
 <label class="fw-bold">Flowchart:</label>
<pre id="mermaid-{{ $workflow->id }}" class="mermaid-code" style="display:none;">
graph TD;
@foreach($workflow->transitions as $transition)
    {{ Str::slug($transition->fromStep->name ?? 'Start', '_') }}["{{ $transition->fromStep->name ?? 'Start' }}"]-->|{{ $transition->name }}|{{ Str::slug($transition->toStep->name ?? 'End', '_') }}["{{ $transition->toStep->name ?? 'End' }}"];
@endforeach
                                                                                                                                            </pre>
                                                                                                                                            <div style="max-width:100%;overflow-x:auto;">
                                                                                                                                                <div id="mermaid-chart-{{ $workflow->id }}" class="mermaid" style="min-width:500px;min-height:350px;max-width:100%;"></div>
                                                                                                                                            </div>
                                                                                                                                        </div>
                                                                                                                                    </div>
                                                                                                                                </div>
                                                                                       
                                                                                            </div>
                                                            <div class="modal-footer">
                                                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                        @endforeach
                    </tbody>
                </table>
                {{ $workflows->links() }}
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/mermaid@10.6.1/dist/mermaid.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    if (window.mermaid) {
        mermaid.initialize({
            startOnLoad: false,
            theme: 'forest',
            themeVariables: {
                primaryColor: '#43e97b',
                secondaryColor: '#38f9d7',
                tertiaryColor: '#f7b32b',
                edgeLabelBackground: '#fff',
                nodeTextColor: '#222',
                fontFamily: 'Segoe UI, Arial, sans-serif',
                lineColor: '#43e97b',
                border1: '#38f9d7',
                border2: '#f7b32b',
                background: '#f8f9fa',
                clusterBkg: '#e3f2fd',
                clusterBorder: '#43e97b',
                mainBkg: '#fffbe6',
                nodeBorder: '#38f9d7',
                nodeBkg: '#fffbe6',
                nodeTextColor: '#222',
                titleColor: '#f7b32b',
                edgeColor: '#43e97b',
            }
        });
        document.querySelectorAll('.mermaid-code').forEach(function(pre) {
            var chartId = pre.id.replace('mermaid-', 'mermaid-chart-');
            var chartDiv = document.getElementById(chartId);
            if (chartDiv) {
                var graphDefinition = pre.textContent.trim();
                mermaid.render('mermaid-svg-' + chartId, graphDefinition).then(({svg}) => {
                    chartDiv.innerHTML = svg;
                });
            }
        });
    }
});
</script>
@endpush
