
@extends('admin.admin_master')

@section('admin')
<div class="page-content">
    <div class="container-fluid">
        <!-- Page Header -->
        <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-user-settings-line font-size-24"></i>
                                        </div>
                                    </div>
                                </div>
                                <div class="flex-grow-1">
                                    <h4 class="page-title mb-1">My Workflows</h4>
                                    <p class="page-subtitle text-muted mb-0">
                                        Manage and track your workflow tasks
                                    </p>
                                </div>
                            </div>
                            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#newWorkflowModal">+ New</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
                @if(session('workflow_completed'))
                <!-- Workflow Completed Modal -->
                <div class="modal fade" id="workflowCompletedModal" tabindex="-1" aria-labelledby="workflowCompletedModalLabel" aria-hidden="true">
                    <div class="modal-dialog modal-dialog-centered">
                        <div class="modal-content">
                            <div class="modal-header bg-success text-white">
                                <h5 class="modal-title" id="workflowCompletedModalLabel">Workflow Completed</h5>
                                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <div class="modal-body">
                                <p>The workflow has been successfully completed!</p>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-success" data-bs-dismiss="modal">OK</button>
                            </div>
                        </div>
                    </div>
                </div>
                <script>
                document.addEventListener('DOMContentLoaded', function() {
                    var completedModal = new bootstrap.Modal(document.getElementById('workflowCompletedModal'));
                    completedModal.show();
                });
                </script>
                @endif
        @include('workflow.partials.new-modal', ['allWorkflows' => \App\Models\Workflow::all()])
     
        <!-- Workflow Tasks Card Layout -->
        <div class="row mt-4">
            <div class="col-12">
                <div class="card shadow-sm border-0">
                    <div class="card-body p-4">
                        <h5 class="mb-3">My Workflow Tasks</h5>
                        <div class="d-flex flex-column gap-3">
                            <style>
                                .wf-task-card{border:0;border-left:4px solid #6571ff;border-radius:14px;background:#fff;overflow:hidden;transition:box-shadow .2s ease,transform .2s ease;}
                                .wf-task-card:hover{box-shadow:0 .5rem 1.5rem rgba(101,113,255,.15)!important;transform:translateY(-2px);}
                                .wf-task-head{background:linear-gradient(135deg,#f5f6ff 0%,#eef0ff 100%);}
                                .wf-step-chip{background:#fff;color:#4b57d6;font-weight:600;border-radius:20px;padding:.15rem .7rem;font-size:.72rem;border:1px solid #dfe3ff;}
                                .wf-timeline{position:relative;margin:0;padding-left:1.35rem;list-style:none;}
                                .wf-timeline:before{content:"";position:absolute;left:.45rem;top:.25rem;bottom:.25rem;width:2px;background:#e5e8ff;}
                                .wf-timeline li{position:relative;padding:0 0 .9rem .25rem;}
                                .wf-timeline li:last-child{padding-bottom:0;}
                                .wf-timeline li:before{content:"";position:absolute;left:-1.02rem;top:.25rem;width:11px;height:11px;border-radius:50%;background:#6571ff;box-shadow:0 0 0 3px #eef0ff;}
                                .wf-timeline li.wf-return:before{background:#f7684b;box-shadow:0 0 0 3px #ffe9e4;}
                                .wf-comment{background:#f8f9fc;border-left:3px solid #dfe3ff;border-radius:6px;padding:.35rem .6rem;font-size:.8rem;color:#5b6270;margin-top:.3rem;}
                                .wf-comment.wf-empty{font-style:italic;color:#b0b5c3;border-left-color:#eef0f5;}
                            </style>
                            @forelse($tasks as $task)
                                @if($task->status !== 'completed')
                                @php
                                    $currentStep = $task->step_id ? \App\Models\WorkflowStep::find($task->step_id) : null;
                                    $availableTransitions = $task->workflow
                                        ? $task->workflow->transitions->where('from_step_id', $task->step_id)
                                        : collect();
                                    $history = \App\Models\WorkflowTask::where('document_id', $task->document_id)
                                        ->where('status', 'completed')
                                        ->with(['transition.fromStep', 'transition.toStep', 'assignedUser'])
                                        ->orderBy('created_at')
                                        ->orderBy('id')
                                        ->get();
                                @endphp
                                <div class="wf-task-card card shadow-sm mb-2 w-100">
                                    <div class="wf-task-head p-3 d-flex justify-content-between align-items-start">
                                        <div>
                                            <h6 class="mb-1 fw-bold text-dark">
                                                <i class="ri-file-text-line me-1 text-primary"></i>{{ $task->document->title ?? 'Untitled document' }}
                                            </h6>
                                            <div class="text-muted small">
                                                <i class="ri-flow-chart me-1"></i>{{ $task->workflow->name ?? '-' }}
                                                @if($currentStep)<span class="wf-step-chip ms-2">Current: {{ $currentStep->name }}</span>@endif
                                            </div>
                                        </div>
                                        <span class="badge bg-primary-subtle text-primary">{{ ucfirst(str_replace('_', ' ', $task->status)) }}</span>
                                    </div>
                                    <div class="p-3">
                                        @if($task->document && $task->document->description)
                                            <p class="text-muted small mb-3">{{ $task->document->description }}</p>
                                        @endif

                                        {{-- Previous steps & their comments --}}
                                        @if($history->count())
                                            <div class="mb-3">
                                                <div class="fw-semibold small text-uppercase text-muted mb-2">
                                                    <i class="ri-history-line me-1"></i>Previous steps
                                                </div>
                                                <ul class="wf-timeline">
                                                    @foreach($history as $h)
                                                        @php
                                                            $fromOrder = optional(optional($h->transition)->fromStep)->order;
                                                            $toOrder = optional(optional($h->transition)->toStep)->order;
                                                            $isReturn = !is_null($fromOrder) && !is_null($toOrder) && $toOrder < $fromOrder;
                                                            $hu = $h->assignedUser;
                                                            $huName = $hu ? (trim(($hu->first_name ?? '') . ' ' . ($hu->last_name ?? '')) ?: ($hu->name ?? 'User')) : null;
                                                        @endphp
                                                        <li class="{{ $isReturn ? 'wf-return' : '' }}">
                                                            <div class="d-flex justify-content-between align-items-center flex-wrap">
                                                                <span class="fw-semibold small">
                                                                    {{ optional($h->transition)->name ?? 'Action' }}
                                                                    <span class="text-muted fw-normal">
                                                                        ({{ optional(optional($h->transition)->fromStep)->name ?? 'Start' }} &rarr; {{ optional(optional($h->transition)->toStep)->name ?? '-' }})
                                                                    </span>
                                                                </span>
                                                                <span class="text-muted" style="font-size:.72rem;">
                                                                    @if($huName)<i class="ri-user-line me-1"></i>{{ $huName }}@endif
                                                                    @if($h->created_at) &middot; {{ $h->created_at->format('Y-m-d H:i') }}@endif
                                                                </span>
                                                            </div>
                                                            @if(trim((string) $h->comment) !== '')
                                                                <div class="wf-comment"><i class="ri-chat-quote-line me-1"></i>{{ $h->comment }}</div>
                                                            @else
                                                                <div class="wf-comment wf-empty">No comment</div>
                                                            @endif
                                                        </li>
                                                    @endforeach
                                                </ul>
                                            </div>
                                        @endif

                                        {{-- Action form --}}
                                        @if($availableTransitions->count())
                                            <form method="POST" action="{{ route('workflow.tasks.transition', $task->id) }}">
                                                @csrf
                                                <div class="row g-2 align-items-end">
                                                    <div class="col-md-5">
                                                        <label class="form-label small fw-semibold mb-1">Choose action</label>
                                                        <select name="transition_id" class="form-select form-select-sm" required>
                                                            <option value="">-- Select an action --</option>
                                                            @foreach($availableTransitions as $tr)
                                                                <option value="{{ $tr->id }}">{{ $tr->name }} (&rarr; {{ optional($tr->toStep)->name ?? '-' }})</option>
                                                            @endforeach
                                                        </select>
                                                    </div>
                                                    <div class="col-md-7">
                                                        <label class="form-label small fw-semibold mb-1">Comment <span class="text-muted fw-normal">(optional)</span></label>
                                                        <textarea name="comment" class="form-control form-control-sm" rows="1" placeholder="Add a comment (optional)"></textarea>
                                                    </div>
                                                </div>
                                                <div class="d-flex gap-2 mt-3">
                                                    <button type="submit" class="btn btn-primary btn-sm px-3"><i class="ri-send-plane-line me-1"></i>Submit</button>
                                                    <a href="{{ url('workflow/tasks/' . $task->id) }}" class="btn btn-outline-secondary btn-sm">View Details</a>
                                                </div>
                                            </form>
                                        @else
                                            <div class="alert alert-warning py-2 px-3 small mb-0">No actions available from the current step.</div>
                                        @endif
                                    </div>
                                </div>
                                @endif
                            @empty
                                <div class="card p-4 text-center w-100 text-muted">
                                    <i class="ri-inbox-line d-block mb-2" style="font-size:1.6rem;"></i>No workflow tasks assigned to you.
                                </div>
                            @endforelse
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- Documents and Their Tasks for Workflows I Created Table (Redesigned) -->
        <div class="card mt-4">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Workflows I Created</h5>
            </div>
            <div class="card-body">
                <table class="table table-hover align-middle">
                    <thead class="table-light">
                        <tr>
                            <th>Document Title</th>
                            <th>Workflow</th>
                            <th>Created At</th>
                            <th>View</th>
                            <th>Tasks</th>
                        </tr>
                    </thead>
                    <tbody>
                        @php
                            $createdWorkflowIds = \App\Models\Workflow::where('created_by', auth()->id())->pluck('id');
                            $documents = \App\Models\Document::whereIn('workflow_id', $createdWorkflowIds)
                                ->with(['workflow', 'tasks.assignedUser', 'tasks.assignedRole', 'tasks.transition.fromStep', 'tasks.transition.toStep'])
                                ->orderByDesc('created_at')->get();
                        @endphp
                        @forelse($documents as $doc)
                        <tr>
                            <td>
                                <div class="fw-bold">{{ $doc->title }}</div>
                                <div class="text-muted small">{{ $doc->description }}</div>
                            </td>
                            <td>{{ $doc->workflow ? $doc->workflow->name : '-' }}</td>
                            <td>{{ $doc->created_at ? $doc->created_at->format('Y-m-d H:i') : '-' }}</td>
                            <td>
                                @if($doc->file_path)
                                    <a href="{{ route('workflow.documents.file', $doc->id) }}" target="_blank" class="btn btn-outline-primary btn-sm">View</a>
                                @else
                                    <span class="text-muted">No file</span>
                                @endif
                            </td>
                            <td>
                                @if($doc->tasks && $doc->tasks->count())
                                    <button class="btn btn-outline-secondary btn-sm" type="button" data-bs-toggle="modal" data-bs-target="#tasksModal{{ $doc->id }}">
                                       Task
                                    </button>
                                    <!-- Modal for tasks -->
                                    <div class="modal fade" id="tasksModal{{ $doc->id }}" tabindex="-1" aria-labelledby="tasksModalLabel{{ $doc->id }}" aria-hidden="true">
                                        <div class="modal-dialog modal-lg">
                                            <div class="modal-content">
                                                <div class="modal-header bg-primary text-white d-flex justify-content-between align-items-center">
                                                    <h5 class="modal-title mb-0 text-white" id="tasksModalLabel{{ $doc->id }}">Tasks for: {{ $doc->title }}</h5>
                                                    <button type="button" class="btn-close btn-close-white ms-auto" data-bs-dismiss="modal" aria-label="Close"></button>
                                                </div>
                                                <div class="modal-body">
                                                    <ul class="list-group">
                                                        @foreach($doc->tasks as $task)
                                                        <li class="list-group-item">
                                                            <div class="d-flex justify-content-between align-items-center">
                                                                <div>
                                                                    <strong>Task #{{ $task->id }}</strong> -
                                                                    <span class="badge bg-{{ $task->status === 'completed' ? 'success' : ($task->status === 'in_progress' ? 'primary' : 'secondary') }}">{{ ucfirst($task->status) }}</span>
                                                                </div>
                                                                <div class="text-muted small">
                                                                    Assigned User: 
                                                                    @if($task->assignedUser)
                                                                        {{ $task->assignedUser->first_name ?? '' }} {{ $task->assignedUser->last_name ?? '' }}
                                                                        @if(empty($task->assignedUser->first_name) && empty($task->assignedUser->last_name))
                                                                            {{ $task->assignedUser->name }}
                                                                        @endif
                                                                    @else
                                                                        <span class="text-muted"></span>
                                                                    @endif |
                                                                    Assigned Role: {{ $task->assignedRole ? $task->assignedRole->name : '-' }}
                                                                </div>
                                                            </div>
                                                            <div class="mt-1">
                                                                @if($task->transition)
                                                                    <span class="text-muted">Transition: {{ $task->transition->name }} ({{ $task->transition->fromStep ? $task->transition->fromStep->name : 'Start' }} → {{ $task->transition->toStep ? $task->transition->toStep->name : '-' }})</span>
                                                                    @if($task->transition->is_end && $task->status !== 'completed')
                                                                        <!-- Show last transition action button if not completed -->
                                                                        <form method="POST" action="{{ route('workflow.tasks.transition', $task->id) }}" class="d-inline">
                                                                            @csrf
                                                                            <input type="hidden" name="transition_id" value="{{ $task->transition->id }}">
                                                                            <input type="hidden" name="comment" value="Final transition action">
                                                                            <button type="submit" class="btn btn-success btn-sm mt-1">Complete Workflow</button>
                                                                        </form>
                                                                    @elseif($task->transition->is_end && $task->status === 'completed')
                                                                        <span class="badge bg-success ms-2">Workflow Complete</span>
                                                                    @endif
                                                                @else
                                                                    <span class="text-muted">No transition info</span>
                                                                @endif
                                                            </div>
                                                        </li>
                                                        @endforeach
                                                    </ul>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                @else
                                    <span class="text-muted">No tasks</span>
                                @endif
                            </td>

                        @empty
                        <tr>
                            <td colspan="5" class="text-center">No documents found for workflows you created.</td>
                        </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
<!-- View Document Modal -->
<div class="modal fade" id="viewDocumentModal" tabindex="-1" aria-labelledby="viewDocumentModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="viewDocumentModalLabel">Document Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <h6 id="docTitle"></h6>
                <p id="docDescription"></p>
                <div id="docPreview"></div>
                   <a id="docLink" href="#" target="_blank" ></a>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    var viewDocumentModal = document.getElementById('viewDocumentModal');
    viewDocumentModal.addEventListener('show.bs.modal', function (event) {
        var button = event.relatedTarget;
        var title = button.getAttribute('data-title');
        var description = button.getAttribute('data-description');
        var link = button.getAttribute('data-link');
        var filePath = button.getAttribute('data-filepath');
        document.getElementById('docTitle').textContent = title;
        document.getElementById('docDescription').textContent = description;
        document.getElementById('docLink').href = link;
        var preview = '';
        if (filePath) {
            var ext = filePath.split('.').pop().toLowerCase();
            if (['pdf'].includes(ext)) {
                preview = '<iframe src=\"' + filePath + '\" width=\"100%\" height=\"400px\"></iframe>';
            } else if (['jpg','jpeg','png','gif','bmp','webp'].includes(ext)) {
                preview = '<img src=\"' + filePath + '\" alt=\"Document Image\" style=\"max-width:100%;max-height:400px;\" />';
            } else {
                preview = '<a href=\"' + filePath + '\" target=\"_blank\">Download File</a>';
            }
        }
        document.getElementById('docPreview').innerHTML = preview;
    });
});
</script>
@endsection
