@extends('layouts.app')
@section('title', $definition['title'])
@section('content')
<main class="nxl-container"><div class="nxl-content"><div class="page-header"><h5>{{ $definition['title'] }}</h5></div><div class="main-content">
@if(session('success'))<div class="alert alert-success">{{ session('success') }}</div>@endif
@if($errors->any())<div class="alert alert-danger">{{ $errors->first() }}</div>@endif

@php
 $topFilters = [
  'date_from'=>['label'=>'Created from','type'=>'date'],
  'date_to'=>['label'=>'Created to','type'=>'date'],
 ];
 foreach($definition['fields'] as $filterName => $filterField) {
  if(($filterField['type'] ?? null) === 'select' && in_array($filterName, ['status','type','priority','visibility','related_type','target_audience'], true)) {
   $topFilters[$filterName] = ['label'=>$filterField['label'], 'options'=>collect($filterField['options'])->mapWithKeys(fn($value)=>[$value=>ucwords(str_replace('_',' ',$value))])->all()];
  }
 }
@endphp
<div class="card mb-4" id="workflowTopFilters">
 <div class="card-header"><strong>{{ $definition['title'] }} Filters</strong></div>
 <x-server-list-toolbar form-id="workflowFilters" apply-label="Apply Filters" reset-label="Reset Filters"
    actions-class="w-100 justify-content-center" placeholder="Search {{ strtolower($definition['title']) }}"
    :filters="$topFilters" />
</div>
@if(request('related_type') && request('related_id'))<div class="alert alert-info py-2 d-flex justify-content-between align-items-center"><span>Showing records linked to <strong>{{ ucwords(request('related_type')) }} #{{ request('related_id') }}</strong>.</span><a class="btn btn-sm btn-outline-secondary" href="{{ route('workflow.index',$module) }}">Clear related record</a></div>@endif

@if($module === 'trade-documents')
<div class="row g-3 mb-4">
 <div class="col-lg-7"><div class="card h-100 mb-0"><div class="card-header">Sequential Numbering</div><div class="card-body">
  <form method="POST" action="{{ route('trade-documents.configure') }}" class="row g-2">@csrf
   <div class="col"><select class="form-select" name="type">@foreach(['proposal','quotation','invoice'] as $type)<option>{{ $type }}</option>@endforeach</select></div>
   <div class="col"><input class="form-control" name="prefix" value="DOC" placeholder="Prefix"></div><div class="col"><input class="form-control" type="number" name="next_number" value="1"></div>
   <div class="col"><input class="form-control" type="number" name="padding" value="5"></div><div class="col"><input class="form-control" name="separator" value="-"></div><div class="col-auto"><button class="btn btn-primary">Save</button></div>
  </form><small class="text-muted">@foreach($numberSettings as $s) {{ ucfirst($s->type) }}: {{ $s->prefix.$s->separator.str_pad($s->next_number,$s->padding,'0',STR_PAD_LEFT) }} @endforeach</small>
 </div></div></div>
 <div class="col-lg-5"><div class="card h-100 mb-0"><div class="card-header">Branded Template</div><div class="card-body">
  <form method="POST" action="{{ route('trade-documents.templates.store') }}" class="row g-2">@csrf
   <div class="col-6"><input class="form-control" name="name" placeholder="Template name" required></div><div class="col-3"><select class="form-select" name="type">@foreach(['all','proposal','quotation','invoice'] as $type)<option>{{ $type }}</option>@endforeach</select></div><div class="col-3"><input class="form-control form-control-color" type="color" name="accent_color" value="#3454d1"></div>
   <div class="col-6"><input class="form-control" name="header_text" placeholder="Header"></div><div class="col-6"><input class="form-control" name="footer_text" placeholder="Footer"></div><div class="col"><label><input type="checkbox" name="is_default" value="1"> Default</label></div><div class="col-auto"><button class="btn btn-primary">Create</button></div>
  </form>
 </div></div></div>
 <div class="col-12"><form method="POST" action="{{ route('trade-documents.sync-legacy') }}">@csrf<button class="btn btn-outline-secondary">Unify Legacy Transactions</button></form></div>
</div>
@endif

<div class="card mb-4"><div class="card-header">Create {{ rtrim($definition['title'],'s') }}</div><div class="card-body">
<form method="POST" enctype="multipart/form-data" action="{{ route('workflow.store',$module) }}" class="row g-3">@csrf
@foreach($definition['fields'] as $name=>$field)<div class="col-md-6"><label class="form-label">{{ $field['label'] }}</label>
 @if($module==='notes' && $name==='owner_id')<select name="owner_id" class="form-select" required><option value="">Select owner</option>@foreach($users as $user)<option value="{{ $user->id }}" @selected((string)old('owner_id',auth()->id())===(string)$user->id)>{{ $user->name }} ({{ $user->email }})</option>@endforeach</select>
 @elseif($module==='trade-documents' && in_array($name,['deal_id','account_id','contact_id','salesperson_id'],true))<select name="{{ $name }}" class="form-select crm-remote-lookup" data-lookup-type="{{ ['deal_id'=>'deal','account_id'=>'account','contact_id'=>'contact','salesperson_id'=>'user'][$name] }}"><option value="">Search {{ ucwords(str_replace('_id','',$name)) }}</option></select>
 @elseif($module==='follow-ups' && $name==='previous_activity_id')<select name="previous_activity_id" class="form-select crm-remote-lookup" data-lookup-type="activity"><option value="">Search previous call, meeting, or email</option></select>
 @elseif(($field['type']??null)==='select')<select name="{{ $name }}" class="form-select"><option value="">Select</option>@foreach($field['options'] as $option)<option value="{{ $option }}" @selected((string) old($name, request($name)) === (string) $option)>{{ ucwords(str_replace('_',' ',$option)) }}</option>@endforeach</select>
 @elseif($name==='related_id' && isset($relatedRecords))<input type="search" class="form-control mb-2 related-record-search" placeholder="Search the selected module" autocomplete="off"><select name="{{ $name }}" class="form-select related-record-select" data-selected="{{ old('related_id', request('related_id')) }}"><option value="">Select related record</option></select><small class="text-muted">Search by name, title, number, or record ID.</small>
 @elseif(($field['type']??null)==='textarea')<textarea name="{{ $name }}" class="form-control">{{ old($name) }}</textarea>
@else<input name="{{ $name }}" type="{{ $field['type']??'text' }}" value="{{ old($name, request($name)) }}" class="form-control">@endif
</div>@endforeach
@if(in_array($module,['messages','notes','follow-ups','todos']))
<div class="col-12"><label class="form-label">Assigned Employees</label>
<select name="assignee_ids[]" class="form-select" multiple size="4" @if(in_array($module,['follow-ups','todos'])) required @endif>@foreach($users as $user)<option value="{{ $user->id }}">{{ $user->name }} ({{ $user->email }})</option>@endforeach</select>
 <small class="text-muted">Hold Ctrl (Windows) or Command (Mac) to select multiple employees.</small>
</div>
@endif
@if(in_array($module,['messages','notes','follow-ups','todos']))<div class="col-md-6"><label class="form-label">Attachment</label><input class="form-control" type="file" name="attachment" accept=".pdf,.png,.jpg,.jpeg,.webp,.doc,.docx,.xls,.xlsx,.csv,.txt"></div>@endif
@if($module==='trade-documents')<div class="col-md-6"><label class="form-label">Branded Template</label><select name="template_id" class="form-select"><option value="">Default</option>@foreach($templates as $t)<option value="{{ $t->id }}">{{ $t->name }}</option>@endforeach</select></div><div class="col-md-6"><label class="form-label">Customer Email</label><input name="customer_email" type="email" class="form-control"></div>@endif
<div class="col-12"><button class="btn btn-primary">Save</button></div></form></div></div>

@if($module==='messages' && $records->count())
<div class="card mb-4"><div class="card-header">Conversation Workspace</div><div class="card-body">
 <div class="row g-0 border rounded overflow-hidden" style="min-height:520px">
  <aside class="col-lg-3 border-end bg-light p-2">
   <form method="GET" action="{{ route('workflow.index','messages') }}" class="mb-2">
    <input class="form-control form-control-sm" name="conversation_search" value="{{ request('conversation_search') }}" placeholder="Search all conversations">
   </form>
   <div class="list-group list-group-flush conversation-list">@foreach($conversations as $thread)
    <a class="list-group-item list-group-item-action {{ request('conversation',$conversations->first()?->thread_key)===$thread->thread_key?'active':'' }}"
       href="{{ route('workflow.index',['messages','conversation'=>$thread->thread_key]) }}">
       <strong class="d-block text-truncate">{{ $thread->thread_key }}</strong><small>{{ $thread->message_count }} messages · {{ \Carbon\Carbon::parse($thread->latest_at)->diffForHumans() }}</small>
    </a>@endforeach</div>
   <div class="mt-2">{{ $conversations->links() }}</div>
  </aside>
  <section class="col-lg-9 p-3">
   <div class="overflow-auto pe-2" style="max-height:420px">@forelse($conversationMessages as $message)
    <a href="{{ route('workflow.index',['messages','conversation'=>$message->conversation_id ?: 'message-'.$message->id,'message_id'=>$message->id]) }}" class="text-reset text-decoration-none">
     <div class="rounded p-3 mb-2 {{ $message->from_address===auth()->user()->email?'bg-soft-primary ms-lg-5':'bg-light me-lg-5' }}">
      <div>{{ $message->content }}</div><small class="text-muted">{{ strtoupper($message->type) }} · {{ ucfirst($message->status) }} · {{ $message->created_at->format('M d, Y H:i') }} · {{ $message->files->count() }} file(s)</small>
     </div>
    </a>@empty<div class="text-muted">Select a conversation.</div>@endforelse</div>
   @if($selectedMessage)<hr><x-crm-file-manager module="messages" :record="$selectedMessage" />@endif
   <h6 class="mt-4">Provider delivery history</h6><div class="table-responsive"><table class="table table-sm"><thead><tr><th>Provider</th><th>Operation</th><th>Status</th><th>Attempt</th><th>Date</th></tr></thead><tbody>
    @forelse($providerHistory as $log)<tr><td>{{ ucfirst($log->provider) }}</td><td>{{ $log->operation }}</td><td>{{ ucfirst($log->status) }}</td><td>{{ $log->attempts }}/{{ $log->max_attempts }}</td><td>{{ $log->created_at }}</td></tr>
    @empty<tr><td colspan="5" class="text-muted">No provider events recorded for this conversation.</td></tr>@endforelse
   </tbody></table></div>
  </section>
 </div>
</div></div>
@endif

@if(false && $module==='messages' && $records->count())
<div class="card mb-4"><div class="card-header">Conversation View</div><div class="card-body">
 @foreach($records->groupBy(fn($message)=>$message->conversation_id ?: 'message-'.$message->id) as $conversation=>$messages)
 <div class="border rounded p-3 mb-3"><strong>{{ $conversation }}</strong>
  @foreach($messages->sortBy('created_at') as $message)
   <div class="mt-2 ps-3 border-start"><div>{{ $message->content }}</div><small class="text-muted">{{ strtoupper($message->type) }} · {{ ucfirst($message->status) }} · {{ $message->created_at->format('M d, Y H:i') }}</small></div>
  @endforeach
 </div>
 @endforeach
</div></div>
@endif

<div class="card"><div class="card-header d-flex justify-content-between"><span>{{ request('deleted')?'Deleted':'Current' }} Records</span><a class="btn btn-sm btn-light" href="{{ route('workflow.index',[$module,'deleted'=>request('deleted')?null:1]) }}">{{ request('deleted')?'Show Current':'Show Deleted' }}</a></div><div class="card-body">
@forelse($records as $record)
<div class="border rounded p-3 mb-3">
 <div class="d-flex justify-content-between"><strong>#{{ $record->id }} {{ $record->document_number ?? $record->name ?? $record->title ?? '' }}</strong><span>{{ ucfirst(str_replace('_',' ',$record->status??'')) }}</span></div>
 <div class="row small text-muted mt-2">@foreach($definition['fields'] as $name=>$field)<div class="col-md-3 mb-1"><strong>{{ $field['label'] }}:</strong> {{ is_array($record->{$name})?json_encode($record->{$name}):$record->{$name} }}</div>@endforeach</div>
 @if(in_array($module,['messages','notes','follow-ups','todos']))
 <div class="small mb-2"><strong>Assigned:</strong> {{ $record->assignments->pluck('user.name')->filter()->join(', ') ?: 'Unassigned' }}</div>
   @if(($assignmentHistories[$record->id] ?? collect())->isNotEmpty())<div class="small text-muted mb-2"><strong>Assignment history:</strong> @foreach($assignmentHistories[$record->id]->take(4) as $history)<span class="me-2">{{ ucfirst($history->action) }} {{ $history->user?->name }} by {{ $history->actor?->name }} ({{ $history->created_at->format('M d H:i') }})</span>@endforeach</div>@endif
   @if($module==='notes' && $record->attachment_path)<a class="btn btn-sm btn-outline-primary mb-2" target="_blank" href="{{ asset('storage/'.$record->attachment_path) }}">Open note attachment</a>@endif
   @endif
  @if($module==='todos' && !$record->trashed())
  <form method="POST" action="{{ route('workflow.todos.comments.update',$record) }}" class="mt-2">
   @csrf @method('PUT')
   <label class="form-label small mb-1" for="todo-comments-{{ $record->id }}">Comments</label>
   <div class="input-group"><textarea id="todo-comments-{{ $record->id }}" name="comments" class="form-control form-control-sm" rows="2" placeholder="Operational updates">{{ old('comments',$record->comments) }}</textarea><button class="btn btn-sm btn-outline-primary" type="submit">Save comments</button></div>
  </form>
  @endif
  @if($record->trashed())<form method="POST" action="{{ route('workflow.restore',[$module,$record->id]) }}">@csrf<button class="btn btn-sm btn-success">Restore</button></form>
 @elseif($module!=='trade-documents')<div class="d-flex gap-2">
  <form method="POST" action="{{ route('workflow.destroy',[$module,$record->id]) }}">@csrf @method('DELETE')<button class="btn btn-sm btn-danger">Delete</button></form>
  @if(in_array($module,['messages','notes','follow-ups','todos','surveys']))
   <button class="btn btn-sm btn-outline-secondary" type="button" data-bs-toggle="collapse" data-bs-target="#files-{{ $module }}-{{ $record->id }}">Files & Attachments</button>
  @endif
 </div>
 @if(in_array($module,['messages','notes','follow-ups','todos','surveys']))
  <div class="collapse mt-3" id="files-{{ $module }}-{{ $record->id }}"><x-crm-file-manager :module="$module" :record="$record" /></div>
 @endif
 @else
 <div class="row g-2 mt-2"><div class="col-lg-7"><form method="POST" action="{{ route('trade-documents.lines.store',$record) }}" class="row g-2">@csrf
  <div class="col-3"><select class="form-select form-select-sm product-selector crm-remote-lookup" data-lookup-type="product" name="product_id"><option value="">Custom line</option></select></div>
  <div class="col"><input class="form-control form-control-sm line-description" name="description" placeholder="Description" required></div><div class="col-2"><input class="form-control form-control-sm" name="quantity" type="number" step=".001" value="1"></div><div class="col-2"><input class="form-control form-control-sm line-price" name="unit_price" type="number" step=".01" placeholder="Price"></div><div class="col-auto"><button class="btn btn-sm btn-primary">Add</button></div>
 </form></div><div class="col-lg-5"><form method="POST" action="{{ route('trade-documents.transition',$record) }}" class="d-flex gap-2">@csrf<input name="note" class="form-control form-control-sm" placeholder="Required rejection note"><select name="status" class="form-select form-select-sm"><option value="">Status</option>@foreach(['pending_approval','approved','rejected','sent','accepted','paid','cancelled'] as $status)<option value="{{ $status }}">{{ ucwords(str_replace('_',' ',$status)) }}</option>@endforeach</select><button class="btn btn-sm btn-primary">Apply</button></form></div></div>
 <div class="d-flex flex-wrap gap-2 mt-2">
  @if(in_array($record->type,['proposal','quotation']))<form method="POST" action="{{ route('trade-documents.convert',$record) }}">@csrf<input type="hidden" name="type" value="{{ $record->type==='proposal'?'quotation':'invoice' }}"><button class="btn btn-sm btn-outline-primary">Convert</button></form>@endif
  <form method="POST" action="{{ route('trade-documents.share',$record) }}">@csrf<button class="btn btn-sm btn-outline-secondary">Share</button></form><a class="btn btn-sm btn-outline-danger" href="{{ route('trade-documents.pdf',$record) }}">Branded PDF</a><a class="btn btn-sm btn-outline-primary" href="{{ route('trade-documents.word',$record) }}">DOCX</a><a class="btn btn-sm btn-outline-success" href="{{ route('trade-documents.csv',$record) }}">CSV</a>
 </div>
 <div class="row g-2 mt-2"><div class="col-md-6"><form method="POST" action="{{ route('trade-documents.email',$record) }}" class="d-flex gap-2">@csrf<input type="email" name="recipient" value="{{ $record->customer_email }}" class="form-control form-control-sm" placeholder="Customer email" required><input name="message" class="form-control form-control-sm" placeholder="Message"><button class="btn btn-sm btn-primary">Email PDF</button></form></div>
 @if($record->type==='invoice')<div class="col-md-6"><form method="POST" enctype="multipart/form-data" action="{{ route('trade-documents.payments.store',$record) }}" class="d-flex gap-2">@csrf<input type="number" step=".01" name="amount" class="form-control form-control-sm" placeholder="Installment" required><input name="payer_name" class="form-control form-control-sm" placeholder="Payer" required><input name="method" class="form-control form-control-sm" placeholder="Method" required><input name="reference" class="form-control form-control-sm" placeholder="Reference" required><input name="payer_account_reference" class="form-control form-control-sm" placeholder="Payer account"><input type="file" name="proof" class="form-control form-control-sm" accept="image/*,.pdf"><input type="datetime-local" name="paid_at" value="{{ now()->format('Y-m-d\\TH:i') }}" class="form-control form-control-sm" required><button class="btn btn-sm btn-success">Record</button></form></div>@endif</div>
 <small class="text-muted">{{ $record->lines->count() }} lines · {{ $record->currency }} {{ number_format($record->total,2) }} · Net Paid {{ number_format($record->paid_amount,2) }}</small>
 @if($record->type==='invoice')<a class="btn btn-sm btn-outline-success ms-2" href="{{ route('trade-documents.payments.index',$record) }}">Complete Payment History</a>@endif
 @if($record->rejection_reason)<div class="alert alert-danger py-1 mt-2">Rejected: {{ $record->rejection_reason }} · Resubmissions: {{ $record->resubmission_count }}</div>@endif
 <div class="small text-muted">@foreach($record->approvalHistories->take(-5) as $h)<span class="me-3">{{ $h->created_at->format('M d H:i') }} {{ ucwords(str_replace('_',' ',$h->action)) }} by {{ $h->user?->name ?: 'Customer' }}</span>@endforeach</div>
 @endif
</div>
@empty<div class="text-center text-muted">No records found.</div>@endforelse
<div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mt-3 pt-3 border-top">
 <small class="text-muted">Showing {{ $records->firstItem() ?? 0 }}–{{ $records->lastItem() ?? 0 }} of {{ $records->total() }} {{ strtolower($definition['title']) }}</small>
 @if($records->hasPages()){{ $records->links() }}@else<nav aria-label="{{ $definition['title'] }} pagination"><ul class="pagination pagination-sm mb-0"><li class="page-item disabled"><span class="page-link">‹</span></li><li class="page-item active"><span class="page-link">1</span></li><li class="page-item disabled"><span class="page-link">›</span></li></ul></nav>@endif
</div></div></div>
</div></div></main>
@endsection
@push('scripts')<script>
const relatedEndpoint=@json(route('workflow.related-records'));
const loadRelatedRecords=(form,search='')=>{
 const type=form.querySelector('[name="related_type"]')?.value,select=form.querySelector('.related-record-select');
 if(!type||!select){if(select)select.innerHTML='<option value="">Select related record</option>';return;}
 const selected=select.dataset.selected||'',params=new URLSearchParams({type,q:search});
 if(selected&&!search)params.set('selected_id',selected);
 fetch(`${relatedEndpoint}?${params}`,{headers:{Accept:'application/json'}}).then(response=>response.ok?response.json():Promise.reject()).then(items=>{
  const current=select.value||selected;
  select.innerHTML='<option value="">Select related record</option>';
  items.forEach(item=>select.add(new Option(`${item.text} (#${item.id})`,item.id,false,String(item.id)===String(current))));
  select.dataset.selected='';
 }).catch(()=>{select.innerHTML='<option value="">Unable to load records</option>';});
};
document.addEventListener('change',e=>{
 if(e.target.classList.contains('product-selector')){const o=e.target.selectedOptions[0],f=e.target.closest('form'),remote=window.jQuery?jQuery(e.target).select2('data')[0]:null,name=o?.dataset.name||remote?.text,price=o?.dataset.price||remote?.price;if(name)f.querySelector('.line-description').value=name;if(price!==undefined&&price!==null)f.querySelector('.line-price').value=price;}
 if(e.target.name==='related_type'){const form=e.target.closest('form'),select=form?.querySelector('.related-record-select');if(select)select.dataset.selected='';loadRelatedRecords(form);}
});
let relatedTimer;
document.addEventListener('input',e=>{
 if(e.target.classList.contains('related-record-search')){
  clearTimeout(relatedTimer);
  relatedTimer=setTimeout(()=>loadRelatedRecords(e.target.closest('form'),e.target.value.trim()),250);
 }
});
document.querySelectorAll('.related-record-select').forEach(select=>loadRelatedRecords(select.closest('form')));
</script>@endpush
