@extends('layouts.app')

@section('title', __('clinicCore::lang.doctors'))

@section('css')
<style>
/* ── Schedule row table ──────────────────────── */
.schedule-row td { vertical-align: middle; font-size:13px; }
.day-badge { display:inline-block; padding:2px 8px; border-radius:4px; background:#e2e8f0; font-size:11px; font-weight:700; color:#475569; }

/* ── Weekly grid view ───────────────────────── */
.week-grid { display:flex; gap:8px; overflow-x:auto; padding-bottom:6px; }
.day-col { flex:1; min-width:110px; }
.day-col-header {
    text-align:center; font-weight:700; font-size:12px; letter-spacing:.5px; text-transform:uppercase;
    padding:8px 4px; border-radius:8px 8px 0 0; background:#f1f5f9; color:#64748b; border:1px solid #e2e8f0;
}
.day-col-header.is-today { background:linear-gradient(135deg,#3b82f6,#6366f1); color:#fff; border-color:transparent; }
.day-col-body { border:1px solid #e2e8f0; border-top:none; border-radius:0 0 8px 8px; min-height:100px; padding:6px; background:#fff; }
.day-off { text-align:center; color:#cbd5e1; font-size:12px; padding:18px 0; }
.day-off i { display:block; font-size:22px; margin-bottom:4px; }

.sched-block {
    border-radius:8px; padding:8px 10px; margin-bottom:6px; color:#fff; position:relative;
    background:linear-gradient(135deg,#0ea5e9,#6366f1);
    box-shadow:0 2px 6px rgba(99,102,241,.25);
}
.sched-block.inactive-block { background:linear-gradient(135deg,#94a3b8,#64748b); box-shadow:none; opacity:.7; }
.sched-block .time-range { font-size:13px; font-weight:700; letter-spacing:.3px; }
.sched-block .slot-pill {
    display:inline-block; background:rgba(255,255,255,.25); border-radius:20px;
    font-size:10px; padding:1px 7px; margin-top:4px; font-weight:600;
}
.sched-block .dept-pill {
    display:block; margin-top:5px; font-size:11px; opacity:.9;
    white-space:nowrap; overflow:hidden; text-overflow:ellipsis;
}
.sched-block .slot-count { font-size:10px; opacity:.75; margin-top:3px; }
.sched-block .inactive-badge {
    position:absolute; top:4px; right:6px; font-size:9px; background:rgba(0,0,0,.3);
    border-radius:10px; padding:1px 5px;
}
</style>
@include('clinicCore::partials._mobile_responsive')
@endsection

@section('content')
<section class="content-header">
    <h1><i class="fas fa-user-md"></i> @lang('clinicCore::lang.doctors')</h1>
</section>

<section class="content">

    <div class="row">
        <div class="col-md-12">
            @component('components.widget', ['class' => 'box-primary'])
                <div class="pull-right" style="margin-bottom:10px;">
                    @can('clinic.manage_doctors')
                    <button class="btn btn-primary" data-toggle="modal" data-target="#doctorModal">
                        <i class="fa fa-plus"></i> @lang('clinicCore::lang.add_doctor')
                    </button>
                    @endcan
                </div>

                <table class="table table-bordered table-striped" id="doctors_table">
                    <thead>
                        <tr>
                            <th>@lang('clinicCore::lang.doctor_name')</th>
                            <th>@lang('clinicCore::lang.departments')</th>
                            <th>@lang('clinicCore::lang.appointments')</th>
                            <th>Product / Fee</th>
                            <th>@lang('clinicCore::lang.status')</th>
                            <th>@lang('clinicCore::lang.actions')</th>
                        </tr>
                    </thead>
                </table>
            @endcomponent
        </div>
    </div>
</section>

{{-- ══════════════════════════════════════════════════════════════
     DOCTOR ADD / EDIT MODAL
══════════════════════════════════════════════════════════════ --}}
<div class="modal fade" id="doctorModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" style="font-size:15px;">&times;</button>
                <h4 class="modal-title" id="doctorModalTitle">@lang('clinicCore::lang.add_doctor')</h4>
            </div>
            <div class="modal-body">
                <input type="hidden" id="doctor_id">
                {{-- Row 1: User select (first) + Status --}}
                <div class="row">
                    <div class="col-md-8">
                        <div class="form-group">
                            <label>@lang('clinicCore::lang.linked_user') <span class="text-danger">*</span></label>
                            <select id="doctor_user_id" class="form-control select2" style="width:100%">
                                <option value="">— Select user —</option>
                                @foreach($users as $user)
                                <option value="{{ $user->id }}"
                                    data-name="{{ $user->first_name }} {{ $user->last_name }}"
                                    data-email="{{ $user->email }}"
                                    data-phone="{{ $user->contact_no }}">
                                    {{ $user->first_name }} {{ $user->last_name }}
                                </option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label>@lang('clinicCore::lang.status')</label>
                            <select id="doctor_status" class="form-control">
                                <option value="active">@lang('clinicCore::lang.active')</option>
                                <option value="inactive">@lang('clinicCore::lang.inactive')</option>
                            </select>
                        </div>
                    </div>
                </div>
                {{-- Row 2: Auto-filled name + email + phone --}}
                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label>@lang('clinicCore::lang.doctor_name')</label>
                            <input type="text" id="doctor_name" class="form-control" readonly placeholder="Auto-filled">
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label>@lang('clinicCore::lang.email')</label>
                            <input type="email" id="doctor_email" class="form-control" readonly placeholder="Auto-filled">
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label>@lang('clinicCore::lang.mobile')</label>
                            <input type="text" id="doctor_phone" class="form-control" readonly placeholder="Auto-filled">
                        </div>
                    </div>
                </div>
                {{-- Row 3: Departments --}}
                <div class="form-group">
                    <label>@lang('clinicCore::lang.departments') <span class="text-danger">*</span>
                        <small class="text-muted">(first selected = primary)</small>
                    </label>
                    <select id="doctor_dept_ids" class="form-control select2" style="width:100%" multiple>
                        @foreach($departments as $dept)
                        <option value="{{ $dept->id }}">
                            {{ $dept->name }}{{ $dept->location ? ' / ' . $dept->location->name : '' }}
                        </option>
                        @endforeach
                    </select>
                </div>
                {{-- Row 4: Specialization + Fee --}}
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>@lang('clinicCore::lang.specialization')</label>
                            <input type="text" id="doctor_specialization" class="form-control">
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>@lang('clinicCore::lang.consultation_fee') <small style="font-weight:400;color:#94a3b8;">(overrides linked product's price when &gt; 0)</small></label>
                            <input type="number" step="0.01" id="doctor_consultation_fee" class="form-control" value="0">
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label><i class="fa fa-link"></i> Linked Consultation Product <span style="font-weight:400;color:#94a3b8;">(for POS)</span></label>
                    <select id="doctor_product_id" class="form-control" style="width:100%;"></select>
                    <small class="text-muted" style="font-size:10.5px;">Pick an ERP product to charge the visit fee from. Leave empty to fall back to the consultation_fee value above.</small>
                </div>
                <div class="form-group">
                    <label>@lang('clinicCore::lang.about')</label>
                    <textarea id="doctor_about" class="form-control" rows="2"></textarea>
                </div>
                <div class="form-group">
                    <label><i class="fa fa-paint-brush"></i> Calendar Color</label>
                    <p class="text-muted" style="margin:0 0 6px;font-size:11.5px;">
                        Color used for this doctor's appointments on the calendar. Leave blank to fall back to the appointment-type color.
                    </p>
                    <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;">
                        <input type="color" id="doctor_color" class="form-control" value="#3498db"
                               style="width:60px;height:36px;padding:2px;cursor:pointer;">
                        <input type="text" id="doctor_color_hex" class="form-control" placeholder="#3498db"
                               maxlength="7" style="width:110px;font-family:monospace;text-transform:uppercase;">
                        <button type="button" class="btn btn-default btn-sm" id="btn_doctor_color_clear" title="Clear color">
                            <i class="fa fa-times"></i> Clear
                        </button>
                        <div id="doctor_color_preview"
                             style="display:inline-flex;align-items:center;gap:6px;padding:4px 12px;border-radius:14px;color:#fff;font-size:11px;font-weight:700;background:#3498db;">
                            <i class="fas fa-calendar-check"></i> Preview
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-default" data-dismiss="modal">@lang('clinicCore::lang.cancel')</button>
                <button class="btn btn-primary" id="btn_save_doctor">@lang('clinicCore::lang.save')</button>
            </div>
        </div>
    </div>
</div>

{{-- ══════════════════════════════════════════════════════════════
     SCHEDULE MANAGEMENT MODAL
══════════════════════════════════════════════════════════════ --}}
<div class="modal fade" id="scheduleModal" tabindex="-1">
    <div class="modal-dialog" style="width:90%;max-width:900px;">
        <div class="modal-content">
            <div class="modal-header" style="background:linear-gradient(135deg,#0ea5e9,#6366f1);color:#fff;border-radius:4px 4px 0 0;">
                <button type="button" class="close" data-dismiss="modal" style="color:#fff;opacity:.8;font-size:15px;">&times;</button>
                <h4 class="modal-title">
                    <i class="fas fa-clock"></i>
                    <span id="schedule_doctor_name">Doctor</span>
                    <small style="opacity:.8;font-size:13px;margin-left:8px;">— Weekly Schedule</small>
                </h4>
            </div>
            <div class="modal-body" style="padding:0;">
                <input type="hidden" id="schedule_doctor_id">

                {{-- Tab nav --}}
                <ul class="nav nav-tabs" style="margin:0;border-bottom:2px solid #e2e8f0;padding:0 16px;">
                    <li class="active">
                        <a href="#sched_overview" data-toggle="tab" style="font-weight:600;">
                            <i class="fa fa-calendar"></i> Overview
                        </a>
                    </li>
                    <li>
                        <a href="#sched_manage" data-toggle="tab" style="font-weight:600;">
                            <i class="fa fa-cog"></i> Manage
                        </a>
                    </li>
                    @can('clinic.schedule.manage_exceptions')
                    <li>
                        <a href="#sched_exceptions" data-toggle="tab" style="font-weight:600;">
                            <i class="fa fa-calendar-times"></i> @lang('clinicCore::lang.exceptions')
                        </a>
                    </li>
                    @endcan
                </ul>

                <div class="tab-content" style="padding:16px;">

                    {{-- ── Overview Tab ── --}}
                    <div class="tab-pane active" id="sched_overview">
                        <div class="week-grid" id="week_grid">
                            {{-- Populated by JS --}}
                        </div>
                        <p class="text-muted" style="font-size:11px;margin-top:10px;">
                            <span style="display:inline-block;width:12px;height:12px;background:linear-gradient(135deg,#0ea5e9,#6366f1);border-radius:3px;vertical-align:middle;"></span> Active &nbsp;
                            <span style="display:inline-block;width:12px;height:12px;background:#94a3b8;border-radius:3px;vertical-align:middle;"></span> Inactive &nbsp;
                            Today's column is highlighted in blue.
                        </p>
                    </div>

                    {{-- ── Manage Tab ── --}}
                    <div class="tab-pane" id="sched_manage">
                        <table class="table table-bordered table-condensed" id="schedule_list_table">
                            <thead>
                                <tr>
                                    <th>Day</th>
                                    <th>Department</th>
                                    <th>Start</th>
                                    <th>End</th>
                                    <th>Slot (min)</th>
                                    <th>Status</th>
                                    <th style="width:70px;"></th>
                                </tr>
                            </thead>
                            <tbody id="schedule_list_body">
                                <tr id="schedule_empty_row"><td colspan="7" class="text-center text-muted">No schedules yet.</td></tr>
                            </tbody>
                        </table>

                        <hr style="margin:12px 0;">

                        {{-- Add / Edit form --}}
                        <input type="hidden" id="schedule_edit_id">
                        <h5 id="schedule_form_title" style="margin-top:0;"><i class="fa fa-plus"></i> Add Schedule Slot</h5>

                        <div class="form-group">
                            <label>Day <span class="text-danger">*</span>
                                <small class="text-muted" id="schedule_day_hint">(select one or more)</small>
                            </label>
                            <br>
                            <div class="btn-group" style="flex-wrap:wrap;">
                                @foreach([0=>'Sun',1=>'Mon',2=>'Tue',3=>'Wed',4=>'Thu',5=>'Fri',6=>'Sat'] as $val => $label)
                                <label class="btn btn-default btn-sm" style="margin:2px;">
                                    <input type="checkbox" class="day-check" value="{{ $val }}"> {{ $label }}
                                </label>
                                @endforeach
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label>Department</label>
                                    <select id="new_schedule_dept" class="form-control">
                                        <option value="">— Any (all depts) —</option>
                                        @foreach($departments as $dept)
                                        <option value="{{ $dept->id }}">
                                            {{ $dept->name }}{{ $dept->location ? ' / '.$dept->location->name : '' }}
                                        </option>
                                        @endforeach
                                    </select>
                                    <small class="text-muted">Leave "Any" = fallback for all departments</small>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label>Start Time <span class="text-danger">*</span></label>
                                    <input type="time" id="new_schedule_start" class="form-control" value="09:00">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label>End Time <span class="text-danger">*</span></label>
                                    <input type="time" id="new_schedule_end" class="form-control" value="17:00">
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="form-group">
                                    <label>Slot (min) <span class="text-danger">*</span></label>
                                    <input type="number" id="new_schedule_slot" class="form-control" value="30" min="5" max="480" step="5">
                                </div>
                            </div>
                        </div>

                        {{-- SIFA P3-T7 — advanced pattern fields (all optional) --}}
                        <div class="row">
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label>@lang('clinicCore::lang.effective_from')</label>
                                    <input type="date" id="new_schedule_eff_from" class="form-control">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label>@lang('clinicCore::lang.effective_to')</label>
                                    <input type="date" id="new_schedule_eff_to" class="form-control">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label>@lang('clinicCore::lang.break_from')</label>
                                    <input type="time" id="new_schedule_break_from" class="form-control">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label>@lang('clinicCore::lang.break_to')</label>
                                    <input type="time" id="new_schedule_break_to" class="form-control">
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label>@lang('clinicCore::lang.max_per_slot')</label>
                                    <input type="number" id="new_schedule_max_per_slot" class="form-control" value="1" min="1" max="99" step="1">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label>@lang('clinicCore::lang.overbooking')</label>
                                    <div class="checkbox" style="margin-top:6px;">
                                        <label><input type="checkbox" id="new_schedule_overbooking_allowed"> @lang('clinicCore::lang.overbooking_allowed')</label>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label>@lang('clinicCore::lang.overbooking_max')</label>
                                    <input type="number" id="new_schedule_overbooking_max" class="form-control" value="0" min="0" max="99" step="1">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label>@lang('clinicCore::lang.branch')</label>
                                    <select id="new_schedule_location" class="form-control">
                                        <option value="">— @lang('clinicCore::lang.any') —</option>
                                        @foreach(\App\BusinessLocation::where('business_id', session('user.business_id'))->get(['id','name']) as $bl)
                                        <option value="{{ $bl->id }}">{{ $bl->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>
                        </div>
                        <p class="text-muted" style="font-size:11px;margin-top:-4px;">
                            @lang('clinicCore::lang.pattern_fields_hint')
                        </p>

                        <button class="btn btn-success btn-sm" id="btn_add_schedule">
                            <i class="fa fa-plus"></i> Add Slot(s)
                        </button>
                        <button class="btn btn-default btn-sm" id="btn_cancel_schedule_edit" style="display:none;">
                            <i class="fa fa-times"></i> Cancel Edit
                        </button>
                    </div>{{-- /sched_manage --}}

                    {{-- ── Exceptions Tab (SIFA P3-T7) ── --}}
                    @can('clinic.schedule.manage_exceptions')
                    <div class="tab-pane" id="sched_exceptions">
                        <p class="text-muted" style="font-size:12px;">
                            @lang('clinicCore::lang.exceptions_hint')
                        </p>
                        <table class="table table-bordered table-condensed" id="exception_list_table">
                            <thead>
                                <tr>
                                    <th>@lang('clinicCore::lang.date')</th>
                                    <th>@lang('clinicCore::lang.type')</th>
                                    <th>@lang('clinicCore::lang.from')</th>
                                    <th>@lang('clinicCore::lang.to')</th>
                                    <th>@lang('clinicCore::lang.reason')</th>
                                    <th style="width:50px;"></th>
                                </tr>
                            </thead>
                            <tbody id="exception_list_body">
                                <tr id="exception_empty_row"><td colspan="6" class="text-center text-muted">@lang('clinicCore::lang.no_exceptions')</td></tr>
                            </tbody>
                        </table>

                        <hr style="margin:12px 0;">
                        <h5 style="margin-top:0;"><i class="fa fa-plus"></i> @lang('clinicCore::lang.add_exception')</h5>
                        <div class="row">
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label>@lang('clinicCore::lang.date') <span class="text-danger">*</span></label>
                                    <input type="date" id="exc_date" class="form-control">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label>@lang('clinicCore::lang.type') <span class="text-danger">*</span></label>
                                    <select id="exc_type" class="form-control">
                                        <option value="unavailable">@lang('clinicCore::lang.exc_unavailable')</option>
                                        <option value="modified">@lang('clinicCore::lang.exc_modified')</option>
                                        <option value="extra">@lang('clinicCore::lang.exc_extra')</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="form-group">
                                    <label>@lang('clinicCore::lang.from')</label>
                                    <input type="time" id="exc_start" class="form-control">
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="form-group">
                                    <label>@lang('clinicCore::lang.to')</label>
                                    <input type="time" id="exc_end" class="form-control">
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="form-group">
                                    <label>&nbsp;</label>
                                    <button class="btn btn-success btn-sm btn-block" id="btn_add_exception">
                                        <i class="fa fa-plus"></i> @lang('clinicCore::lang.add')
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label>@lang('clinicCore::lang.reason')</label>
                            <input type="text" id="exc_reason" class="form-control" placeholder="@lang('clinicCore::lang.optional')">
                        </div>
                    </div>{{-- /sched_exceptions --}}
                    @endcan

                </div>{{-- /tab-content --}}
            </div>
            <div class="modal-footer">
                <button class="btn btn-default" data-dismiss="modal">@lang('clinicCore::lang.close')</button>
            </div>
        </div>
    </div>
</div>
@endsection

@section('javascript')
@include('clinicCore::partials.product_picker_js')
<script>
var dayNames = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];

/* Init non-modal select2s */
$('#doctor_user_id').select2({ width: '100%', dropdownParent: $('#doctorModal') });
$('#doctor_dept_ids').select2({ width: '100%', dropdownParent: $('#doctorModal'), placeholder: 'Select departments...' });

$('#doctorModal').on('shown.bs.modal', function () {
    $('#doctor_dept_ids').select2({ width: '100%', dropdownParent: $('#doctorModal'), placeholder: 'Select departments...' });
    $('#doctor_user_id').select2({ width: '100%', dropdownParent: $('#doctorModal'), placeholder: '— None —', allowClear: true });
});

/* ── Doctors DataTable ─────────────────────────── */
var doctorTable = $('#doctors_table').DataTable({
    processing: true,
    serverSide: true,
    ajax: '{{ route('clinic.doctors.list') }}',
    columns: [
        { data: 'doctor_info',       name: 'name', orderable: true },
        { data: 'departments_list',  name: 'departments_list', orderable: false, searchable: false },
        { data: 'appointments_col',  name: 'appointments_count', orderable: true, searchable: false },
        { data: 'product_badge',     name: 'product_id', orderable: false, searchable: false },
        { data: 'status_badge',      name: 'status', orderable: false },
        { data: 'action',            name: 'action', orderable: false, searchable: false }
    ]
});

/* ── Auto-fill from selected user ─────────────── */
$('#doctor_user_id').on('change', function () {
    var $opt = $(this).find('option:selected');
    var uid  = $(this).val();
    $(this).next('.select2-container').find('.select2-selection').css('border-color', '');
    if (uid) {
        $('#doctor_name').val($opt.data('name'));
        $('#doctor_email').val($opt.data('email'));
        $('#doctor_phone').val($opt.data('phone') || '');
    } else {
        $('#doctor_name, #doctor_email, #doctor_phone').val('');
    }
});

/* ── Save doctor ───────────────────────────────── */
$('#btn_save_doctor').on('click', function () {
    if (!$('#doctor_user_id').val()) {
        toastr.error('Please select a linked system user.');
        $('#doctor_user_id').next('.select2-container').find('.select2-selection').css('border-color','red');
        return;
    }
    var id  = $('#doctor_id').val();
    var url = id ? '{{ url('clinic/doctors') }}/' + id + '/update' : '{{ route('clinic.doctors.store') }}';
    $.ajax({
        url: url, method: 'POST',
        data: {
            _token:           '{{ csrf_token() }}',
            name:             $('#doctor_name').val(),
            email:            $('#doctor_email').val(),
            phone:            $('#doctor_phone').val(),
            dept_ids:         $('#doctor_dept_ids').val(),
            specialization:   $('#doctor_specialization').val(),
            consultation_fee: $('#doctor_consultation_fee').val(),
            user_id:          $('#doctor_user_id').val(),
            status:           $('#doctor_status').val(),
            about:            $('#doctor_about').val(),
            color:            $('#doctor_color_hex').val() || null,
            product_id:       $('#doctor_product_id').val() || null
        },
        success: function (res) {
            if (res.success) {
                $('#doctorModal').modal('hide');
                doctorTable.ajax.reload();
                toastr.success(res.msg);
            }
        },
        error: function (xhr) { toastr.error(xhr.responseJSON?.message ?? 'Error'); }
    });
});

/* ── Edit doctor ───────────────────────────────── */
$(document).on('click', '.btn-edit-doctor', function () {
    var id = $(this).data('id');
    $.get('{{ url('clinic/doctors') }}/' + id + '/edit', function (data) {
        $('#doctor_id').val(data.id);
        $('#doctor_dept_ids').val(data.dept_ids).trigger('change');
        $('#doctor_specialization').val(data.specialization);
        $('#doctor_consultation_fee').val(data.consultation_fee);
        $('#doctor_status').val(data.status);
        $('#doctor_about').val(data.about);
        $('#doctor_user_id').val(data.user_id || '').trigger('change');
        // auto-fill from stored snapshot (in case user option data-attrs differ)
        $('#doctor_name').val(data.name);
        $('#doctor_email').val(data.email);
        $('#doctor_phone').val(data.phone);
        var clr = data.color || '';
        $('#doctor_color_hex').val(clr ? clr.toUpperCase() : '');
        $('#doctor_color').val(clr || '#3498db');
        updateDoctorColorPreview(clr);
        if (window.drmInitProductPicker) window.drmInitProductPicker('#doctor_product_id', data.product_id || '');
        $('#doctorModalTitle').text('@lang('clinicCore::lang.edit')');
        $('#doctorModal').modal('show');
    });
});

// Init product picker on modal show for add-new
$('#doctorModal').on('shown.bs.modal', function (e) {
    if (!$('#doctor_product_id').hasClass('select2-hidden-accessible') && window.drmInitProductPicker) {
        window.drmInitProductPicker('#doctor_product_id', '');
    }
});

/* ── Doctor color picker sync ──────────────────── */
function updateDoctorColorPreview(hex) {
    var c = hex && /^#[0-9A-Fa-f]{6}$/.test(hex) ? hex : '#3498db';
    $('#doctor_color_preview').css('background', c);
}
$('#doctor_color').on('input change', function () {
    var v = $(this).val().toUpperCase();
    $('#doctor_color_hex').val(v);
    updateDoctorColorPreview(v);
});
$('#doctor_color_hex').on('input change', function () {
    var v = $(this).val().trim();
    if (v && !v.startsWith('#')) v = '#' + v;
    v = v.toUpperCase();
    $(this).val(v);
    if (/^#[0-9A-F]{6}$/.test(v)) $('#doctor_color').val(v);
    updateDoctorColorPreview(v);
});
$('#btn_doctor_color_clear').on('click', function () {
    $('#doctor_color_hex').val('');
    $('#doctor_color').val('#3498db');
    updateDoctorColorPreview('');
});

// Reset color fields when modal opens via "Add Doctor" (not edit)
$('#doctorModal').on('show.bs.modal', function (e) {
    var triggered = $(e.relatedTarget);
    if (triggered.length && !triggered.hasClass('btn-edit-doctor')) {
        // It's an "add new" trigger — reset color fields
        $('#doctor_color_hex').val('');
        $('#doctor_color').val('#3498db');
        updateDoctorColorPreview('');
    }
});

/* ── Delete doctor ─────────────────────────────── */
$(document).on('click', '.btn-delete-doctor', function () {
    if (!confirm('@lang('clinicCore::lang.are_you_sure')')) return;
    var id = $(this).data('id');
    $.ajax({
        url: '{{ url('clinic/doctors') }}/' + id,
        method: 'DELETE',
        data: { _token: '{{ csrf_token() }}' },
        success: function (res) {
            if (res.success) { doctorTable.ajax.reload(); toastr.success(res.msg); }
        }
    });
});

/* ── Open schedule modal ───────────────────────── */
$(document).on('click', '.btn-schedule-doctor', function () {
    var id   = $(this).data('id');
    var name = $(this).data('name');
    $('#schedule_doctor_id').val(id);
    $('#schedule_doctor_name').text(name);
    loadSchedules(id);
    if (typeof loadExceptions === 'function') { loadExceptions(id); }
    $('#scheduleModal').modal('show');
});

function slotCount(start, end, slotMin) {
    var s = start.split(':'), e = end.split(':');
    var mins = (parseInt(e[0])*60 + parseInt(e[1])) - (parseInt(s[0])*60 + parseInt(s[1]));
    return mins > 0 ? Math.floor(mins / slotMin) : 0;
}

function renderWeekGrid(data) {
    var today   = new Date().getDay();
    var byDay   = {};
    data.forEach(function(s) {
        if (!byDay[s.day_of_week]) byDay[s.day_of_week] = [];
        byDay[s.day_of_week].push(s);
    });

    var html = '';
    for (var d = 0; d < 7; d++) {
        var isToday = (d === today);
        var slots   = byDay[d] || [];
        html += '<div class="day-col">';
        html += '<div class="day-col-header' + (isToday ? ' is-today' : '') + '">'
             + dayNames[d].substring(0,3)
             + (isToday ? '<br><small style="font-weight:400;font-size:9px;">Today</small>' : '')
             + '</div>';
        html += '<div class="day-col-body">';

        if (!slots.length) {
            html += '<div class="day-off"><i class="fa fa-moon"></i>Off</div>';
        } else {
            slots.forEach(function(s) {
                var deptLabel = s.department ? s.department.name : 'All Depts';
                var inactive  = s.status !== 'active';
                var count     = slotCount(s.start_time.substring(0,5), s.end_time.substring(0,5), s.slot_duration_minutes);
                html += '<div class="sched-block' + (inactive ? ' inactive-block' : '') + '" '
                     + 'data-sid="' + s.id + '" '
                     + 'data-day="' + s.day_of_week + '" '
                     + 'data-dept="' + (s.department_id || '') + '" '
                     + 'data-start="' + s.start_time.substring(0,5) + '" '
                     + 'data-end="' + s.end_time.substring(0,5) + '" '
                     + 'data-slot="' + s.slot_duration_minutes + '" '
                     + 'data-status="' + s.status + '" '
                     + 'title="Click to edit" style="cursor:pointer;">';
                if (inactive) html += '<span class="inactive-badge">off</span>';
                html += '<div class="time-range">' + s.start_time.substring(0,5) + ' – ' + s.end_time.substring(0,5) + '</div>';
                html += '<span class="slot-pill"><i class="fa fa-clock"></i> ' + s.slot_duration_minutes + ' min</span>';
                html += '<span class="dept-pill"><i class="fa fa-hospital"></i> ' + deptLabel + '</span>';
                html += '<div class="slot-count">' + count + ' slots / day</div>';
                html += '</div>';
            });
        }

        html += '</div></div>';
    }
    $('#week_grid').html(html);
}

var scheduleCache = {}; // SIFA P3-T7 — sid → full schedule row (for edit prefill)

function loadSchedules(doctorId) {
    $.get('{{ url('clinic/doctors') }}/' + doctorId + '/schedules', function (data) {
        // ── Cache full rows for the advanced-fields edit prefill ──
        scheduleCache = {};
        data.forEach(function (s) { scheduleCache[s.id] = s; });

        // ── Render overview grid ──
        renderWeekGrid(data);

        // ── Render manage table ──
        var $body = $('#schedule_list_body').empty();
        if (!data.length) {
            $body.html('<tr id="schedule_empty_row"><td colspan="7" class="text-center text-muted">No schedules yet.</td></tr>');
            return;
        }
        data.forEach(function (s) {
            var deptName    = s.department ? s.department.name : '—';
            var deptId      = s.department_id || '';
            var statusBadge = '<span class="label label-' + (s.status === 'active' ? 'success' : 'danger') + '">' + s.status + '</span>';
            var actions = '<button class="btn btn-xs btn-primary btn-edit-schedule" '
                + 'data-sid="'   + s.id + '" '
                + 'data-day="'   + s.day_of_week + '" '
                + 'data-dept="'  + deptId + '" '
                + 'data-start="' + s.start_time.substring(0,5) + '" '
                + 'data-end="'   + s.end_time.substring(0,5) + '" '
                + 'data-slot="'  + s.slot_duration_minutes + '" '
                + 'data-status="'+ s.status + '" '
                + 'title="Edit"><i class="fa fa-edit"></i></button> '
                + '<button class="btn btn-xs btn-danger btn-delete-schedule" data-sid="' + s.id + '" title="Delete"><i class="fa fa-trash"></i></button>';

            $body.append('<tr class="schedule-row" data-sid="' + s.id + '">'
                + '<td><span class="day-badge">' + (dayNames[s.day_of_week] || s.day_of_week) + '</span></td>'
                + '<td>' + deptName + '</td>'
                + '<td>' + s.start_time.substring(0,5) + '</td>'
                + '<td>' + s.end_time.substring(0,5) + '</td>'
                + '<td>' + s.slot_duration_minutes + '</td>'
                + '<td>' + statusBadge + '</td>'
                + '<td>' + actions + '</td>'
                + '</tr>');
        });
    });
}

/* ── Click block in overview → switch to manage tab + prefill ── */
$(document).on('click', '.sched-block', function () {
    var s = $(this).data();
    // Switch to manage tab
    $('#scheduleModal .nav-tabs a[href="#sched_manage"]').tab('show');
    // Trigger edit
    $('.day-check').prop('checked', false).closest('label').removeClass('active');
    $('.day-check[value="' + s.day + '"]').prop('checked', true).closest('label').addClass('active');
    $('#new_schedule_dept').val(s.dept || '');
    $('#new_schedule_start').val(s.start);
    $('#new_schedule_end').val(s.end);
    $('#new_schedule_slot').val(s.slot);
    $('#schedule_edit_id').val(s.sid);
    $('#schedule_form_title').html('<i class="fa fa-edit"></i> Edit Schedule Slot');
    $('#schedule_day_hint').text('(editing single record)');
    $('#btn_add_schedule').html('<i class="fa fa-save"></i> Update Slot').removeClass('btn-success').addClass('btn-warning');
    $('#btn_cancel_schedule_edit').show();
});

function resetScheduleForm() {
    $('#schedule_edit_id').val('');
    $('.day-check').prop('checked', false).closest('label').removeClass('active');
    $('#new_schedule_dept').val('');
    $('#new_schedule_start').val('09:00');
    $('#new_schedule_end').val('17:00');
    $('#new_schedule_slot').val('30');
    // SIFA P3-T7 — reset advanced pattern fields
    $('#new_schedule_eff_from, #new_schedule_eff_to, #new_schedule_break_from, #new_schedule_break_to').val('');
    $('#new_schedule_max_per_slot').val('1');
    $('#new_schedule_overbooking_allowed').prop('checked', false);
    $('#new_schedule_overbooking_max').val('0');
    $('#new_schedule_location').val('');
    $('#schedule_form_title').html('<i class="fa fa-plus"></i> Add Schedule Slot');
    $('#schedule_day_hint').text('(select one or more)');
    $('#btn_add_schedule').html('<i class="fa fa-plus"></i> Add Slot(s)').removeClass('btn-warning').addClass('btn-success');
    $('#btn_cancel_schedule_edit').hide();
}

/* ── Edit schedule ─────────────────────────────── */
$(document).on('click', '.btn-edit-schedule', function () {
    var s = $(this).data();
    $('#schedule_edit_id').val(s.sid);

    // Set single day
    $('.day-check').prop('checked', false).closest('label').removeClass('active');
    var $dayChk = $('.day-check[value="' + s.day + '"]');
    $dayChk.prop('checked', true).closest('label').addClass('active');

    $('#new_schedule_dept').val(s.dept || '');
    $('#new_schedule_start').val(s.start);
    $('#new_schedule_end').val(s.end);
    $('#new_schedule_slot').val(s.slot);

    // SIFA P3-T7 — prefill advanced pattern fields from the cached full row.
    var full = scheduleCache[s.sid] || {};
    $('#new_schedule_eff_from').val(full.effective_from ? String(full.effective_from).substring(0,10) : '');
    $('#new_schedule_eff_to').val(full.effective_to ? String(full.effective_to).substring(0,10) : '');
    $('#new_schedule_break_from').val(full.break_from ? String(full.break_from).substring(0,5) : '');
    $('#new_schedule_break_to').val(full.break_to ? String(full.break_to).substring(0,5) : '');
    $('#new_schedule_max_per_slot').val(full.max_per_slot || 1);
    $('#new_schedule_overbooking_allowed').prop('checked', !!Number(full.overbooking_allowed));
    $('#new_schedule_overbooking_max').val(full.overbooking_max || 0);
    $('#new_schedule_location').val(full.location_id || '');

    $('#schedule_form_title').html('<i class="fa fa-edit"></i> Edit Schedule Slot');
    $('#schedule_day_hint').text('(editing single record)');
    $('#btn_add_schedule').html('<i class="fa fa-save"></i> Update Slot').removeClass('btn-success').addClass('btn-warning');
    $('#btn_cancel_schedule_edit').show();

    // Scroll to form
    document.getElementById('schedule_form_title').scrollIntoView({ behavior: 'smooth' });
});

$('#btn_cancel_schedule_edit').on('click', resetScheduleForm);

/* ── Add / Update schedule slot ────────────────── */
$('#btn_add_schedule').on('click', function () {
    var doctorId = $('#schedule_doctor_id').val();
    var editId   = $('#schedule_edit_id').val();
    if (!doctorId) return;

    var selectedDays = $('.day-check:checked').map(function () { return $(this).val(); }).get();
    if (!selectedDays.length) { toastr.error('Please select at least one day.'); return; }

    var start = $('#new_schedule_start').val();
    var end   = $('#new_schedule_end').val();
    var slot  = $('#new_schedule_slot').val();
    var dept  = $('#new_schedule_dept').val();

    if (!start || !end || !slot) { toastr.error('Please fill start time, end time and slot duration.'); return; }
    if (start >= end)            { toastr.error('End time must be after start time.'); return; }

    // SIFA P3-T7 — advanced pattern fields (all optional)
    var patternFields = {
        effective_from:      $('#new_schedule_eff_from').val() || '',
        effective_to:        $('#new_schedule_eff_to').val() || '',
        break_from:          $('#new_schedule_break_from').val() || '',
        break_to:            $('#new_schedule_break_to').val() || '',
        max_per_slot:        $('#new_schedule_max_per_slot').val() || 1,
        overbooking_allowed: $('#new_schedule_overbooking_allowed').is(':checked') ? 1 : 0,
        overbooking_max:     $('#new_schedule_overbooking_max').val() || 0,
        location_id:         $('#new_schedule_location').val() || '',
    };

    if (editId) {
        // UPDATE existing record (single day)
        $.ajax({
            url:    '{{ url('clinic/doctors/schedules') }}/' + editId,
            method: 'POST',
            data: Object.assign({
                _token:                '{{ csrf_token() }}',
                day_of_week:           selectedDays[0],
                department_id:         dept,
                start_time:            start,
                end_time:              end,
                slot_duration_minutes: slot,
            }, patternFields),
            success: function (res) {
                if (res.success) { toastr.success(res.msg); loadSchedules(doctorId); resetScheduleForm(); }
            },
            error: function (xhr) { toastr.error(xhr.responseJSON?.message ?? 'Error'); }
        });
    } else {
        // CREATE — one record per selected day
        var requests = selectedDays.map(function (day) {
            return $.ajax({
                url:    '{{ url('clinic/doctors') }}/' + doctorId + '/schedules/store',
                method: 'POST',
                data: Object.assign({
                    _token:                '{{ csrf_token() }}',
                    day_of_week:           day,
                    department_id:         dept,
                    start_time:            start,
                    end_time:              end,
                    slot_duration_minutes: slot,
                }, patternFields)
            });
        });
        $.when.apply($, requests)
            .done(function () {
                toastr.success(selectedDays.length + ' schedule slot(s) saved.');
                loadSchedules(doctorId);
                resetScheduleForm();
                $('#scheduleModal .nav-tabs a[href="#sched_overview"]').tab('show');
            })
            .fail(function (xhr) { toastr.error(xhr.responseJSON?.message ?? 'Error saving schedules.'); });
    }
});

/* ── Delete schedule slot ──────────────────────── */
$(document).on('click', '.btn-delete-schedule', function () {
    if (!confirm('@lang('clinicCore::lang.are_you_sure')')) return;
    var sid      = $(this).data('sid');
    var doctorId = $('#schedule_doctor_id').val();
    $.ajax({
        url:    '{{ url('clinic/doctors/schedules') }}/' + sid,
        method: 'DELETE',
        data:   { _token: '{{ csrf_token() }}' },
        success: function (res) {
            if (res.success) {
                toastr.success(res.msg);
                loadSchedules(doctorId);
                resetScheduleForm();
                $('#scheduleModal .nav-tabs a[href="#sched_overview"]').tab('show');
            }
        }
    });
});

@can('clinic.schedule.manage_exceptions')
/* ── Schedule exceptions (SIFA P3-T7) ──────────── */
var excTypeLabels = {
    unavailable: '@lang('clinicCore::lang.exc_unavailable')',
    modified:    '@lang('clinicCore::lang.exc_modified')',
    extra:       '@lang('clinicCore::lang.exc_extra')'
};
function loadExceptions(doctorId) {
    $.get('{{ url('clinic/doctors') }}/' + doctorId + '/schedule-exceptions', function (rows) {
        var $body = $('#exception_list_body').empty();
        if (!rows.length) {
            $body.html('<tr id="exception_empty_row"><td colspan="6" class="text-center text-muted">@lang('clinicCore::lang.no_exceptions')</td></tr>');
            return;
        }
        rows.forEach(function (e) {
            $body.append('<tr>'
                + '<td>' + e.date + '</td>'
                + '<td>' + (excTypeLabels[e.type] || e.type) + '</td>'
                + '<td>' + (e.start_time || '—') + '</td>'
                + '<td>' + (e.end_time || '—') + '</td>'
                + '<td>' + (e.reason ? $('<div>').text(e.reason).html() : '—') + '</td>'
                + '<td><button class="btn btn-xs btn-danger btn-delete-exception" data-id="' + e.id + '"><i class="fa fa-trash"></i></button></td>'
                + '</tr>');
        });
    });
}
$('#btn_add_exception').on('click', function () {
    var doctorId = $('#schedule_doctor_id').val();
    if (!doctorId) return;
    var type = $('#exc_type').val();
    var start = $('#exc_start').val();
    var end   = $('#exc_end').val();
    if (!$('#exc_date').val()) { toastr.error('@lang('clinicCore::lang.date') required.'); return; }
    if ((type === 'modified' || type === 'extra') && (!start || !end)) {
        toastr.error('@lang('clinicCore::lang.exc_window_required')'); return;
    }
    $.ajax({
        url:    '{{ url('clinic/doctors') }}/' + doctorId + '/schedule-exceptions',
        method: 'POST',
        data: {
            _token:     '{{ csrf_token() }}',
            date:       $('#exc_date').val(),
            type:       type,
            start_time: start,
            end_time:   end,
            reason:     $('#exc_reason').val(),
        },
        success: function (res) {
            if (res.success) {
                toastr.success(res.msg);
                loadExceptions(doctorId);
                $('#exc_date, #exc_start, #exc_end, #exc_reason').val('');
                $('#exc_type').val('unavailable');
            }
        },
        error: function (xhr) { toastr.error(xhr.responseJSON?.msg ?? 'Error'); }
    });
});
$(document).on('click', '.btn-delete-exception', function () {
    if (!confirm('@lang('clinicCore::lang.are_you_sure')')) return;
    var id = $(this).data('id');
    var doctorId = $('#schedule_doctor_id').val();
    $.ajax({
        url:    '{{ url('clinic/doctors/schedule-exceptions') }}/' + id,
        method: 'DELETE',
        data:   { _token: '{{ csrf_token() }}' },
        success: function (res) { if (res.success) { toastr.success(res.msg); loadExceptions(doctorId); } }
    });
});
@endcan

/* ── Reset schedule modal on close ───────────── */
$('#scheduleModal').on('hidden.bs.modal', resetScheduleForm);

/* ── Reset doctor modal on close ──────────────── */
$('#doctorModal').on('hidden.bs.modal', function () {
    $('#doctor_id').val('');
    $('#doctor_name, #doctor_email, #doctor_phone, #doctor_specialization, #doctor_about').val('');
    $('#doctor_consultation_fee').val('0');
    $('#doctor_dept_ids').val([]).trigger('change');
    $('#doctor_user_id').val('').trigger('change');
    $('#doctor_status').val('active');
    $('#doctorModalTitle').text('@lang('clinicCore::lang.add_doctor')');
});
</script>
@endsection
