@extends('layouts.app')
@section('title', $student->name)
@section('page_title', 'Student Profile')
@section('breadcrumbs')
    <li class="breadcrumb-item"><a href="{{ route('students.index') }}">Students</a></li>
    <li class="breadcrumb-item active">{{ $student->name }}</li>
@endsection

@php $f = $student->family; @endphp

@section('content')
{{-- ============ Header card with identity + quick actions ============ --}}
<div class="card mb-3">
    <div class="card-body">
        <div class="d-flex flex-wrap align-items-center gap-3">
            @if($student->photo_url)
                <img src="{{ $student->photo_url }}" class="rounded-circle" width="76" height="76" style="object-fit:cover">
            @else
                <span class="sms-avatar" style="width:76px;height:76px;font-size:1.6rem">{{ $student->initials }}</span>
            @endif
            <div class="flex-grow-1">
                <h4 class="mb-0">{{ $student->name }}
                    <span class="badge bg-soft-{{ $student->status_color }} text-capitalize align-middle ms-1">{{ str_replace('_',' ',$student->status) }}</span>
                    @php $feeOutstanding = $feeOutstanding ?? $challans->whereIn('status', ['unpaid', 'partial'])->sum(fn ($c) => max(0, (float) $c->balance)); @endphp
                    <span class="badge align-middle ms-1 {{ $feeOutstanding > 0 ? 'bg-soft-danger' : 'bg-soft-success' }}"
                          title="Total remaining fees on the family account">
                        <i class="bi bi-cash-coin me-1"></i>Remaining: Rs {{ number_format($feeOutstanding) }}
                    </span>
                </h4>
                @if($student->status !== 'active' && ($student->status_changed_at || $student->status_reason))
                    <div class="small text-muted mt-1">
                        <i class="bi bi-info-circle me-1"></i>{{ ucfirst(str_replace('_',' ',$student->status)) }}
                        @if($student->status_changed_at) on {{ $student->status_changed_at->format('d M Y') }}@endif
                        @if($student->status_reason) — {{ $student->status_reason }}@endif
                    </div>
                @endif
                <div class="text-muted small">
                    <span class="me-3"><i class="bi bi-hash"></i>{{ $student->admission_number }}</span>
                    <span class="me-3"><i class="bi bi-mortarboard me-1"></i>{{ $student->schoolClass?->name ?? '—' }}{{ $student->section ? ' / '.$student->section->name : '' }}</span>
                    <span class="me-3"><i class="bi bi-people me-1"></i><a href="{{ route('families.show', $student->family_id) }}" class="text-decoration-none">{{ $f?->family_code }}</a></span>
                    <span><i class="bi bi-building me-1"></i>{{ $student->branch?->name }}</span>
                </div>
            </div>
            <div class="d-flex gap-2">
                @can('fees.view')
                    <a href="{{ route('students.fee-card', $student) }}" target="_blank" class="btn btn-outline-success btn-sm"><i class="bi bi-card-heading me-1"></i>Fee Card</a>
                @endcan
                @can('update', $student)
                    <a href="{{ route('students.edit', $student) }}" class="btn btn-outline-primary btn-sm"><i class="bi bi-pencil me-1"></i>Edit</a>
                    <div class="dropdown">
                        <button class="btn btn-primary btn-sm dropdown-toggle" data-bs-toggle="dropdown"><i class="bi bi-lightning-charge me-1"></i>Actions</button>
                        <ul class="dropdown-menu dropdown-menu-end shadow">
                            <li><h6 class="dropdown-header">Quick Actions</h6></li>
                            @can('fees.collect')
                                <li><a class="dropdown-item" href="{{ $collectChallan ? route('challans.show', $collectChallan) : route('challans.create') }}"><i class="bi bi-cash-coin me-2"></i>Collect Fee</a></li>
                            @endcan
                            @can('attendance.create')
                                <li><a class="dropdown-item" href="{{ route('attendance.students.index', ['class_id' => $student->class_id, 'section_id' => $student->section_id]) }}"><i class="bi bi-calendar-check me-2"></i>Mark Attendance</a></li>
                            @endcan
                            @can('exams.view')
                                <li><a class="dropdown-item" href="{{ route('results.card', ['student_id' => $student->id]) }}"><i class="bi bi-card-checklist me-2"></i>View Results</a></li>
                            @endcan
                            @can('certificates.view')
                                <li><a class="dropdown-item" href="{{ route('certificates.generate', ['student_id' => $student->id]) }}"><i class="bi bi-award me-2"></i>Generate Certificate</a></li>
                            @endcan
                            <li><a class="dropdown-item" href="{{ route('students.id-card', $student) }}" target="_blank"><i class="bi bi-person-badge me-2"></i>Print ID Card</a></li>
                            @can('communication.send')
                                <li><a class="dropdown-item" href="{{ route('communication.compose', ['channel' => 'sms', 'audience' => 'custom', 'to' => $student->family?->primary_mobile]) }}"><i class="bi bi-chat-dots me-2"></i>Send SMS</a></li>
                            @endcan
                            <li><hr class="dropdown-divider"></li>
                            <li><h6 class="dropdown-header">Lifecycle</h6></li>
                            <li>
                                <form method="POST" action="{{ route('students.promote', $student) }}" data-confirm="Promote {{ $student->name }} to the next class?">
                                    @csrf <button class="dropdown-item"><i class="bi bi-arrow-up-circle me-2"></i>Promote to Next Class</button>
                                </form>
                            </li>
                            @if($student->status === 'active')
                                <li>
                                    <button class="dropdown-item text-danger js-lifecycle" data-status="withdrawn"
                                        data-title="Withdraw Admission" data-icon="bi-person-dash"
                                        data-help="Records the admission as withdrawn. Add the reason below.">
                                        <i class="bi bi-person-dash me-2"></i>Withdraw Admission
                                    </button>
                                </li>
                                <li>
                                    <button class="dropdown-item text-warning js-lifecycle" data-status="left"
                                        data-title="Mark as Left" data-icon="bi-box-arrow-right"
                                        data-help="Records that the student has left the school. Add the reason below.">
                                        <i class="bi bi-box-arrow-right me-2"></i>Mark as Left
                                    </button>
                                </li>
                            @else
                                <li>
                                    <button class="dropdown-item text-success js-lifecycle" data-status="active"
                                        data-title="Rejoin / Reactivate" data-icon="bi-person-check"
                                        data-help="Brings the student back to Active status."
                                        data-reason="0">
                                        <i class="bi bi-person-check me-2"></i>Rejoin / Reactivate
                                    </button>
                                </li>
                            @endif
                            <li>
                                <button class="dropdown-item" data-bs-toggle="modal" data-bs-target="#statusModal"><i class="bi bi-toggles me-2"></i>Change Status…</button>
                            </li>
                            <li>
                                <form method="POST" action="{{ route('students.create-login', $student) }}" data-confirm="{{ $student->loginUser ? 'Reset this student login password?' : 'Create a student-portal login?' }}">
                                    @csrf <button class="dropdown-item"><i class="bi bi-key me-2"></i>{{ $student->loginUser ? 'Reset Student Login' : 'Create Student Login' }}</button>
                                </form>
                            </li>
                        </ul>
                    </div>
                @endcan
            </div>
        </div>
    </div>
</div>

{{-- ============ Tabs ============ --}}
<div class="card">
    <div class="card-header p-0 border-0">
        <ul class="nav nav-tabs px-2 pt-2 flex-nowrap overflow-auto" role="tablist">
            @php
                $tabs = [
                    'basic' => ['Basic', 'bi-person-vcard'],
                    'parent' => ['Parents', 'bi-people'],
                    'family' => ['Family', 'bi-house-heart'],
                    'siblings' => ['Siblings', 'bi-diagram-3'],
                    'fees' => ['Fees', 'bi-cash-coin'],
                    'attendance' => ['Attendance', 'bi-calendar2-check'],
                    'exams' => ['Examination', 'bi-journal-text'],
                    'documents' => ['Documents', 'bi-folder'],
                    'communication' => ['Communication', 'bi-chat-left-dots'],
                    'medical' => ['Medical', 'bi-heart-pulse'],
                    'promotion' => ['Promotion', 'bi-arrow-up-circle'],
                    'activity' => ['Activity', 'bi-clock-history'],
                ];
            @endphp
            @foreach($tabs as $key => [$label, $icon])
                <li class="nav-item" role="presentation">
                    <button class="nav-link {{ $loop->first ? 'active' : '' }} text-nowrap" data-bs-toggle="tab" data-bs-target="#tab-{{ $key }}" type="button">
                        <i class="bi {{ $icon }} me-1"></i>{{ $label }}
                    </button>
                </li>
            @endforeach
        </ul>
    </div>
    <div class="card-body tab-content">
        {{-- Basic --}}
        <div class="tab-pane fade show active" id="tab-basic">
            <dl class="row mb-0 small">
                <dt class="col-sm-3 text-muted">Full Name</dt><dd class="col-sm-3">{{ $student->name }}</dd>
                <dt class="col-sm-3 text-muted">Name (Urdu)</dt><dd class="col-sm-3" dir="rtl">{{ $student->name_urdu ?: '—' }}</dd>
                <dt class="col-sm-3 text-muted">Gender</dt><dd class="col-sm-3 text-capitalize">{{ $student->gender }}</dd>
                <dt class="col-sm-3 text-muted">Date of Birth</dt><dd class="col-sm-3">{{ optional($student->date_of_birth)->format('d M Y') ?? '—' }} @if($student->age)<span class="text-muted">({{ $student->age }} yrs)</span>@endif</dd>
                <dt class="col-sm-3 text-muted">Place of Birth</dt><dd class="col-sm-3">{{ $student->place_of_birth ?: '—' }}</dd>
                <dt class="col-sm-3 text-muted">Blood Group</dt><dd class="col-sm-3">{{ $student->blood_group ?: '—' }}</dd>
                <dt class="col-sm-3 text-muted">Religion</dt><dd class="col-sm-3">{{ $student->religion ?: '—' }}</dd>
                <dt class="col-sm-3 text-muted">Nationality</dt><dd class="col-sm-3">{{ $student->nationality ?: '—' }}</dd>
                <dt class="col-sm-3 text-muted">B-Form #</dt><dd class="col-sm-3">{{ $student->b_form_number ?: '—' }}</dd>
                <dt class="col-sm-3 text-muted">GR Number</dt><dd class="col-sm-3">{{ $student->gr_number ?: '—' }}</dd>
                <dt class="col-sm-3 text-muted">Roll Number</dt><dd class="col-sm-3">{{ $student->roll_number ?: '—' }}</dd>
                <dt class="col-sm-3 text-muted">Registration #</dt><dd class="col-sm-3">{{ $student->registration_number ?: '—' }}</dd>
                <dt class="col-sm-3 text-muted">Class / Section</dt><dd class="col-sm-3">{{ $student->schoolClass?->name ?? '—' }}{{ $student->section ? ' / '.$student->section->name : '' }}</dd>
                <dt class="col-sm-3 text-muted">Group</dt><dd class="col-sm-3">{{ $student->group ?: '—' }}</dd>
                <dt class="col-sm-3 text-muted">Session</dt><dd class="col-sm-3">{{ $student->academicSession?->name ?? '—' }}</dd>
                <dt class="col-sm-3 text-muted">Admission Date</dt><dd class="col-sm-3">{{ optional($student->admission_date)->format('d M Y') ?? '—' }}</dd>
            </dl>
        </div>

        {{-- Parents --}}
        <div class="tab-pane fade" id="tab-parent">
            <div class="row">
                <div class="col-md-6">
                    <h6 class="text-uppercase text-muted small fw-bold">Father</h6>
                    <dl class="row small">
                        <dt class="col-5 text-muted">Name</dt><dd class="col-7">{{ $f?->father_name ?: '—' }}</dd>
                        <dt class="col-5 text-muted">CNIC</dt><dd class="col-7">{{ $f?->father_cnic ?: '—' }}</dd>
                        <dt class="col-5 text-muted">Mobile</dt><dd class="col-7">{{ $f?->father_mobile ?: '—' }}</dd>
                        <dt class="col-5 text-muted">Occupation</dt><dd class="col-7">{{ $f?->father_occupation ?: '—' }}</dd>
                    </dl>
                </div>
                <div class="col-md-6">
                    <h6 class="text-uppercase text-muted small fw-bold">Mother / Guardian</h6>
                    <dl class="row small">
                        <dt class="col-5 text-muted">Mother</dt><dd class="col-7">{{ $f?->mother_name ?: '—' }}</dd>
                        <dt class="col-5 text-muted">Mother Mobile</dt><dd class="col-7">{{ $f?->mother_mobile ?: '—' }}</dd>
                        <dt class="col-5 text-muted">Guardian</dt><dd class="col-7">{{ $f?->guardian_name ?: '—' }}</dd>
                        <dt class="col-5 text-muted">Emergency</dt><dd class="col-7">{{ $f?->emergency_contact ?: '—' }}</dd>
                    </dl>
                </div>
            </div>
        </div>

        {{-- Family --}}
        <div class="tab-pane fade" id="tab-family">
            <div class="d-flex justify-content-between mb-2">
                <h6 class="mb-0">Family {{ $f?->family_code }}</h6>
                <a href="{{ route('families.show', $student->family_id) }}" class="btn btn-sm btn-light border">Open Family <i class="bi bi-arrow-right"></i></a>
            </div>
            <dl class="row small mb-0">
                <dt class="col-sm-3 text-muted">Primary Contact</dt><dd class="col-sm-3">{{ $f?->primary_contact_name }}</dd>
                <dt class="col-sm-3 text-muted">Primary Mobile</dt><dd class="col-sm-3">{{ $f?->primary_mobile }}</dd>
                <dt class="col-sm-3 text-muted">Email</dt><dd class="col-sm-3">{{ $f?->email ?: '—' }}</dd>
                <dt class="col-sm-3 text-muted">Address</dt><dd class="col-sm-9">{{ $f?->address ?: '—' }}</dd>
            </dl>
        </div>

        {{-- Siblings --}}
        <div class="tab-pane fade" id="tab-siblings">
            @if($siblings->isEmpty())
                <p class="text-muted mb-0">No siblings linked to this family.</p>
            @else
                <div class="row g-2">
                    @foreach($siblings as $sib)
                        <div class="col-md-6 col-xl-4">
                            <a href="{{ route('students.show', $sib) }}" class="text-decoration-none">
                                <div class="border rounded p-2 d-flex align-items-center gap-2 h-100">
                                    <span class="sms-avatar sm">{{ $sib->initials }}</span>
                                    <div>
                                        <div class="fw-semibold text-dark">{{ $sib->name }}</div>
                                        <div class="small text-muted">{{ $sib->schoolClass?->name ?? '—' }} ·
                                            <span class="badge bg-soft-{{ $sib->status_color }} text-capitalize">{{ str_replace('_',' ',$sib->status) }}</span>
                                        </div>
                                    </div>
                                </div>
                            </a>
                        </div>
                    @endforeach
                </div>
            @endif
        </div>

        {{-- Fees (family challans) --}}
        <div class="tab-pane fade" id="tab-fees">
            {{-- Per-student fee amounts (overrides vs class default) --}}
            @can('fees.view')
                <div class="card border mb-3">
                    <div class="card-header bg-light d-flex justify-content-between align-items-center py-2">
                        <span class="fw-semibold small"><i class="bi bi-cash-coin me-1"></i>Fee Setup — {{ $student->name }}</span>
                        <span class="text-muted" style="font-size:.75rem">Custom = set for this student · Default = class structure / stop fare</span>
                    </div>
                    <div class="card-body">
                        <form method="POST" action="{{ route('students.fee-heads.update', $student) }}">
                            @csrf @method('PUT')
                            <div class="row g-2">
                                @foreach($feeRows as $row)
                                    <div class="col-md-3 col-sm-4">
                                        <label class="form-label small mb-1">
                                            {{ $row['type']->name }}
                                            @if($row['override'] !== null)
                                                <span class="badge bg-soft-primary">Custom</span>
                                            @else
                                                <span class="badge bg-soft-secondary">Default</span>
                                            @endif
                                        </label>
                                        <div class="input-group input-group-sm">
                                            <span class="input-group-text">Rs</span>
                                            <input type="number" step="0.01" min="0" name="fees[{{ $row['type']->id }}]"
                                                   value="{{ $row['override'] !== null ? (0 + $row['override']) : '' }}"
                                                   placeholder="{{ (int) $row['resolved'] }}"
                                                   class="form-control" @unless(auth()->user()->isSuperAdmin()) disabled @endunless>
                                        </div>
                                        <div class="form-text" style="font-size:.7rem">
                                            Currently bills: <b>Rs {{ number_format($row['resolved']) }}</b>{{ $row['is_transport'] ? ' (stop fare)' : '' }}
                                        </div>
                                    </div>
                                @endforeach
                            </div>
                            @if(auth()->user()->isSuperAdmin())
                                <div class="mt-2 d-flex align-items-center gap-2">
                                    <button class="btn btn-sm btn-primary"><i class="bi bi-save me-1"></i>Save Fee Amounts</button>
                                    <span class="text-muted small">Leave a box blank to use the class default. Changes apply to challans generated from now on.</span>
                                </div>
                            @endif
                        </form>
                    </div>
                </div>
            @endcan

            <div class="d-flex justify-content-between mb-2">
                <span class="text-muted small">Fee challans are issued to the family ({{ $student->family?->family_code }}).</span>
                @can('fees.view')<a href="{{ route('challans.index') }}" class="btn btn-sm btn-light border">Open Fees</a>@endcan
            </div>
            <table class="table table-sm align-middle">
                <thead><tr><th>Challan</th><th>Title</th><th>Due</th><th class="text-end">Net</th><th class="text-end">Paid</th><th class="text-end">Balance</th><th class="text-center">Status</th></tr></thead>
                <tbody>
                    @forelse($challans as $ch)
                        <tr>
                            <td class="small">@can('fees.view')<a href="{{ route('challans.show', $ch) }}" class="text-decoration-none">{{ $ch->challan_number }}</a>@else{{ $ch->challan_number }}@endcan</td>
                            <td class="small">{{ $ch->title }}</td>
                            <td class="small">{{ optional($ch->due_date)->format('d M Y') }}</td>
                            <td class="text-end">{{ number_format($ch->net_payable) }}</td>
                            <td class="text-end text-success">{{ number_format($ch->paid_amount) }}</td>
                            <td class="text-end fw-semibold {{ $ch->balance > 0 ? 'text-danger' : '' }}">{{ number_format($ch->balance) }}</td>
                            <td class="text-center"><span class="badge bg-soft-{{ $ch->status_color }} text-capitalize">{{ $ch->status }}</span></td>
                        </tr>
                    @empty
                        <tr><td colspan="7" class="text-center text-muted py-3">No fee challans issued yet.</td></tr>
                    @endforelse
                </tbody>
            </table>
        </div>

        {{-- Attendance (this month) --}}
        <div class="tab-pane fade" id="tab-attendance">
            <div class="row g-2 mb-3">
                @foreach(['present'=>'success','absent'=>'danger','leave'=>'info'] as $k => $tone)
                    <div class="col"><div class="border rounded p-2 text-center"><div class="h5 mb-0 text-{{ $tone }}">{{ $attendanceSummary[$k] }}</div><div class="small text-muted text-capitalize">{{ $k }}</div></div></div>
                @endforeach
                <div class="col"><div class="border rounded p-2 text-center"><div class="h5 mb-0">{{ $attendanceSummary['total'] ? round(($attendanceSummary['present'])/$attendanceSummary['total']*100) : 0 }}%</div><div class="small text-muted">This month</div></div></div>
            </div>
            <table class="table table-sm align-middle">
                <thead><tr><th>Date</th><th>Day</th><th>Status</th><th>Remarks</th></tr></thead>
                <tbody>
                    @forelse($attendance as $a)
                        <tr>
                            <td class="small">{{ $a->date->format('d M Y') }}</td>
                            <td class="small text-muted">{{ $a->date->format('l') }}</td>
                            <td><span class="badge bg-soft-{{ App\Models\StudentAttendance::statusColor($a->status) }} text-capitalize">{{ str_replace('_',' ',$a->status) }}</span></td>
                            <td class="small text-muted">{{ $a->remarks ?: '—' }}</td>
                        </tr>
                    @empty
                        <tr><td colspan="4" class="text-center text-muted py-3">No attendance recorded this month.</td></tr>
                    @endforelse
                </tbody>
            </table>
        </div>

        {{-- Examination (published results) --}}
        <div class="tab-pane fade" id="tab-exams">
            @forelse($examResults as $er)
                <div class="border rounded p-3 mb-2">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <h6 class="mb-0">{{ $er['exam']->name }}</h6>
                        <div>
                            <span class="badge bg-soft-info">{{ $er['result']['percentage'] }}%</span>
                            <span class="badge bg-soft-primary">Grade {{ $er['result']['grade'] }}</span>
                            <span class="badge bg-soft-{{ $er['result']['status']==='Pass' ? 'success' : 'danger' }}">{{ $er['result']['status'] }}</span>
                            @can('exams.view')<a href="{{ route('results.card', ['exam_id'=>$er['exam']->id, 'student_id'=>$student->id]) }}" class="btn btn-sm btn-light border ms-1">Card</a>@endcan
                        </div>
                    </div>
                    <table class="table table-sm mb-0">
                        <thead><tr><th>Subject</th><th class="text-end">Marks</th><th class="text-center">Grade</th></tr></thead>
                        <tbody>
                            @foreach($er['result']['rows'] as $row)
                                <tr><td>{{ $row['subject'] }}</td><td class="text-end">{{ $row['absent'] ? 'ABS' : number_format($row['obtained']) }}/{{ number_format($row['total']) }}</td><td class="text-center"><span class="badge bg-soft-{{ $row['pass'] ? 'success' : 'danger' }}">{{ $row['grade'] }}</span></td></tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            @empty
                <p class="text-muted text-center py-4">No published exam results for this student yet.</p>
            @endforelse
        </div>

        {{-- Communication --}}
        <div class="tab-pane fade" id="tab-communication">
            <table class="table table-sm align-middle">
                <thead><tr><th>When</th><th>Channel</th><th>To</th><th>Message</th><th class="text-center">Status</th></tr></thead>
                <tbody>
                    @forelse($messages as $m)
                        <tr>
                            <td class="small">{{ $m->sent_at?->format('d M, H:i') ?? $m->created_at->format('d M, H:i') }}</td>
                            <td><span class="badge bg-soft-{{ $m->channel_color }}">{{ App\Models\CommunicationLog::CHANNELS[$m->channel] }}</span></td>
                            <td class="small">{{ $m->to }}</td>
                            <td class="small text-muted">{{ Str::limit($m->body, 50) }}</td>
                            <td class="text-center"><span class="badge bg-soft-{{ $m->status_color }} text-capitalize">{{ $m->status }}</span></td>
                        </tr>
                    @empty
                        <tr><td colspan="5" class="text-center text-muted py-3">No messages sent to this family yet.</td></tr>
                    @endforelse
                </tbody>
            </table>
        </div>

        {{-- Documents --}}
        <div class="tab-pane fade" id="tab-documents">
            @can('update', $student)
                <form method="POST" action="{{ route('students.documents.store', $student) }}" enctype="multipart/form-data" class="row g-2 align-items-end mb-3 p-3 bg-light rounded">
                    @csrf
                    <div class="col-md-3">
                        <label class="form-label small">Type</label>
                        <select name="type" class="form-select form-select-sm" required>
                            @foreach(App\Models\StudentDocument::TYPES as $val => $label)
                                <option value="{{ $val }}">{{ $label }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-4"><label class="form-label small">Title (optional)</label>
                        <input type="text" name="title" class="form-control form-control-sm"></div>
                    <div class="col-md-3"><label class="form-label small">File</label>
                        <input type="file" name="file" class="form-control form-control-sm" required></div>
                    <div class="col-md-2"><button class="btn btn-sm btn-primary w-100"><i class="bi bi-upload me-1"></i>Upload</button></div>
                </form>
            @endcan
            <div class="table-responsive">
                <table class="table table-sm align-middle">
                    <thead><tr><th>Type</th><th>Title</th><th>Uploaded</th><th class="text-end">Actions</th></tr></thead>
                    <tbody>
                        @forelse($student->documents as $doc)
                            <tr>
                                <td><span class="badge bg-soft-info">{{ $doc->type_label }}</span></td>
                                <td>{{ $doc->title }}</td>
                                <td class="small text-muted">{{ $doc->created_at->format('d M Y') }}</td>
                                <td class="text-end">
                                    <a href="{{ $doc->url }}" target="_blank" class="btn btn-sm btn-light border"><i class="bi bi-eye"></i></a>
                                    @can('update', $student)
                                        <form method="POST" action="{{ route('students.documents.destroy', [$student, $doc]) }}" class="d-inline" data-confirm="Delete this document?">
                                            @csrf @method('DELETE')
                                            <button class="btn btn-sm btn-light border text-danger"><i class="bi bi-trash"></i></button>
                                        </form>
                                    @endcan
                                </td>
                            </tr>
                        @empty
                            <tr><td colspan="4" class="text-center text-muted py-3">No documents uploaded.</td></tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>

        {{-- Medical --}}
        <div class="tab-pane fade" id="tab-medical">
            <dl class="row small mb-0">
                <dt class="col-sm-3 text-muted">Allergies</dt><dd class="col-sm-9">{{ $student->allergies ?: '—' }}</dd>
                <dt class="col-sm-3 text-muted">Medical Conditions</dt><dd class="col-sm-9">{{ $student->medical_conditions ?: '—' }}</dd>
                <dt class="col-sm-3 text-muted">Disability Info</dt><dd class="col-sm-9">{{ $student->disability_info ?: '—' }}</dd>
                <dt class="col-sm-3 text-muted">Medical Notes</dt><dd class="col-sm-9">{{ $student->medical_notes ?: '—' }}</dd>
            </dl>
        </div>

        {{-- Promotion History (derived from activity log class changes) --}}
        <div class="tab-pane fade" id="tab-promotion">
            @php $promo = $activities->filter(fn($a) => isset($a->properties['attributes']['class_id'])); @endphp
            @if($promo->isEmpty())
                <p class="text-muted mb-0">No promotion / class-change history recorded yet.</p>
            @else
                <ul class="list-group list-group-flush">
                    @foreach($promo as $a)
                        <li class="list-group-item small">
                            <i class="bi bi-arrow-up-circle text-primary me-1"></i>Class changed
                            <span class="text-muted">— {{ $a->causer?->name ?? 'System' }}, {{ $a->created_at->format('d M Y H:i') }}</span>
                        </li>
                    @endforeach
                </ul>
            @endif
        </div>

        {{-- Activity --}}
        <div class="tab-pane fade" id="tab-activity">
            @if($activities->isEmpty())
                <p class="text-muted mb-0">No activity recorded.</p>
            @else
                <ul class="list-group list-group-flush">
                    @foreach($activities as $a)
                        <li class="list-group-item d-flex justify-content-between small">
                            <span><span class="badge bg-soft-secondary text-capitalize me-2">{{ $a->event ?? $a->description }}</span>{{ $a->description }}</span>
                            <span class="text-muted">{{ $a->causer?->name ?? 'System' }} · {{ $a->created_at->diffForHumans() }}</span>
                        </li>
                    @endforeach
                </ul>
            @endif
        </div>
    </div>
</div>

{{-- Change-status modal --}}
@can('update', $student)
<div class="modal fade" id="statusModal" tabindex="-1">
    <div class="modal-dialog">
        <form method="POST" action="{{ route('students.status', $student) }}" class="modal-content">
            @csrf
            <div class="modal-header"><h5 class="modal-title">Change Student Status</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <div class="row g-2">
                    <div class="col-md-6">
                        <label class="form-label small">Status</label>
                        <select name="status" class="form-select text-capitalize">
                            @foreach(App\Models\Student::STATUSES as $s)
                                <option value="{{ $s }}" @selected($student->status === $s)>{{ ucfirst(str_replace('_',' ',$s)) }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label small">Effective Date</label>
                        <input type="date" name="status_changed_at" value="{{ now()->format('Y-m-d') }}" class="form-control">
                    </div>
                    <div class="col-12">
                        <label class="form-label small">Reason / Note</label>
                        <input type="text" name="status_reason" value="{{ $student->status_reason }}" class="form-control" placeholder="e.g. relocation, fee default, transferred to other school">
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-light border" data-bs-dismiss="modal">Cancel</button>
                <button class="btn btn-primary">Update Status</button>
            </div>
        </form>
    </div>
</div>

{{-- Dedicated lifecycle modal (Withdraw / Left / Rejoin) --}}
<div class="modal fade" id="lifecycleModal" tabindex="-1">
    <div class="modal-dialog">
        <form method="POST" action="{{ route('students.status', $student) }}" class="modal-content">
            @csrf
            <input type="hidden" name="status" id="lc_status">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi" id="lc_icon"></i> <span id="lc_title"></span></h5>
                <button class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p class="text-muted small" id="lc_help"></p>
                <div class="mb-2">
                    <label class="form-label small">Effective Date</label>
                    <input type="date" name="status_changed_at" value="{{ now()->format('Y-m-d') }}" class="form-control">
                </div>
                <div class="mb-1" id="lc_reason_wrap">
                    <label class="form-label small">Reason</label>
                    <input type="text" name="status_reason" id="lc_reason" class="form-control" placeholder="e.g. relocation, transferred, fee default">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-light border" data-bs-dismiss="modal">Cancel</button>
                <button class="btn btn-primary" id="lc_submit">Confirm</button>
            </div>
        </form>
    </div>
</div>
@endcan

@push('scripts')
<script>
    document.querySelectorAll('[data-soon]').forEach(b => b.addEventListener('click', e => {
        e.preventDefault();
        alert('This quick action becomes available when its module is built in a later phase.');
    }));

    // Dedicated lifecycle actions (Withdraw / Left / Rejoin)
    (function () {
        const modalEl = document.getElementById('lifecycleModal');
        if (!modalEl) return;
        const modal = new bootstrap.Modal(modalEl);
        document.querySelectorAll('.js-lifecycle').forEach(btn => {
            btn.addEventListener('click', () => {
                document.getElementById('lc_status').value = btn.dataset.status;
                document.getElementById('lc_title').textContent = btn.dataset.title;
                document.getElementById('lc_icon').className = 'bi ' + (btn.dataset.icon || 'bi-toggles');
                document.getElementById('lc_help').textContent = btn.dataset.help || '';
                const showReason = btn.dataset.reason !== '0';
                document.getElementById('lc_reason_wrap').style.display = showReason ? '' : 'none';
                document.getElementById('lc_reason').required = false;
                document.getElementById('lc_submit').textContent = btn.dataset.title;
                modal.show();
            });
        });
    })();
</script>
@endpush
@endsection
