@extends('layouts.app')

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

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

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

<section class="content">
    <div class="row" style="margin-bottom:10px;">
        <div class="col-md-12">
            <div class="alert alert-info alert-sm" style="padding:6px 12px;margin-bottom:0;">
                <i class="fa fa-info-circle"></i>
                Medicines are a reference catalogue for prescriptions only.
                All purchasing, selling, and stock tracking is handled through the
                <strong>ERP default sell/purchase modules</strong>.
                Optionally link each medicine to an ERP product to create a unified record.
            </div>
        </div>
    </div>

    <div class="row" style="margin-bottom:10px;">
        <div class="col-md-12">
            @can('clinic.manage_medicines')
            <button class="btn btn-primary pull-right" data-toggle="modal" data-target="#medicineModal"
                    id="btn_open_add_medicine">
                <i class="fa fa-plus"></i> @lang('clinicCore::lang.add_new')
            </button>
            @endcan
        </div>
    </div>

    <div class="row">
        <div class="col-md-12">
            @component('components.widget', ['class' => 'box-primary'])
                <table class="table table-bordered table-striped" id="medicines_table">
                    <thead>
                        <tr>
                            <th>@lang('clinicCore::lang.name')</th>
                            <th>Generic Name</th>
                            <th>Category</th>
                            <th>Company</th>
                            <th>Unit</th>
                            <th>ERP Product</th>
                            <th>@lang('clinicCore::lang.status')</th>
                            <th>@lang('clinicCore::lang.actions')</th>
                        </tr>
                    </thead>
                </table>
            @endcomponent
        </div>
    </div>
</section>

{{-- Add/Edit Medicine Modal --}}
<div class="modal fade" id="medicineModal" 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="medicine_modal_title">Add Medicine</h4>
            </div>
            <div class="modal-body">
                <input type="hidden" id="medicine_id">

                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>@lang('clinicCore::lang.name') <span class="text-danger">*</span></label>
                            <input type="text" id="med_name" class="form-control" required>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Generic Name</label>
                            <input type="text" id="med_generic_name" class="form-control">
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Category</label>
                            <select id="med_category_id" class="form-control select2-cat" style="width:100%">
                                <option value="">— None —</option>
                                @foreach($categories as $cat)
                                <option value="{{ $cat->id }}">{{ $cat->name }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label>Company / Manufacturer</label>
                            <input type="text" id="med_company" class="form-control">
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label>Unit</label>
                            <input type="text" id="med_unit" class="form-control" placeholder="e.g. mg, ml, tab">
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label>@lang('clinicCore::lang.status')</label>
                            <select id="med_status" class="form-control">
                                <option value="active">Active</option>
                                <option value="inactive">Inactive</option>
                            </select>
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <label>
                        Link to ERP Product
                        <small class="text-muted">(optional — for sell/purchase tracking)</small>
                    </label>
                    <select id="med_product_id" class="form-control" style="width:100%">
                        <option value=""></option>
                    </select>
                    <p class="help-block" style="margin-bottom:0;">
                        Search existing ERP products, or leave blank and create the product manually in
                        the ERP product catalogue later.
                    </p>
                </div>

                <div class="form-group">
                    <label>Description</label>
                    <textarea id="med_description" class="form-control" rows="2"></textarea>
                </div>

                @can('clinic.manage_controlled')
                <div class="form-group" style="margin-bottom:0;padding:10px 12px;background:#fff7ed;border:1px solid #fed7aa;border-radius:7px;">
                    <label style="color:#9a3412;">
                        <i class="fa fa-shield-alt"></i> Controlled Substance Schedule
                        <small class="text-muted">(leave blank if this is NOT a controlled drug)</small>
                    </label>
                    <select id="med_controlled_schedule" class="form-control">
                        <option value="">— Not controlled —</option>
                        @foreach(\Modules\ClinicCore\Entities\ClcMedicine::schedules() as $key => $cfg)
                            <option value="{{ $key }}">{{ $cfg['label'] }}</option>
                        @endforeach
                    </select>
                    <p class="help-block" style="margin:5px 0 0;font-size:11px;color:#9a3412;">
                        Once set, every IN / OUT for this medicine must be logged in the Controlled Drug Register.
                    </p>
                </div>
                @endcan
            </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_medicine">
                    <i class="fa fa-save"></i> @lang('clinicCore::lang.save')
                </button>
            </div>
        </div>
    </div>
</div>
@endsection

@section('javascript')
<script>
var medicinesTable = $('#medicines_table').DataTable({
    processing: true,
    serverSide: true,
    ajax: '{{ route('clinic.medicines.list') }}',
    columns: [
        { data: 'name',          name: 'name' },
        { data: 'generic_name',  name: 'generic_name' },
        { data: 'category_name', name: 'category_name', orderable: false },
        { data: 'company',       name: 'company' },
        { data: 'unit',          name: 'unit' },
        { data: 'product_col',   name: 'product_col', orderable: false },
        { data: 'status_badge',  name: 'status', orderable: false },
        { data: 'action',        name: 'action', orderable: false, searchable: false }
    ]
});

// Select2 for category inside modal
$('.select2-cat').select2({ width: '100%', dropdownParent: $('#medicineModal') });

// Select2 AJAX for ERP product search
$('#med_product_id').select2({
    width: '100%',
    minimumInputLength: 1,
    allowClear: true,
    placeholder: 'Search ERP products by name or SKU…',
    dropdownParent: $('#medicineModal'),
    ajax: {
        url: '{{ route('clinic.medicines.product-search') }}',
        dataType: 'json',
        delay: 300,
        data: function (p) { return { q: p.term }; },
        processResults: function (data) { return { results: data }; }
    },
    language: {
        inputTooShort: function () { return 'Type to search products…'; },
        noResults:     function () { return 'No ERP products found'; },
        searching:     function () { return 'Searching…'; }
    }
});

// Open add modal
$('#btn_open_add_medicine').on('click', function () {
    $('#medicine_modal_title').text('Add Medicine');
    $('#medicine_id').val('');
    $('#med_name,#med_generic_name,#med_company,#med_unit,#med_description').val('');
    $('#med_category_id').val('').trigger('change');
    $('#med_product_id').val(null).trigger('change');
    $('#med_status').val('active');
    $('#med_controlled_schedule').val('');
});

// Edit medicine
$(document).on('click', '.btn-edit-medicine', function () {
    var id = $(this).data('id');
    $.get('{{ url('clinic/medicines') }}/' + id + '/edit', function (d) {
        $('#medicine_modal_title').text('Edit Medicine');
        $('#medicine_id').val(d.id);
        $('#med_name').val(d.name);
        $('#med_generic_name').val(d.generic_name);
        $('#med_category_id').val(d.category_id).trigger('change');
        $('#med_company').val(d.company);
        $('#med_unit').val(d.unit);
        $('#med_description').val(d.description);
        $('#med_status').val(d.status);
        $('#med_controlled_schedule').val(d.controlled_schedule || '');

        // Pre-select ERP product if linked
        if (d.product_id && d.product_name) {
            var label = d.product_name + (d.product_sku ? ' [' + d.product_sku + ']' : '');
            var opt   = new Option(label, d.product_id, true, true);
            $('#med_product_id').append(opt).trigger('change');
        } else {
            $('#med_product_id').val(null).trigger('change');
        }

        $('#medicineModal').modal('show');
    });
});

// Save medicine
$('#btn_save_medicine').on('click', function () {
    var $btn = $(this);
    var id   = $('#medicine_id').val();
    var url  = id ? '{{ url('clinic/medicines') }}/' + id : '{{ route('clinic.medicines.store') }}';
    $btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i>');

    $.ajax({
        url: url, method: id ? 'PUT' : 'POST',
        data: {
            _token:       '{{ csrf_token() }}',
            name:         $('#med_name').val(),
            generic_name: $('#med_generic_name').val(),
            category_id:  $('#med_category_id').val(),
            company:      $('#med_company').val(),
            unit:         $('#med_unit').val(),
            product_id:   $('#med_product_id').val() || '',
            description:         $('#med_description').val(),
            status:              $('#med_status').val(),
            controlled_schedule: $('#med_controlled_schedule').val() || ''
        },
        success: function (res) {
            if (res.success) {
                $('#medicineModal').modal('hide');
                toastr.success(res.msg);
                medicinesTable.ajax.reload();
            }
        },
        error: function (xhr) {
            toastr.error(xhr.responseJSON?.message ?? 'Error saving medicine.');
        },
        complete: function () {
            $btn.prop('disabled', false).html('<i class="fa fa-save"></i> @lang('clinicCore::lang.save')');
        }
    });
});

// Delete
$(document).on('click', '.btn-delete-medicine', function () {
    if (!confirm('@lang('clinicCore::lang.confirm_delete')')) return;
    var id = $(this).data('id');
    $.ajax({
        url: '{{ url('clinic/medicines') }}/' + id,
        method: 'DELETE',
        data: { _token: '{{ csrf_token() }}' },
        success: function (res) {
            if (res.success) { toastr.success(res.msg); medicinesTable.ajax.reload(); }
        }
    });
});
</script>
@endsection
