@extends('layouts.app')
@section('title', $plan->title)

@section('content')
@php($pr = $plan->progress())
<div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3">
    <div>
        <h1 class="h4 fw-bold mb-0">📋 {{ $plan->title }}</h1>
        <span class="mb-muted small">
            <a href="{{ route('tenant.patients.show', $plan->patient) }}">{{ $plan->patient->full_name }}</a>
            · {{ $plan->dentist->name }}
        </span>
    </div>
    <div class="d-flex gap-2 align-items-center">
        <span class="status-chip" style="background: {{ $plan->status->color() }}">{{ $plan->status->label() }}</span>
        <a class="btn btn-sm mb-btn-ghost" target="_blank" href="{{ route('tenant.treatment-plans.pdf', $plan) }}">📄 PDF</a>
        @if($plan->items->isNotEmpty() && $plan->patient->whatsapp_opt_in)
        @can('treatment-plans.manage')
            <form method="POST" action="{{ route('tenant.treatment-plans.send-pdf', $plan) }}">
                @csrf
                <button class="btn btn-sm mb-btn-ghost">💬 {{ __('Send on WhatsApp') }}</button>
            </form>
        @endcan
        @endif
    </div>
</div>

@can('update', $plan)
<div class="d-flex gap-2 mb-3 flex-wrap">
    @foreach($statuses as $s)
        @if($plan->status->canTransitionTo($s))
            <form method="POST" action="{{ route('tenant.treatment-plans.status', $plan) }}">
                @csrf @method('PATCH')
                <input type="hidden" name="status" value="{{ $s->value }}">
                <button class="btn btn-sm mb-btn-ghost">→ {{ $s->label() }}</button>
            </form>
        @endif
    @endforeach
</div>
@endcan

<div class="row g-3">
    <div class="col-lg-8">
        <div class="mb-card p-3">
            <table class="table mb-table align-middle mb-0">
                <thead><tr>
                    <th>{{ __('Procedure') }}</th><th>{{ __('Tooth') }}</th>
                    <th>{{ __('Price') }}</th><th>{{ __('Status') }}</th><th></th>
                </tr></thead>
                <tbody>
                @forelse($plan->items as $item)
                    <tr class="{{ $item->status === \App\Enums\PlanItemStatus::Cancelled ? 'opacity-50' : '' }}">
                        <td>
                            {{ $item->procedure->name() }}
                            @if($item->note)<div class="mb-muted small">{{ $item->note }}</div>@endif
                        </td>
                        <td>
                            @if($item->tooth)
                                <strong>{{ $item->tooth }}</strong>
                                @if($item->surfaces)<span class="mb-muted small">{{ implode(',', $item->surfaces) }}</span>@endif
                            @else — @endif
                        </td>
                        <td dir="ltr">{{ number_format($item->price) }}</td>
                        <td>
                            <span class="badge text-bg-{{ match($item->status) {
                                \App\Enums\PlanItemStatus::Completed => 'success',
                                \App\Enums\PlanItemStatus::Scheduled => 'info',
                                \App\Enums\PlanItemStatus::Cancelled => 'secondary',
                                default => 'warning' } }}">{{ $item->status->label() }}</span>
                        </td>
                        <td class="text-end">
                            @can('update', $plan)
                                @if($item->status !== \App\Enums\PlanItemStatus::Completed && $item->status !== \App\Enums\PlanItemStatus::Cancelled)
                                    <form class="d-inline" method="POST" action="{{ route('tenant.treatment-plans.items.complete', [$plan, $item]) }}">
                                        @csrf
                                        <button class="btn btn-sm mb-btn-primary">✓ {{ __('Complete') }}</button>
                                    </form>
                                    <form class="d-inline" method="POST" action="{{ route('tenant.treatment-plans.items.cancel', [$plan, $item]) }}">
                                        @csrf
                                        <button class="btn btn-sm mb-btn-ghost">✕</button>
                                    </form>
                                @endif
                            @endcan
                        </td>
                    </tr>
                @empty
                    <tr><td colspan="5" class="mb-muted py-4 text-center">{{ __('No items yet — add the first procedure below.') }}</td></tr>
                @endforelse
                </tbody>
            </table>
        </div>

        @can('update', $plan)
        @if(! in_array($plan->status, [\App\Enums\TreatmentPlanStatus::Completed, \App\Enums\TreatmentPlanStatus::Cancelled]))
        <div class="mb-card p-4 mt-3">
            <h2 class="h6 fw-semibold mb-3">+ {{ __('Add item') }}</h2>
            <form method="POST" action="{{ route('tenant.treatment-plans.items.store', $plan) }}" class="row g-2 align-items-end">
                @csrf
                <div class="col-md-4">
                    <label class="form-label small">{{ __('Procedure') }}</label>
                    <select name="procedure_id" id="itemProc" class="form-select form-select-sm" required>
                        @foreach($procedures as $proc)
                            <option value="{{ $proc->id }}" data-price="{{ $proc->default_price }}">
                                {{ $proc->name() }} — {{ number_format($proc->default_price) }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-6 col-md-2">
                    <label class="form-label small">{{ __('Tooth (FDI)') }}</label>
                    <select name="tooth" class="form-select form-select-sm">
                        <option value="">—</option>
                        @foreach(\App\Domain\Clinical\Fdi::all() as $t)
                            <option value="{{ $t }}">{{ $t }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-6 col-md-2">
                    <label class="form-label small">{{ __('Price (IQD)') }}</label>
                    <input type="number" name="price" id="itemPrice" min="0" step="250" class="form-control form-control-sm">
                </div>
                <div class="col-md-3">
                    <label class="form-label small">{{ __('Note') }}</label>
                    <input name="note" class="form-control form-control-sm">
                </div>
                <div class="col-md-1">
                    <button class="btn mb-btn-primary btn-sm w-100">+</button>
                </div>
                <div class="col-12">
                    <div class="d-flex gap-2 align-items-center">
                        <span class="small mb-muted">{{ __('Surfaces') }}:</span>
                        @foreach(config('dental.surfaces') as $s)
                            <div class="form-check form-check-inline m-0">
                                <input class="form-check-input" type="checkbox" name="surfaces[]" value="{{ $s }}" id="sf{{ $s }}">
                                <label class="form-check-label small" for="sf{{ $s }}">{{ $s }}</label>
                            </div>
                        @endforeach
                    </div>
                </div>
            </form>
        </div>
        @endif
        @endcan
    </div>

    <div class="col-lg-4">
        <div class="mb-card p-4">
            <h2 class="h6 fw-semibold mb-3">{{ __('Summary') }}</h2>
            <dl class="row mb-0">
                <dt class="col-6">{{ __('Progress') }}</dt>
                <dd class="col-6">{{ $pr['done'] }}/{{ $pr['total'] }} {{ __('items') }}</dd>
                <dt class="col-6">{{ __('Subtotal') }}</dt>
                <dd class="col-6" dir="ltr">{{ number_format($plan->totalGross()) }} IQD</dd>
                <dt class="col-6">{{ __('Discount') }}</dt>
                <dd class="col-6" dir="ltr">− {{ number_format($plan->discount_amount) }} IQD</dd>
                <dt class="col-6 fw-bold">{{ __('Total') }}</dt>
                <dd class="col-6 fw-bold" dir="ltr">{{ number_format($plan->totalNet()) }} IQD</dd>
            </dl>
            @can('update', $plan)
            <hr style="border-color:var(--mb-line)">
            <form method="POST" action="{{ route('tenant.treatment-plans.update', $plan) }}">
                @csrf @method('PATCH')
                <label class="form-label small">{{ __('Discount (IQD)') }}</label>
                <div class="input-group input-group-sm mb-2">
                    <input type="number" name="discount_amount" value="{{ $plan->discount_amount }}"
                           min="0" max="{{ $plan->totalGross() }}" step="250" class="form-control">
                    <button class="btn mb-btn-primary">{{ __('Apply') }}</button>
                </div>
            </form>
            @endcan
            @if($plan->notes)
                <hr style="border-color:var(--mb-line)">
                <p class="mb-muted small mb-0">{{ $plan->notes }}</p>
            @endif
        </div>
        <div class="mb-card p-4 mt-3 d-grid gap-2">
            <a class="btn mb-btn-ghost btn-sm" href="{{ route('tenant.patients.chart', $plan->patient) }}">
                🦷 {{ __('Open dental chart') }}
            </a>
            @can('invoices.manage')
                @if($plan->items->isNotEmpty())
                <form method="POST" action="{{ route('tenant.treatment-plans.invoice', $plan) }}">
                    @csrf
                    <button class="btn mb-btn-primary btn-sm w-100">🧾 {{ __('Create invoice from plan') }}</button>
                </form>
                @endif
            @endcan
        </div>
    </div>
</div>

@push('page-scripts')
<script>
// Pre-fill price from the chosen procedure's default
const proc = document.getElementById('itemProc');
const price = document.getElementById('itemPrice');
function syncPrice() { if (proc && price) price.value = proc.selectedOptions[0]?.dataset.price ?? 0; }
proc?.addEventListener('change', syncPrice);
syncPrice();
</script>
@endpush
@endsection
