@extends('layouts.app')

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

@section('css')
@include('clinicCore::partials._mobile_responsive')
@endsection

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

<section class="content">

    <div class="row">
        <div class="col-md-12">
            @component('components.widget', ['class' => 'box-primary'])
                <div class="row" style="margin-bottom:10px;">
                    <div class="col-md-3">
                        <select id="filter_dept_status" class="form-control input-sm">
                            <option value="">All Statuses</option>
                            <option value="active">Active</option>
                            <option value="inactive">Inactive</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <select id="filter_dept_location" class="form-control input-sm">
                            <option value="">All Clinics / Locations</option>
                            @foreach($locations as $loc)
                            <option value="{{ $loc->id }}">{{ $loc->name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-5 text-right">
                        @can('clinic.access_settings')
                        <button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#departmentModal">
                            <i class="fa fa-plus"></i> @lang('clinicCore::lang.add_department')
                        </button>
                        @endcan
                    </div>
                </div>

                <table class="table table-bordered table-striped" id="departments_table">
                    <thead>
                        <tr>
                            <th>@lang('clinicCore::lang.name')</th>
                            <th>@lang('clinicCore::lang.location')</th>
                            <th>@lang('clinicCore::lang.description')</th>
                            <th>@lang('clinicCore::lang.status')</th>
                            <th>@lang('clinicCore::lang.actions')</th>
                        </tr>
                    </thead>
                </table>
            @endcomponent
        </div>
    </div>
</section>

{{-- Add/Edit Modal --}}
<div class="modal fade" id="departmentModal" tabindex="-1">
    <div class="modal-dialog">
        <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="deptModalTitle">@lang('clinicCore::lang.add_department')</h4>
            </div>
            <div class="modal-body">
                <input type="hidden" id="dept_id">
                <div class="form-group">
                    <label>@lang('clinicCore::lang.name') <span class="text-danger">*</span></label>
                    <input type="text" id="dept_name" class="form-control" required>
                </div>
                <div class="form-group">
                    <label>@lang('clinicCore::lang.location')</label>
                    <select id="dept_location_id" class="form-control select2" style="width:100%">
                        <option value="">— No Location —</option>
                        @foreach($locations as $loc)
                        <option value="{{ $loc->id }}">{{ $loc->name }}</option>
                        @endforeach
                    </select>
                    @if($locations->isEmpty())
                    <small class="text-muted">
                        No clinic locations defined yet.
                        <a href="{{ route('clinic.locations.index') }}">Add locations first</a>.
                    </small>
                    @endif
                </div>
                <div class="form-group">
                    <label>@lang('clinicCore::lang.department_icon')</label>
                    <input type="text" id="dept_icon" class="form-control" placeholder="e.g. fa-stethoscope">
                </div>
                <div class="form-group">
                    <label>@lang('clinicCore::lang.description')</label>
                    <textarea id="dept_description" class="form-control" rows="2"></textarea>
                </div>
                <div class="form-group">
                    <label>@lang('clinicCore::lang.status')</label>
                    <select id="dept_status" class="form-control">
                        <option value="active">@lang('clinicCore::lang.active')</option>
                        <option value="inactive">@lang('clinicCore::lang.inactive')</option>
                    </select>
                </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_dept">@lang('clinicCore::lang.save')</button>
            </div>
        </div>
    </div>
</div>
@endsection

@section('javascript')
<script>
$('.select2').select2({ width: '100%' });

$('#filter_dept_status, #filter_dept_location').on('change', function () {
    deptTable.ajax.reload();
});

var deptTable = $('#departments_table').DataTable({
    processing: true,
    serverSide: true,
    ajax: {
        url: '{{ route('clinic.departments.list') }}',
        data: function (d) {
            d.filter_status      = $('#filter_dept_status').val();
            d.filter_location_id = $('#filter_dept_location').val();
        }
    },
    columns: [
        { data: 'name',          name: 'name' },
        { data: 'location_name', name: 'location_name', orderable: false },
        { data: 'description',   name: 'description' },
        { data: 'status_badge',  name: 'status', orderable: false },
        { data: 'action',        name: 'action', orderable: false, searchable: false }
    ]
});

$('#btn_save_dept').on('click', function () {
    var id   = $('#dept_id').val();
    var url  = id ? '{{ url('clinic/departments') }}/' + id + '/update' : '{{ route('clinic.departments.store') }}';
    $.ajax({
        url: url, method: 'POST',
        data: {
            _token:      '{{ csrf_token() }}',
            name:        $('#dept_name').val(),
            icon:        $('#dept_icon').val(),
            description: $('#dept_description').val(),
            location_id: $('#dept_location_id').val(),
            status:      $('#dept_status').val()
        },
        success: function (res) {
            if (res.success) {
                $('#departmentModal').modal('hide');
                deptTable.ajax.reload();
                toastr.success(res.msg);
            }
        },
        error: function (xhr) { toastr.error(xhr.responseJSON?.message ?? 'Error'); }
    });
});

$(document).on('click', '.btn-edit-department', function () {
    var id = $(this).data('id');
    $.get('{{ url('clinic/departments') }}/' + id + '/edit', function (data) {
        $('#dept_id').val(data.id);
        $('#dept_name').val(data.name);
        $('#dept_icon').val(data.icon);
        $('#dept_description').val(data.description);
        $('#dept_location_id').val(data.location_id).trigger('change.select2');
        $('#dept_status').val(data.status);
        $('#deptModalTitle').text('@lang('clinicCore::lang.edit')');
        $('#departmentModal').modal('show');
    });
});

$(document).on('click', '.btn-delete-department', function () {
    if (!confirm('@lang('clinicCore::lang.are_you_sure')')) return;
    var id = $(this).data('id');
    $.ajax({
        url: '{{ url('clinic/departments') }}/' + id,
        method: 'DELETE',
        data: { _token: '{{ csrf_token() }}' },
        success: function (res) {
            if (res.success) { deptTable.ajax.reload(); toastr.success(res.msg); }
            else             { toastr.error(res.msg); }
        },
        error: function (xhr) {
            toastr.error(xhr.responseJSON?.msg ?? 'Cannot delete this department.');
        }
    });
});

$('#departmentModal').on('hidden.bs.modal', function () {
    $('#dept_id').val('');
    $('#dept_name, #dept_icon, #dept_description').val('');
    $('#dept_location_id').val('').trigger('change.select2');
    $('#dept_status').val('active');
    $('#deptModalTitle').text('@lang('clinicCore::lang.add_department')');
});
</script>
@endsection
