@extends('layouts.app')

@section('title', 'Edit Prescription')

@section('content')
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
    <div class="mb-6 flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
        <h1 class="text-3xl font-bold text-gray-800">Edit Prescription</h1>
        <a href="{{ route('prescriptions.show', $prescription->id) }}" 
           class="bg-gray-600 hover:bg-gray-700 text-white px-4 py-2 rounded">
            <i class="fas fa-arrow-left mr-2"></i>Back to Prescription
        </a>
    </div>

    <!-- Patient Information Section -->
    <div class="bg-white rounded-lg shadow p-6 mb-6">
        <h2 class="text-xl font-bold mb-4">Patient Information</h2>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            <div><strong>Name:</strong> {{ $prescription->patient->full_name }}</div>
            <div><strong>Patient ID:</strong> {{ $prescription->patient->patient_id }}</div>
            <div><strong>Identity Number:</strong> {{ $prescription->patient->identity_number ?? 'N/A' }}</div>
            <div><strong>Date of Birth:</strong> {{ $prescription->patient->date_of_birth?->format('m-d-Y') ?? 'N/A' }}</div>
            <div><strong>Age:</strong> {{ $prescription->patient->date_of_birth ? \Carbon\Carbon::parse($prescription->patient->date_of_birth)->age : 'N/A' }} years</div>
            <div><strong>Gender:</strong> {{ $prescription->patient->gender ?? 'N/A' }}</div>
            <div><strong>Payment Mode:</strong> {{ $prescription->patient->payment_mode ?? 'N/A' }}</div>
            @if($prescription->patient->payment_mode === 'Medical Aid Payment')
                <div><strong>Medical Aid:</strong> {{ $prescription->patient->medical_aid_number ?? 'N/A' }}</div>
                <div><strong>Membership Status:</strong> {{ $prescription->patient->main_member ?? 'N/A' }}</div>
            @endif
        </div>
    </div>

    <!-- Vitals Section -->
    @if($prescription->appointment && $prescription->appointment->vitals)
    <div class="bg-white rounded-lg shadow p-6 mb-6">
        <h2 class="text-xl font-bold mb-4">Patient Vitals</h2>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div class="p-3 bg-gray-50 rounded">
                <strong>Blood Pressure:</strong> {{ $prescription->appointment->vitals->blood_pressure ?? 'N/A' }} mmHg
            </div>
            <div class="p-3 bg-gray-50 rounded">
                <strong>Pulse Rate:</strong> {{ $prescription->appointment->vitals->pulse_rate ?? 'N/A' }} bpm
            </div>
            <div class="p-3 bg-gray-50 rounded">
                <strong>RBS:</strong> {{ $prescription->appointment->vitals->rbs ?? 'N/A' }} %
            </div>
            <div class="p-3 bg-gray-50 rounded">
                <strong>Resp Pattern:</strong> {{ $prescription->appointment->vitals->resp_pattern ?? 'N/A' }}
            </div>
            <div class="p-3 bg-gray-50 rounded">
                <strong>SpO2:</strong> {{ $prescription->appointment->vitals->spo2 ?? 'N/A' }} %
            </div>
            <div class="p-3 bg-gray-50 rounded">
                <strong>Temperature:</strong> {{ $prescription->appointment->vitals->temperature ?? 'N/A' }} °C
            </div>
            <div class="p-3 bg-gray-50 rounded">
                <strong>Blood Glucose:</strong> {{ $prescription->appointment->vitals->blood_glucose ?? 'N/A' }} mmol/L
            </div>
            <div class="p-3 bg-gray-50 rounded">
                <strong>BMI:</strong> {{ $prescription->appointment->vitals->bmi ?? 'N/A' }} kg/m²
            </div>
        </div>
    </div>
    @endif

    <form method="POST" action="{{ route('prescriptions.update', $prescription->id) }}" class="bg-white rounded-lg shadow p-6">
        @csrf
        @method('PUT')

        <!-- Diagnosis Section -->
        <div class="mb-6">
            <label class="block text-gray-700 text-sm font-bold mb-2">Diagnosis</label>
            <textarea name="diagnosis" rows="3" class="w-full px-3 py-2 border rounded" placeholder="Enter diagnosis...">{{ old('diagnosis', $prescription->diagnosis) }}</textarea>
        </div>

        <!-- Prescription Items Section -->
        <div class="mb-6">
            <h3 class="text-lg font-bold mb-4">Prescription Items</h3>
            <div id="items-container">
                @foreach($prescription->items as $index => $item)
                <div class="item-row mb-4 p-4 border rounded bg-gray-50">
                    <div class="grid grid-cols-1 md:grid-cols-6 gap-4 mb-4">
                        <div class="md:col-span-2">
                            <label class="block text-gray-700 text-sm font-bold mb-2">Prescription Items Rx *</label>
                            <input type="text" name="items[{{ $index }}][medicine_name]" required class="w-full px-3 py-2 border rounded medicine-autocomplete" placeholder="Type or select medicine name" list="medicine-list-{{ $index }}" autocomplete="off" value="{{ old('items.'.$index.'.medicine_name', $item->medicine_name) }}">
                            <datalist id="medicine-list-{{ $index }}">
                                @foreach($medicineNames as $medicine)
                                    <option value="{{ $medicine }}">{{ $medicine }}</option>
                                @endforeach
                            </datalist>
                        </div>
                        <div>
                            <label class="block text-gray-700 text-sm font-bold mb-2">Rx Quantity *</label>
                            <select name="items[{{ $index }}][quantity]" required class="w-full px-3 py-2 border rounded">
                                <option value="">Please Select</option>
                                @if(isset($quantityItems) && $quantityItems->count() > 0)
                                    @foreach($quantityItems as $qItem)
                                        <option value="{{ $qItem->name }}" {{ old('items.'.$index.'.quantity', $item->quantity) == $qItem->name ? 'selected' : '' }}>{{ $qItem->name }}</option>
                                    @endforeach
                                @else
                                    {{-- Fallback options --}}
                                    <option value="5ml Teaspoon" {{ old('items.'.$index.'.quantity', $item->quantity) == '5ml Teaspoon' ? 'selected' : '' }}>5ml Teaspoon</option>
                                    @for($i = 1; $i <= 40; $i++)
                                        <option value="{{ $i }} {{ $i == 1 ? 'Tablet' : 'Tablets' }}" {{ old('items.'.$index.'.quantity', $item->quantity) == ($i . ' ' . ($i == 1 ? 'Tablet' : 'Tablets')) ? 'selected' : '' }}>{{ $i }} {{ $i == 1 ? 'Tablet' : 'Tablets' }}</option>
                                    @endfor
                                    <option value="Apply" {{ old('items.'.$index.'.quantity', $item->quantity) == 'Apply' ? 'selected' : '' }}>Apply</option>
                                    <option value="Chew" {{ old('items.'.$index.'.quantity', $item->quantity) == 'Chew' ? 'selected' : '' }}>Chew</option>
                                    <option value="Dab" {{ old('items.'.$index.'.quantity', $item->quantity) == 'Dab' ? 'selected' : '' }}>Dab</option>
                                    <option value="Dissolve" {{ old('items.'.$index.'.quantity', $item->quantity) == 'Dissolve' ? 'selected' : '' }}>Dissolve</option>
                                    <option value="Drip" {{ old('items.'.$index.'.quantity', $item->quantity) == 'Drip' ? 'selected' : '' }}>Drip</option>
                                    <option value="Drop" {{ old('items.'.$index.'.quantity', $item->quantity) == 'Drop' ? 'selected' : '' }}>Drop</option>
                                    <option value="Flush" {{ old('items.'.$index.'.quantity', $item->quantity) == 'Flush' ? 'selected' : '' }}>Flush</option>
                                    <option value="Gargle" {{ old('items.'.$index.'.quantity', $item->quantity) == 'Gargle' ? 'selected' : '' }}>Gargle</option>
                                    <option value="Infuse" {{ old('items.'.$index.'.quantity', $item->quantity) == 'Infuse' ? 'selected' : '' }}>Infuse</option>
                                    <option value="Inhale" {{ old('items.'.$index.'.quantity', $item->quantity) == 'Inhale' ? 'selected' : '' }}>Inhale</option>
                                    <option value="Inject" {{ old('items.'.$index.'.quantity', $item->quantity) == 'Inject' ? 'selected' : '' }}>Inject</option>
                                    <option value="Insert" {{ old('items.'.$index.'.quantity', $item->quantity) == 'Insert' ? 'selected' : '' }}>Insert</option>
                                    <option value="Instil" {{ old('items.'.$index.'.quantity', $item->quantity) == 'Instil' ? 'selected' : '' }}>Instil</option>
                                    <option value="Massage" {{ old('items.'.$index.'.quantity', $item->quantity) == 'Massage' ? 'selected' : '' }}>Massage</option>
                                    <option value="Place between gum and cheek" {{ old('items.'.$index.'.quantity', $item->quantity) == 'Place between gum and cheek' ? 'selected' : '' }}>Place between gum and cheek</option>
                                    <option value="Place under the tongue" {{ old('items.'.$index.'.quantity', $item->quantity) == 'Place under the tongue' ? 'selected' : '' }}>Place under the tongue</option>
                                    <option value="Rinse" {{ old('items.'.$index.'.quantity', $item->quantity) == 'Rinse' ? 'selected' : '' }}>Rinse</option>
                                    <option value="Rub" {{ old('items.'.$index.'.quantity', $item->quantity) == 'Rub' ? 'selected' : '' }}>Rub</option>
                                    <option value="Soak" {{ old('items.'.$index.'.quantity', $item->quantity) == 'Soak' ? 'selected' : '' }}>Soak</option>
                                    <option value="Spray" {{ old('items.'.$index.'.quantity', $item->quantity) == 'Spray' ? 'selected' : '' }}>Spray</option>
                                    <option value="Spread" {{ old('items.'.$index.'.quantity', $item->quantity) == 'Spread' ? 'selected' : '' }}>Spread</option>
                                    <option value="Sprinkle" {{ old('items.'.$index.'.quantity', $item->quantity) == 'Sprinkle' ? 'selected' : '' }}>Sprinkle</option>
                                    <option value="Swallow" {{ old('items.'.$index.'.quantity', $item->quantity) == 'Swallow' ? 'selected' : '' }}>Swallow</option>
                                    <option value="Swish and spit" {{ old('items.'.$index.'.quantity', $item->quantity) == 'Swish and spit' ? 'selected' : '' }}>Swish and spit</option>
                                @endif
                            </select>
                        </div>
                        <div>
                            <label class="block text-gray-700 text-sm font-bold mb-2">Rx Frequency (OD/BD/TDS) *</label>
                            <select name="items[{{ $index }}][frequency]" required class="w-full px-3 py-2 border rounded">
                                <option value="">Please Select</option>
                                @if(isset($frequencyItems) && $frequencyItems->count() > 0)
                                    @foreach($frequencyItems as $fItem)
                                        <option value="{{ $fItem->name }}" {{ old('items.'.$index.'.frequency', $item->frequency) == $fItem->name ? 'selected' : '' }}>{{ $fItem->name }}</option>
                                    @endforeach
                                @else
                                    {{-- Fallback options --}}
                                    <option value="Once a day" {{ old('items.'.$index.'.frequency', $item->frequency) == 'Once a day' ? 'selected' : '' }}>Once a day</option>
                                    <option value="Immediately" {{ old('items.'.$index.'.frequency', $item->frequency) == 'Immediately' ? 'selected' : '' }}>Immediately</option>
                                    <option value="At night" {{ old('items.'.$index.'.frequency', $item->frequency) == 'At night' ? 'selected' : '' }}>At night</option>
                                    <option value="At bedtime" {{ old('items.'.$index.'.frequency', $item->frequency) == 'At bedtime' ? 'selected' : '' }}>At bedtime</option>
                                    <option value="Twice a day" {{ old('items.'.$index.'.frequency', $item->frequency) == 'Twice a day' ? 'selected' : '' }}>Twice a day</option>
                                    <option value="Three times a day" {{ old('items.'.$index.'.frequency', $item->frequency) == 'Three times a day' ? 'selected' : '' }}>Three times a day</option>
                                    <option value="Four times a day" {{ old('items.'.$index.'.frequency', $item->frequency) == 'Four times a day' ? 'selected' : '' }}>Four times a day</option>
                                    <option value="Every four hours" {{ old('items.'.$index.'.frequency', $item->frequency) == 'Every four hours' ? 'selected' : '' }}>Every four hours</option>
                                    <option value="Every six hours" {{ old('items.'.$index.'.frequency', $item->frequency) == 'Every six hours' ? 'selected' : '' }}>Every six hours</option>
                                    <option value="Every eight hours" {{ old('items.'.$index.'.frequency', $item->frequency) == 'Every eight hours' ? 'selected' : '' }}>Every eight hours</option>
                                    <option value="Every twelve hours" {{ old('items.'.$index.'.frequency', $item->frequency) == 'Every twelve hours' ? 'selected' : '' }}>Every twelve hours</option>
                                    <option value="Every twenty-four hours" {{ old('items.'.$index.'.frequency', $item->frequency) == 'Every twenty-four hours' ? 'selected' : '' }}>Every twenty-four hours</option>
                                    <option value="Once a week" {{ old('items.'.$index.'.frequency', $item->frequency) == 'Once a week' ? 'selected' : '' }}>Once a week</option>
                                    <option value="Every week" {{ old('items.'.$index.'.frequency', $item->frequency) == 'Every week' ? 'selected' : '' }}>Every week</option>
                                    <option value="Once a month" {{ old('items.'.$index.'.frequency', $item->frequency) == 'Once a month' ? 'selected' : '' }}>Once a month</option>
                                @endif
                                {{-- Instill options --}}
                                <option value="instill 1 drop" {{ old('items.'.$index.'.frequency', $item->frequency) == 'instill 1 drop' ? 'selected' : '' }}>instill 1 drop</option>
                                <option value="instill 2 drops" {{ old('items.'.$index.'.frequency', $item->frequency) == 'instill 2 drops' ? 'selected' : '' }}>instill 2 drops</option>
                                <option value="instill 3 drops" {{ old('items.'.$index.'.frequency', $item->frequency) == 'instill 3 drops' ? 'selected' : '' }}>instill 3 drops</option>
                                <option value="instill 5 drops" {{ old('items.'.$index.'.frequency', $item->frequency) == 'instill 5 drops' ? 'selected' : '' }}>instill 5 drops</option>
                                <option value="instill 10 drops" {{ old('items.'.$index.'.frequency', $item->frequency) == 'instill 10 drops' ? 'selected' : '' }}>instill 10 drops</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-gray-700 text-sm font-bold mb-2">Rx Instruction</label>
                            <select name="items[{{ $index }}][instructions]" class="w-full px-3 py-2 border rounded">
                                <option value="">Please Select</option>
                                @if(isset($instructionItems) && $instructionItems->count() > 0)
                                    @foreach($instructionItems as $iItem)
                                        <option value="{{ $iItem->name }}" {{ old('items.'.$index.'.instructions', $item->instructions) == $iItem->name ? 'selected' : '' }}>{{ $iItem->name }}</option>
                                    @endforeach
                                @else
                                    {{-- Fallback options --}}
                                    <option value="When required" {{ old('items.'.$index.'.instructions', $item->instructions) == 'When required' ? 'selected' : '' }}>When required</option>
                                    <option value="Finish the Course" {{ old('items.'.$index.'.instructions', $item->instructions) == 'Finish the Course' ? 'selected' : '' }}>Finish the Course</option>
                                    <option value="Only if necessary" {{ old('items.'.$index.'.instructions', $item->instructions) == 'Only if necessary' ? 'selected' : '' }}>Only if necessary</option>
                                    <option value="Before meals" {{ old('items.'.$index.'.instructions', $item->instructions) == 'Before meals' ? 'selected' : '' }}>Before meals</option>
                                    <option value="After meals" {{ old('items.'.$index.'.instructions', $item->instructions) == 'After meals' ? 'selected' : '' }}>After meals</option>
                                    <option value="With food" {{ old('items.'.$index.'.instructions', $item->instructions) == 'With food' ? 'selected' : '' }}>With food</option>
                                    <option value="On alternate days" {{ old('items.'.$index.'.instructions', $item->instructions) == 'On alternate days' ? 'selected' : '' }}>On alternate days</option>
                                    <option value="At night only" {{ old('items.'.$index.'.instructions', $item->instructions) == 'At night only' ? 'selected' : '' }}>At night only</option>
                                    <option value="As directed by your healthcare provider" {{ old('items.'.$index.'.instructions', $item->instructions) == 'As directed by your healthcare provider' ? 'selected' : '' }}>As directed by your healthcare provider</option>
                                    <option value="Up to the maximum prescribed dose" {{ old('items.'.$index.'.instructions', $item->instructions) == 'Up to the maximum prescribed dose' ? 'selected' : '' }}>Up to the maximum prescribed dose</option>
                                    <option value="Gradually increase or decrease the dose as instructed" {{ old('items.'.$index.'.instructions', $item->instructions) == 'Gradually increase or decrease the dose as instructed' ? 'selected' : '' }}>Gradually increase or decrease the dose as instructed</option>
                                @endif
                            </select>
                        </div>
                        <div>
                            <label class="block text-gray-700 text-sm font-bold mb-2">Rx Duration *</label>
                            <select name="items[{{ $index }}][duration]" required class="w-full px-3 py-2 border rounded">
                                <option value="">Please Select</option>
                                @if(isset($durationItems) && $durationItems->count() > 0)
                                    @foreach($durationItems as $dItem)
                                        <option value="{{ $dItem->name }}" {{ old('items.'.$index.'.duration', $item->duration) == $dItem->name ? 'selected' : '' }}>{{ $dItem->name }}</option>
                                    @endforeach
                                @else
                                    {{-- Fallback options --}}
                                    @for($i = 1; $i <= 7; $i++)
                                        <option value="{{ $i }} {{ $i == 1 ? 'Day' : 'Days' }} Treatment" {{ old('items.'.$index.'.duration', $item->duration) == ($i . ' ' . ($i == 1 ? 'Day' : 'Days') . ' Treatment') ? 'selected' : '' }}>{{ $i }} {{ $i == 1 ? 'Day' : 'Days' }} Treatment</option>
                                    @endfor
                                    @for($i = 1; $i <= 5; $i++)
                                        <option value="{{ $i }} {{ $i == 1 ? 'Week' : 'Weeks' }} Treatment" {{ old('items.'.$index.'.duration', $item->duration) == ($i . ' ' . ($i == 1 ? 'Week' : 'Weeks') . ' Treatment') ? 'selected' : '' }}>{{ $i }} {{ $i == 1 ? 'Week' : 'Weeks' }} Treatment</option>
                                    @endfor
                                    @for($i = 1; $i <= 6; $i++)
                                        <option value="{{ $i }} {{ $i == 1 ? 'Month' : 'Months' }} Treatment" {{ old('items.'.$index.'.duration', $item->duration) == ($i . ' ' . ($i == 1 ? 'Month' : 'Months') . ' Treatment') ? 'selected' : '' }}>{{ $i }} {{ $i == 1 ? 'Month' : 'Months' }} Treatment</option>
                                    @endfor
                                    <option value="12 Months Treatment" {{ old('items.'.$index.'.duration', $item->duration) == '12 Months Treatment' ? 'selected' : '' }}>12 Months Treatment</option>
                                @endif
                            </select>
                        </div>
                    </div>
                    <div class="mb-2">
                        <label class="block text-gray-700 text-sm font-bold mb-2">Specific Instructions</label>
                        <input type="text" name="items[{{ $index }}][dosage]" class="w-full px-3 py-2 border rounded" placeholder="e.g., 500mg" value="{{ old('items.'.$index.'.dosage', $item->dosage) }}">
                    </div>
                    @if($index > 0)
                    <button type="button" onclick="removeItem(this)" class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded">
                        <i class="fas fa-trash"></i> Remove
                    </button>
                    @endif
                </div>
                @endforeach
            </div>
            <button type="button" onclick="addItem()" class="bg-gray-600 hover:bg-gray-700 text-white px-4 py-2 rounded">
                <i class="fas fa-plus"></i> Add Item
            </button>
        </div>

        <!-- Additional Prescription Details Section -->
        <div class="mb-6">
            <label class="block text-gray-700 text-sm font-bold mb-2">Additional Prescription Details</label>
            <textarea name="additional_prescription_details" rows="3" class="w-full px-3 py-2 border rounded" placeholder="Enter any additional prescription details...">{{ old('additional_prescription_details', $prescription->additional_prescription_details) }}</textarea>
        </div>

        <div class="flex justify-end">
            <button type="submit" class="bg-[#ec4899] hover:bg-[#db2777] text-white px-6 py-2 rounded">
                <i class="fas fa-save mr-2"></i>Update Prescription
            </button>
        </div>
    </form>
</div>

<script>
let itemCount = {{ $prescription->items->count() }};

// Prescription items from database
const quantityItems = @json(isset($quantityItems) ? $quantityItems->pluck('name') : []);
const frequencyItems = @json(isset($frequencyItems) ? $frequencyItems->pluck('name') : []);
const instructionItems = @json(isset($instructionItems) ? $instructionItems->pluck('name') : []);
const durationItems = @json(isset($durationItems) ? $durationItems->pluck('name') : []);
const medicineNames = @json(isset($medicineNames) ? $medicineNames : []);

// Fallback options if database is empty
const fallbackQuantity = ['5ml Teaspoon', '10ml', '15ml', '20ml', ...Array.from({length: 40}, (_, i) => `${i+1} ${i === 0 ? 'Tablet' : 'Tablets'}`), 'Apply', 'Chew', 'Dab', 'Dissolve', 'Drip', 'Drop', 'Flush', 'Gargle', 'Infuse', 'Inhale', 'Inject', 'Insert', 'Instil', 'Massage', 'Place between gum and cheek', 'Place under the tongue', 'Rinse', 'Rub', 'Soak', 'Spray', 'Spread', 'Sprinkle', 'Swallow', 'Swish and spit'];
const fallbackFrequency = ['Once a day', 'Immediately', 'At night', 'At bedtime', 'Twice a day', 'Three times a day', 'Four times a day', 'Every four hours', 'Every six hours', 'Every eight hours', 'Every twelve hours', 'Every twenty-four hours', 'Once a week', 'Every week', 'Once a month'];
const fallbackInstruction = ['When required', 'Finish the Course', 'Only if necessary', 'Before meals', 'After meals', 'With food', 'On alternate days', 'At night only', 'As directed by your healthcare provider', 'Up to the maximum prescribed dose', 'Gradually increase or decrease the dose as instructed'];
const fallbackDuration = [...Array.from({length: 7}, (_, i) => `${i+1} ${i === 0 ? 'Day' : 'Days'} Treatment`), ...Array.from({length: 5}, (_, i) => `${i+1} ${i === 0 ? 'Week' : 'Weeks'} Treatment`), ...Array.from({length: 6}, (_, i) => `${i+1} ${i === 0 ? 'Month' : 'Months'} Treatment`), '12 Months Treatment'];

// New instill frequency options
const instillOptions = ['instill 1 drop', 'instill 2 drops', 'instill 3 drops', 'instill 5 drops', 'instill 10 drops'];

function generateQuantityOptions() {
    const items = quantityItems.length > 0 ? quantityItems : fallbackQuantity;
    return items.map(item => `<option value="${item}">${item}</option>`).join('');
}

function generateFrequencyOptions() {
    const items = frequencyItems.length > 0 ? frequencyItems : fallbackFrequency;
    const allItems = [...items, ...instillOptions];
    return allItems.map(item => `<option value="${item}">${item}</option>`).join('');
}

function generateInstructionOptions() {
    const items = instructionItems.length > 0 ? instructionItems : fallbackInstruction;
    return items.map(item => `<option value="${item}">${item}</option>`).join('');
}

function generateDurationOptions() {
    const items = durationItems.length > 0 ? durationItems : fallbackDuration;
    return items.map(item => `<option value="${item}">${item}</option>`).join('');
}

function addItem() {
    const container = document.getElementById('items-container');
    const newItem = document.createElement('div');
    newItem.className = 'item-row mb-4 p-4 border rounded bg-gray-50';
    newItem.innerHTML = `
        <div class="grid grid-cols-1 md:grid-cols-6 gap-4 mb-4">
            <div class="md:col-span-2">
                <label class="block text-gray-700 text-sm font-bold mb-2">Prescription Items Rx *</label>
                <input type="text" name="items[${itemCount}][medicine_name]" required class="w-full px-3 py-2 border rounded medicine-autocomplete" placeholder="Type or select medicine name" list="medicine-list-${itemCount}" autocomplete="off">
                <datalist id="medicine-list-${itemCount}">
                    ${medicineNames.map(medicine => `<option value="${medicine}">${medicine}</option>`).join('')}
                </datalist>
            </div>
            <div>
                <label class="block text-gray-700 text-sm font-bold mb-2">Rx Quantity *</label>
                <select name="items[${itemCount}][quantity]" required class="w-full px-3 py-2 border rounded">
                    <option value="">Please Select</option>
                    ${generateQuantityOptions()}
                </select>
            </div>
            <div>
                <label class="block text-gray-700 text-sm font-bold mb-2">Rx Frequency (OD/BD/TDS) *</label>
                <select name="items[${itemCount}][frequency]" required class="w-full px-3 py-2 border rounded">
                    <option value="">Please Select</option>
                    ${generateFrequencyOptions()}
                </select>
            </div>
            <div>
                <label class="block text-gray-700 text-sm font-bold mb-2">Rx Instruction</label>
                <select name="items[${itemCount}][instructions]" class="w-full px-3 py-2 border rounded">
                    <option value="">Please Select</option>
                    ${generateInstructionOptions()}
                </select>
            </div>
            <div>
                <label class="block text-gray-700 text-sm font-bold mb-2">Rx Duration *</label>
                <select name="items[${itemCount}][duration]" required class="w-full px-3 py-2 border rounded">
                    <option value="">Please Select</option>
                    ${generateDurationOptions()}
                </select>
            </div>
        </div>
        <div class="mb-2">
            <label class="block text-gray-700 text-sm font-bold mb-2">Specific Instructions</label>
            <input type="text" name="items[${itemCount}][dosage]" class="w-full px-3 py-2 border rounded" placeholder="e.g., 500mg">
        </div>
        <button type="button" onclick="removeItem(this)" class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded">
            <i class="fas fa-trash"></i> Remove
        </button>
    `;
    container.appendChild(newItem);
    itemCount++;
}

function removeItem(button) {
    button.closest('.item-row').remove();
}
</script>
@endsection

