@extends('layouts.app')
@section('title', $cfg['singular'].' — '.$record->display_name)
@section('crumbs', '<a href="'.crud_url($key,'index').'">'.$cfg['title'].'</a> · <b>'.$record->display_name.'</b>')
@section('content')
@php $st = $record->status ?? null; @endphp
<div class="card">
  <div class="card-h"><h2>{{ $cfg['singular'] }}: {{ $record->display_name }}</h2>
    @if($st)<span class="bdg b-{{ statusClass($st) }}">{{ $st }}</span>@endif
    <div class="sp no-print">
      <a class="btn btn-sm btn-ghost" href="{{ crud_url($key,'index') }}">← Back</a>
      @if(Route::has($key.'.print'))<a class="btn btn-sm btn-ghost" href="{{ route($key.'.print',$record->id) }}" target="_blank">🖨 Print</a> <a class="btn btn-sm btn-ghost" href="{{ route($key.'.print',$record->id) }}?pdf=1">📄 PDF</a>@endif
      @if(perm($cfg['perm'].'.edit') && empty($cfg['no_edit']) && ($editUrl = crud_route($key,'edit',$record->id)))<a class="btn btn-sm" href="{{ $editUrl }}">Edit</a>@endif
      @foreach(($cfg['transitions'] ?? []) as $tkey => $t)
        @if(perm($cfg['perm'].'.approve') && $st && in_array($st,$t['from']))
        <form method="POST" action="{{ route('crud.transition',['key'=>$key,'id'=>$record->id,'action'=>$tkey]) }}" data-confirm="Set status to {{ $t['to'] }}?" style="display:inline">@csrf<button class="btn btn-sm {{ ($t['class']??'')==='ok'?'btn-ok':((($t['class']??'')==='danger'?'btn-danger':'btn-info')) }}">{{ $t['label'] }}</button></form>
        @endif
      @endforeach
      {{-- ── document workflow actions ── --}}
      @if($key==='production-entries' && $st==='draft' && perm('production.approve'))
        <form method="POST" action="{{ route('production-entries.approve',$record->id) }}" data-confirm="Approve & post {{ $record->produced_tonnes }}t to stockpile?" style="display:inline">@csrf<button class="btn btn-sm btn-ok">✓ Approve & post</button></form>
      @endif
      @if($key==='stock-adjustments' && $st==='draft' && perm('inventory.approve'))
        <form method="POST" action="{{ route('stock-adjustments.post',$record->id) }}" data-confirm="Post adjustment to stock ledger?" style="display:inline">@csrf<button class="btn btn-sm btn-ok">✓ Post to ledger</button></form>
      @endif
      @if($key==='maintenance-work-orders')
        @if($st==='open' && perm('fleet.edit'))<form method="POST" action="{{ route('maintenance-work-orders.start',$record->id) }}" style="display:inline">@csrf<button class="btn btn-sm btn-warn">▶ Start work</button></form>@endif
        @if($st==='completed' && perm('fleet.approve'))<form method="POST" action="{{ route('maintenance-work-orders.close',$record->id) }}" style="display:inline">@csrf<button class="btn btn-sm btn-ok">✓ Close</button></form>@endif
      @endif
      @if($key==='weighbridge-tickets' && $st==='open' && perm('sales.edit'))<a class="btn btn-sm btn-warn" href="{{ route('weighbridge-tickets.close-form',$record->id) }}">⚖ Capture 2nd weight</a>@endif
      @if($key==='quotations')
        @if($st==='draft' && perm('sales.edit'))<form method="POST" action="{{ route('quotations.send',$record->id) }}" style="display:inline">@csrf<button class="btn btn-sm btn-info">✉ Send for approval</button></form>@endif
        @if(in_array($st,['approved','sent']) && perm('sales.create'))<form method="POST" action="{{ route('quotations.convert',$record->id) }}" data-confirm="Convert to sales order?" style="display:inline">@csrf<button class="btn btn-sm btn-ok">→ Convert to order</button></form>@endif
      @endif
      @if($key==='sales-orders')
        @if(in_array($st,['confirmed','partially-dispatched']) && perm('sales.create'))<a class="btn btn-sm btn-ok" href="{{ route('delivery-notes.create',['from_order'=>$record->id]) }}">🚛 Dispatch</a>@endif
        @if(in_array($st,['confirmed','partially-dispatched','dispatched']) && perm('sales.create'))<a class="btn btn-sm btn-info" href="{{ route('sales-invoices.create',['from_order'=>$record->id]) }}">🧾 Invoice</a>@endif
        @if($st==='confirmed' && perm('sales.edit'))<form method="POST" action="{{ route('sales-orders.cancel',$record->id) }}" data-confirm="Cancel this order?" style="display:inline">@csrf<button class="btn btn-sm btn-danger">Cancel</button></form>@endif
      @endif
      @if($key==='delivery-notes' && $st==='dispatched' && perm('sales.create'))<a class="btn btn-sm btn-info" href="{{ route('delivery-notes.invoice',$record->id) }}">🧾 Create invoice</a>@endif
      @if($key==='sales-invoices')
        @if($st==='draft' && perm('sales.approve'))<form method="POST" action="{{ route('sales-invoices.post',$record->id) }}" data-confirm="Post invoice to ledger (AR + VAT)?" style="display:inline">@csrf<button class="btn btn-sm btn-ok">✓ Post to ledger</button></form>@endif
        @if(($record->balance_due ?? 0) > 0 && $st!=='draft' && perm('sales.create'))<a class="btn btn-sm btn-pri" href="{{ route('customer-payments.create',['invoice_id'=>$record->id]) }}">💰 Receive payment</a>@endif
      @endif
      @if($key==='sales-credit-notes' && $st==='draft' && perm('sales.approve'))<form method="POST" action="{{ route('sales-credit-notes.approve',$record->id) }}" data-confirm="Apply credit note?" style="display:inline">@csrf<button class="btn btn-sm btn-ok">✓ Approve & apply</button></form>@endif
      @if($key==='purchase-requisitions' && $st==='approved' && perm('purchase.create'))<form method="POST" action="{{ route('purchase-requisitions.convert',$record->id) }}" style="display:inline">@csrf<button class="btn btn-sm btn-ok">→ Convert to LPO</button></form>@endif
      @if($key==='purchase-orders')
        @if($st==='draft' && perm('purchase.edit'))<form method="POST" action="{{ route('purchase-orders.submit',$record->id) }}" style="display:inline">@csrf<button class="btn btn-sm btn-info">✉ Submit for approval</button></form>@endif
        @if(in_array($st,['sent','partially-received']) && perm('purchase.create'))<a class="btn btn-sm btn-ok" href="{{ route('purchase-orders.receive',$record->id) }}">📦 Receive (GRN)</a>@endif
      @endif
      @if($key==='goods-receipts')
        @if($st==='draft' && perm('purchase.approve'))<form method="POST" action="{{ route('goods-receipts.post',$record->id) }}" data-confirm="Post GRN to stock?" style="display:inline">@csrf<button class="btn btn-sm btn-ok">✓ Post to stock</button></form>@endif
        @if($st==='posted' && perm('purchase.create'))<a class="btn btn-sm btn-info" href="{{ route('goods-receipts.bill',$record->id) }}">🧾 Create bill</a>@endif
      @endif
      @if($key==='purchase-invoices')
        @if($st==='draft' && perm('purchase.approve'))<form method="POST" action="{{ route('purchase-invoices.post',$record->id) }}" data-confirm="Post bill to ledger (AP + WHT)?" style="display:inline">@csrf<button class="btn btn-sm btn-ok">✓ Post to ledger</button></form>@endif
        @if(($record->balance_due ?? 0) > 0 && $st!=='draft' && perm('purchase.create'))<a class="btn btn-sm btn-pri" href="{{ route('supplier-payments.create',['invoice_id'=>$record->id]) }}">💰 Pay supplier</a>@endif
      @endif
      @if($key==='journals')
        @if($st==='draft' && perm('finance.approve'))<form method="POST" action="{{ route('journals.post',$record->id) }}" data-confirm="Post journal to GL?" style="display:inline">@csrf<button class="btn btn-sm btn-ok">✓ Post to GL</button></form>@endif
        @if($st==='posted' && perm('finance.approve'))<form method="POST" action="{{ route('journals.reverse',$record->id) }}" data-confirm="Post a reversing journal?" style="display:inline">@csrf<button class="btn btn-sm btn-warn">↩ Reverse</button></form>@endif
      @endif
      @if($key==='bank-transactions' && !$record->reconciled && perm('finance.edit'))<form method="POST" action="{{ route('bank-transactions.reconcile',$record->id) }}" style="display:inline">@csrf<button class="btn btn-sm btn-ok">✓ Reconcile</button></form>@endif
      @if(perm($cfg['perm'].'.delete') && empty($cfg['no_delete']) && ($delUrl = crud_route($key,'destroy',$record->id)))
      <form method="POST" action="{{ $delUrl }}" data-confirm="Delete this record?" style="display:inline">@csrf @method('DELETE')<button class="btn btn-sm btn-danger">Delete</button></form>
      @endif
    </div>
  </div>
  <div class="card-b">
    @if($pendingApproval)
    <div class="flash warn">⏳ Awaiting approval — requested by {{ $pendingApproval->requester->name ?? '—' }} on {{ fdate($pendingApproval->created_at) }}.
      <span style="margin-left:auto;display:inline-flex;gap:6px">
        <form method="POST" action="{{ route('approvals.decide',$pendingApproval->id) }}" style="display:inline">@csrf<input type="hidden" name="decision" value="approved"><button class="btn btn-sm btn-ok">Approve</button></form>
        <form method="POST" action="{{ route('approvals.decide',$pendingApproval->id) }}" style="display:inline">@csrf<input type="hidden" name="decision" value="rejected"><button class="btn btn-sm btn-danger">Reject</button></form>
      </span>
    </div>
    @endif

    @if($key==='maintenance-work-orders' && in_array($st,['open','in-progress','on-hold']) && perm('fleet.approve'))
    <details class="card" style="margin-bottom:14px"><summary style="cursor:pointer;padding:10px 14px;font-weight:700">✓ Complete this work order (posts parts issue)</summary>
      <div class="card-b"><form method="POST" action="{{ route('maintenance-work-orders.complete',$record->id) }}">@csrf
        <div class="frow">
          <div class="fld c4"><label>Parts store (issue from)</label><select name="warehouse_id"><option value="">— Don't issue parts —</option>@foreach(\App\Models\Warehouse::orderBy('name')->get() as $w)<option value="{{ $w->id }}">{{ $w->name }}</option>@endforeach</select></div>
          <div class="fld c4"><label>Labour cost</label><input type="number" step="0.01" name="labour_cost" value="{{ $record->labour_cost }}"></div>
          <div class="fld c4"><label>Work done</label><input type="text" name="work_done" value="{{ $record->work_done }}"></div>
        </div><button class="btn btn-ok btn-sm">Complete work order</button>
      </form></div>
    </details>
    @endif
    @if($key==='expense-claims' && $st==='approved' && perm('finance.approve'))
    <details class="card" style="margin-bottom:14px" open><summary style="cursor:pointer;padding:10px 14px;font-weight:700">💰 Pay this claim ({{ cmoney($record->total_amount) }})</summary>
      <div class="card-b"><form method="POST" action="{{ route('expense-claims.pay',$record->id) }}">@csrf
        <div class="frow"><div class="fld c6"><label>Pay from</label><select name="bank_account_id" required><option value="">— Select —</option>@foreach(\App\Models\BankAccount::where('is_active',true)->orderBy('bank_name')->get() as $b)<option value="{{ $b->id }}">{{ $b->display_name }} ({{ money($b->current_balance) }})</option>@endforeach</select></div></div>
        <button class="btn btn-pri btn-sm">Pay & post</button>
      </form></div>
    </details>
    @endif

    <dl class="dl">
    @if(!empty($cfg['fields']))
      @foreach($cfg['fields'] as $name => $f)
        @php
          $type = $f['type'] ?? 'text'; $v = $record->$name ?? null;
          if(!empty($f['model']) && str_ends_with($name,'_id') && $v){ $rel = substr($name,0,-3); try{ $rv = data_get($record,$rel); if($rv) $v = $rv->display_name ?? $rv->name ?? $v; }catch(\Throwable $e){} }
          if(!empty($f['options']) && isset($f['options'][$v])) $v = $f['options'][$v];
          if($name==='allowances' && is_array($record->allowances)) { $tmp=[]; foreach($record->allowances as $ak=>$av) $tmp[]="$ak: ".money($av); $v = implode(' · ',$tmp); }
        @endphp
        <div><dt>{{ $f['label'] }}</dt><dd>
          @if($type==='checkbox'){!! $v ? '<span class="bdg b-ok">Yes</span>' : '<span class="muted">No</span>' !!}
          @elseif($type==='date'){{ fdate($v) }}
          @elseif($name==='status')<span class="bdg b-{{ statusClass($v) }}">{{ $v }}</span>
          @else{{ $v ?? '—' }}@endif
        </dd></div>
      @endforeach
    @else
      @foreach($record->getAttributes() as $an => $av)
        @if(!in_array($an,['password','remember_token']))
        <div><dt>{{ ucwords(str_replace('_',' ',$an)) }}</dt><dd>
          @if($an==='status')<span class="bdg b-{{ statusClass($av) }}">{{ $av }}</span>
          @elseif(str_ends_with($an,'_at') || str_ends_with($an,'_date') || $an==='valid_until'){{ fdate($av) }}
          @elseif(is_numeric($av) && str_contains($an,'amount') || in_array($an,['grand_total','subtotal','balance_due','amount_paid','total_amount','net_payable','amount','rate','subtotal'])){{ money($av) }}@if(!empty($record->currency_code) && $record->currency_code!=='GHS') <span class="muted">{{ $record->currency_code }}</span>@endif
          @else{{ $av ?? '—' }}@endif
        </dd></div>
        @endif
      @endforeach
    @endif
    </dl>

    @if($lines->count())
    @php
      $lineCols = match($key){
        'quotations' => ['product.display_name'=>'Product','description'=>'Desc','qty_tonnes'=>'Qty|qty','rate'=>'Rate|money','discount'=>'Disc|money','amount'=>'Amount|money'],
        'sales-orders' => ['product.display_name'=>'Product','qty_ordered'=>'Ordered|qty','qty_dispatched'=>'Dispatched|qty','rate'=>'Rate|money','amount'=>'Amount|money'],
        'delivery-notes' => ['product.display_name'=>'Product','stockpile.code'=>'Pile','qty_tonnes'=>'Qty|qty','rate'=>'Rate|money','amount'=>'Amount|money'],
        'sales-invoices' => ['description'=>'Description','qty'=>'Qty|qty','rate'=>'Rate|money','amount'=>'Amount|money'],
        'sales-credit-notes' => ['description'=>'Description','qty'=>'Qty|qty','rate'=>'Rate|money','amount'=>'Amount|money'],
        'purchase-requisitions' => ['item.display_name'=>'Item','description'=>'Desc','qty'=>'Qty|qty','estimated_rate'=>'Est rate|money'],
        'purchase-orders' => ['description'=>'Description','qty_ordered'=>'Ordered|qty','qty_received'=>'Received|qty','rate'=>'Rate|money','amount'=>'Amount|money'],
        'goods-receipts' => ['item.display_name'=>'Item','product.display_name'=>'Product','qty_received'=>'Received|qty','qty_accepted'=>'Accepted|qty','qty_rejected'=>'Rejected|qty','rate'=>'Rate|money','amount'=>'Amount|money'],
        'purchase-invoices' => ['description'=>'Description','qty'=>'Qty|qty','rate'=>'Rate|money','amount'=>'Amount|money'],
        'stock-adjustments' => ['item.display_name'=>'Item','system_qty'=>'System|qty','counted_qty'=>'Counted|qty','diff_qty'=>'Diff|qty','rate'=>'Rate|money'],
        'journals' => ['account.display_name'=>'Account','narration'=>'Narration','debit'=>'Debit|money','credit'=>'Credit|money'],
        'expense-claims' => ['expense_date'=>'Date|date','category'=>'Category','description'=>'Description','amount'=>'Amount|money'],
        default => [],
      };
    @endphp
    @if($lineCols)
    <h3 style="margin:16px 0 8px">Lines</h3>
    <div class="twrap"><table class="tbl"><thead><tr>
      @foreach($lineCols as $lf => $lspec)@php [$ll,$lfmt]=array_pad(explode('|',$lspec,2),2,null); @endphp<th @if(in_array($lfmt,['money','qty']))class="r"@endif>{{ $ll }}</th>@endforeach
    </tr></thead><tbody>
      @foreach($lines as $ln)<tr>
        @foreach($lineCols as $lf => $lspec)@php [$ll,$lfmt]=array_pad(explode('|',$lspec,2),2,null); $lv=data_get($ln,$lf); @endphp
        <td @if(in_array($lfmt,['money','qty']))class="r"@endif>@if($lfmt==='money'){{ money($lv) }}@if(!empty($record->currency_code) && $record->currency_code!=='GHS') <span class="muted">{{ $record->currency_code }}</span>@endif@elseif($lfmt==='qty'){{ qty($lv) }}@elseif($lfmt==='date'){{ fdate($lv) }}@else{{ $lv ?? '—' }}@endif</td>
        @endforeach
      </tr>@endforeach
    </tbody></table></div>
    @endif
    @endif

    @if($parts->count())
    <h3 style="margin:16px 0 8px">Parts used</h3>
    <div class="twrap"><table class="tbl"><thead><tr><th>Part</th><th class="r">Qty</th><th class="r">Rate</th><th class="r">Amount</th></tr></thead>
    <tbody>@foreach($parts as $p)<tr><td>{{ $p->item->display_name ?? '' }}</td><td class="r">{{ qty($p->qty) }}</td><td class="r">{{ money($p->rate) }}</td><td class="r">{{ money($p->amount) }}</td></tr>@endforeach</tbody></table></div>
    @endif
  </div>
</div>
@endsection
