@include('header')

@if(isset($ipdData) && $ipdData)
<script>
    // Store IPD data for JavaScript access
    var ipdData = @json($ipdData);
    var editMode = true;
</script>
@else
<script>
    var ipdData = null;
    var editMode = false;
</script>
@endif

<style>
fieldset {
    border: 1px solid #3b6fa5;
    border-radius: 5px;
    padding: 10px;
    margin-bottom: 10px;
    position: relative;
    background: #f5f8fc;
}
fieldset legend {
    position: absolute;
    top: -12px;
    left: 15px;
    background: #f5f8fc;
    padding: 0 8px;
    font-size: 14px;
    color: #1d4b7f;
}
.form-control {
    height: 28px;
    font-size: 13px;
}
textarea.form-control {
    height: auto;
}
.btn {
    min-width: 80px;
}
</style>

<div class="container-fluid mt-2">

<form id="ipdForm" method="POST">
@csrf
<input type="hidden" name="MrdNo" id="MrdNo" value="{{ isset($ipdData) && $ipdData ? ($ipdData->MrdNo ?? '') : '' }}">
<input type="hidden" name="actionvalue" id="actionvalue" value="{{ isset($ipdData) && $ipdData ? 'Edit' : 'Save' }}">
<input type="hidden" name="saveid" id="saveid" value="{{ isset($ipdData) && $ipdData ? ($ipdData->id ?? '') : '' }}">

<!-- ================= OPD DETAILS ================= -->
<fieldset>
    <legend>OPD Details</legend>
    <div class="row">
        <div class="col-md-2">
            <label>UHID No.</label>
            <input type="text" class="form-control" id="UhidNo" name="UhidNo" value="{{ isset($ipdData) && $ipdData ? ($ipdData->UhidNo ?? '') : '' }}">
        </div>
        <div class="col-md-4">
            <label>Name</label>
            <input type="text" class="form-control" id="PatientName" name="PatientName" value="{{ isset($ipdData) && $ipdData ? ($ipdData->PatientName ?? '') : '' }}">
        </div>
        <div class="col-md-2">
            <label>Age</label>
            <input type="text" class="form-control" id="Age" name="Age" value="{{ isset($ipdData) && $ipdData ? ($ipdData->Age ?? '') : '' }}">
        </div>
        <div class="col-md-2">
            <label>Gender</label>
            <select class="form-control" id="Gender" name="Gender">
                <option value="">Select</option>
                <option value="Male" {{ isset($ipdData) && $ipdData && ($ipdData->Gender ?? '') == 'Male' ? 'selected' : '' }}>Male</option>
                <option value="Female" {{ isset($ipdData) && $ipdData && ($ipdData->Gender ?? '') == 'Female' ? 'selected' : '' }}>Female</option>
            </select>
        </div>
        <div class="col-md-2">
            <label>Weight</label>
            <input type="text" class="form-control" name="Weight" value="{{ isset($ipdData) && $ipdData ? ($ipdData->Weight ?? '') : '' }}">
        </div>
        <div class="col-md-2 mt-1">
            <label>Temp</label>
            <input type="text" class="form-control" name="Temp" value="{{ isset($ipdData) && $ipdData ? ($ipdData->Temp ?? '') : '' }}">
        </div>
        <div class="col-md-2 mt-1">
            <label>Height</label>
            <input type="text" class="form-control" name="Height" value="{{ isset($ipdData) && $ipdData ? ($ipdData->Height ?? '') : '' }}">
        </div>
    </div>
</fieldset>

<!-- ================= IPD INFO ================= -->
<fieldset>
    <legend>IPD Info</legend>
    <div class="row">
        <div class="col-md-2">
            <label>IPD No.</label>
            <input type="text" class="form-control" id="IpdNo" name="IpdNo" readonly value="{{ isset($ipdData) && $ipdData ? ($ipdData->IpdNo ?? '') : '' }}">
        </div>
        <div class="col-md-2">
            <label>Date Of Adm.</label>
            <input type="date" class="form-control" name="AdmissionDate" value="{{ isset($ipdData) && $ipdData && $ipdData->AdmissionDate ? date('Y-m-d', strtotime($ipdData->AdmissionDate)) : '' }}">
        </div>
        <div class="col-md-2">
            <label>Time</label>
            <input type="time" class="form-control" name="AdmissionTime" value="{{ isset($ipdData) && $ipdData ? ($ipdData->AdmissionTime ?? '') : '' }}">
        </div>
        <div class="col-md-2">
            <label>Blood Group</label>
            <select class="form-control" name="BloodGroup">
                <option value="">Select</option>
                <option value="A+" {{ isset($ipdData) && $ipdData && ($ipdData->BloodGroup ?? '') == 'A+' ? 'selected' : '' }}>A+</option>
                <option value="B+" {{ isset($ipdData) && $ipdData && ($ipdData->BloodGroup ?? '') == 'B+' ? 'selected' : '' }}>B+</option>
                <option value="O+" {{ isset($ipdData) && $ipdData && ($ipdData->BloodGroup ?? '') == 'O+' ? 'selected' : '' }}>O+</option>
                <option value="AB+" {{ isset($ipdData) && $ipdData && ($ipdData->BloodGroup ?? '') == 'AB+' ? 'selected' : '' }}>AB+</option>
                <option value="A-" {{ isset($ipdData) && $ipdData && ($ipdData->BloodGroup ?? '') == 'A-' ? 'selected' : '' }}>A-</option>
                <option value="B-" {{ isset($ipdData) && $ipdData && ($ipdData->BloodGroup ?? '') == 'B-' ? 'selected' : '' }}>B-</option>
                <option value="O-" {{ isset($ipdData) && $ipdData && ($ipdData->BloodGroup ?? '') == 'O-' ? 'selected' : '' }}>O-</option>
                <option value="AB-" {{ isset($ipdData) && $ipdData && ($ipdData->BloodGroup ?? '') == 'AB-' ? 'selected' : '' }}>AB-</option>
            </select>
        </div>
        <div class="col-md-2">
            <label>Type</label>
            <select class="form-control" name="PatientType">
                <option value="General" {{ isset($ipdData) && $ipdData && ($ipdData->Type ?? '') == 'General' ? 'selected' : '' }}>General</option>
                <option value="Private" {{ isset($ipdData) && $ipdData && ($ipdData->Type ?? '') == 'Private' ? 'selected' : '' }}>Private</option>
            </select>
        </div>

        <div class="col-md-3 mt-1">
            <label>Aadhar Card</label>
            <input type="text" class="form-control" name="AadharNo" value="{{ isset($ipdData) && $ipdData ? ($ipdData->AadharCardNo ?? '') : '' }}">
        </div>
        <div class="col-md-3 mt-1">
            <label>Ward *</label>
            <select class="form-control" name="Ward">
                <option value="">Select Ward</option>
                <option value="1" {{ isset($ipdData) && $ipdData && ($ipdData->WardId ?? '') == 1 ? 'selected' : '' }}>Ward A</option>
                <option value="2" {{ isset($ipdData) && $ipdData && ($ipdData->WardId ?? '') == 2 ? 'selected' : '' }}>Ward B</option>
                <option value="3" {{ isset($ipdData) && $ipdData && ($ipdData->WardId ?? '') == 3 ? 'selected' : '' }}>Ward C</option>
                <option value="4" {{ isset($ipdData) && $ipdData && ($ipdData->WardId ?? '') == 4 ? 'selected' : '' }}>Ward D</option>
                <option value="5" {{ isset($ipdData) && $ipdData && ($ipdData->WardId ?? '') == 5 ? 'selected' : '' }}>ICU</option>
                <option value="6" {{ isset($ipdData) && $ipdData && ($ipdData->WardId ?? '') == 6 ? 'selected' : '' }}>NICU</option>
                <option value="7" {{ isset($ipdData) && $ipdData && ($ipdData->WardId ?? '') == 7 ? 'selected' : '' }}>PICU</option>
            </select>
            <small class="text-muted">If your ward is not listed, contact administrator to add it</small>
        </div>
        <div class="col-md-2 mt-1">
            <label>Bed No.</label>
            <input type="text" class="form-control" name="BedNo" value="{{ isset($ipdData) && $ipdData ? ($ipdData->BedNo ?? '') : '' }}">
        </div>

        <div class="col-md-2 mt-1">
            <label>Wt. On Adm.</label>
            <input type="text" class="form-control" name="WtOnAdm" value="{{ isset($ipdData) && $ipdData ? ($ipdData->WtOnAdm ?? '') : '' }}">
        </div>
        <div class="col-md-2 mt-1">
            <label>Ht. On Adm.</label>
            <input type="text" class="form-control" name="HtOnAdm" value="{{ isset($ipdData) && $ipdData ? ($ipdData->HtOnAdm ?? '') : '' }}">
        </div>
        <div class="col-md-2 mt-1">
            <label>Tmp. On Adm.</label>
            <input type="text" class="form-control" name="TempOnAdm" value="{{ isset($ipdData) && $ipdData ? ($ipdData->TempOnAdm ?? '') : '' }}">
        </div>
    </div>
</fieldset>

<!-- ================= RELATIVE DETAILS ================= -->
<fieldset>
    <legend>Relative Details</legend>
    <div class="row">
        <div class="col-md-6">
            <label>Name of Relative / Father *</label>
            <input type="text" class="form-control" name="RelativeName" value="{{ isset($ipdData) && $ipdData ? ($ipdData->RelativeName ?? '') : '' }}">
        </div>
        <div class="col-md-6">
            <label>Name of Relative 2</label>
            <input type="text" class="form-control" name="RelativeName2" value="{{ isset($ipdData) && $ipdData ? ($ipdData->RelativeName2 ?? '') : '' }}">
        </div>
        <div class="col-md-6 mt-1">
            <label>Address *</label>
            <textarea class="form-control" rows="2" name="RelativeAddress">{{ isset($ipdData) && $ipdData ? ($ipdData->RelativeAddress ?? '') : '' }}</textarea>
        </div>
        <div class="col-md-6 mt-1">
            <label>Occupation</label>
            <input type="text" class="form-control" name="Occupation" value="{{ isset($ipdData) && $ipdData ? ($ipdData->Occupation ?? '') : '' }}">
        </div>
        <div class="col-md-3 mt-1">
            <label>Mob. No.1 *</label>
            <input type="text" class="form-control" name="Mobile1" value="{{ isset($ipdData) && $ipdData ? ($ipdData->RelativePhone ?? ($ipdData->Mobile ?? '')) : '' }}">
        </div>
        <div class="col-md-3 mt-1">
            <label>Mob. No.2</label>
            <input type="text" class="form-control" name="Mobile2" value="{{ isset($ipdData) && $ipdData ? ($ipdData->RelativePhone2 ?? '') : '' }}">
        </div>
    </div>
</fieldset>

<!-- ================= DIAGNOSIS ================= -->
<fieldset>
    <legend>Diagnosis</legend>
    <div class="row">
        <div class="col-md-6">
            <label>Provisional Diagnosis</label>
            <textarea class="form-control" rows="3" name="ProvisionalDiagnosis">{{ isset($ipdData) && $ipdData ? ($ipdData->ProDiagnosis ?? '') : '' }}</textarea>
        </div>
        <div class="col-md-6">
            <label>Final Diagnosis</label>
            <textarea class="form-control" rows="3" name="FinalDiagnosis">{{ isset($ipdData) && $ipdData ? ($ipdData->FinalDiagnosis ?? '') : '' }}</textarea>
        </div>
        <div class="col-md-4 mt-1">
            <label>Discharge Status</label>
            <select class="form-control" name="DischargeStatus">
                <option value="">Select</option>
                <option value="Recovered" {{ isset($ipdData) && $ipdData && ($ipdData->DischargeStatus ?? '') == 'Recovered' ? 'selected' : '' }}>Recovered</option>
                <option value="Referred" {{ isset($ipdData) && $ipdData && ($ipdData->DischargeStatus ?? '') == 'Referred' ? 'selected' : '' }}>Referred</option>
            </select>
        </div>
        <div class="col-md-4 mt-1">
            <label>Referred By</label>
            <input type="text" class="form-control" name="ReferredBy" value="{{ isset($ipdData) && $ipdData ? ($ipdData->ReferedBy ?? '') : '' }}">
        </div>
        <div class="col-md-4 mt-1">
            <label>Consultant</label>
            <input type="text" class="form-control" name="Consultant" value="{{ isset($ipdData) && $ipdData ? ($ipdData->Consultant ?? '') : '' }}">
        </div>
    </div>
</fieldset>

<!-- ================= OTHER INFO ================= -->
<fieldset>
    <legend>Other Info</legend>
    <div class="row">
        <div class="col-md-4">
            <label>Type Of Admission</label>
            <select class="form-control" name="AdmissionType">
                <option value="">Select</option>
                <option value="Emergency" {{ isset($ipdData) && $ipdData && ($ipdData->AdmissionType ?? '') == 'Emergency' ? 'selected' : '' }}>Emergency</option>
                <option value="Planned" {{ isset($ipdData) && $ipdData && ($ipdData->AdmissionType ?? '') == 'Planned' ? 'selected' : '' }}>Planned</option>
            </select>
        </div>
        <div class="col-md-4">
            <label>Indication For Admission</label>
            <textarea class="form-control" rows="2" name="Indication">{{ isset($ipdData) && $ipdData ? ($ipdData->AdmissionIndication ?? '') : '' }}</textarea>
        </div>
        <div class="col-md-4">
            <label>Admission For</label>
            <select class="form-control" name="AdmissionFor">
                <option value="">Select</option>
                <option value="Medical" {{ isset($ipdData) && $ipdData && ($ipdData->AdmissionFor ?? '') == 'Medical' ? 'selected' : '' }}>Medical</option>
                <option value="Surgical" {{ isset($ipdData) && $ipdData && ($ipdData->AdmissionFor ?? '') == 'Surgical' ? 'selected' : '' }}>Surgical</option>
            </select>
        </div>
    </div>
</fieldset>

<!-- ================= BUTTONS ================= -->
<div class="text-center mt-3">
    <button class="btn btn-primary" type="submit">Save</button>
    <button class="btn btn-success" type="button">Print</button>
    <button class="btn btn-info" type="button" onclick="location.reload()">Refresh</button>
    <button class="btn btn-dark" type="button" onclick="window.close()">Exit</button>
</div>

</form>
</div>

@include('footerscript')

<script>
let patientTimer;

function generateIpdNo(){
    $.ajax({
        url: "{{ url('generateIpdNo') }}",
        type: "POST",
        data: {_token:"{{ csrf_token() }}"},
        success:function(res){
            if(res.ipd_no){
                $('#IpdNo').val(res.ipd_no);
            }
        }
    });
}

// Fetch patient by MRD No or UHID No
function fetchPatientDetails(searchVal){
    if(!searchVal || searchVal.trim() == ''){
        return;
    }
    
    $.ajax({
        url: "{{ url('getPatientByMrdOrUhid') }}",
        type: "POST",
        data: {
            _token: "{{ csrf_token() }}",
            searchVal: searchVal
        },
        dataType: "json",
        success: function(data){
            if(data){
                $('#PatientName').val(data.PatientName || '');
                $('#Age').val(data.Age || '');
                $('#Gender').val(data.Gender || '').trigger('change');
                $('#Weight').val(data.Weight || '');
                $('#Height').val(data.Height || '');
                if(data.UhidNo) $('#UhidNo').val(data.UhidNo);
                if(data.MrdNo) {
                    $('input[name="MrdNo"]').val(data.MrdNo);
                }
                if(data.Phone) $('input[name="Mobile1"]').val(data.Phone);
                if(data.Address) $('textarea[name="RelativeAddress"]').val(data.Address);
                if(data.BloodGroup) $('select[name="BloodGroup"]').val(data.BloodGroup);
            }
        },
        error: function(){
            console.log('Patient not found');
        }
    });
}

// Listen to UHID No input
$(document).on('input', '#UhidNo', function(){
    clearTimeout(patientTimer);
    let val = $(this).val().trim();
    patientTimer = setTimeout(function(){
        if(val){
            fetchPatientDetails(val);
        }
    }, 500);
});

// Add MRD No field if not exists
if($('input[name="MrdNo"]').length == 0){
    $('<input>').attr({
        type: 'hidden',
        name: 'MrdNo',
        id: 'MrdNo'
    }).appendTo('#ipdForm');
}

// Form submission
$('#ipdForm').on('submit', function(e){
    e.preventDefault();
    
    var formData = new FormData(this);
    var actionValue = $('#actionvalue').val() || 'Save';
    formData.set('actionvalue', actionValue);
    
    if (actionValue === 'Edit') {
        formData.set('saveid', $('#saveid').val());
    }
    
    $.ajax({
        url: "{{ url('saveIpdCasePaper') }}",
        type: "POST",
        data: formData,
        processData: false,
        contentType: false,
        dataType: "json",
        success: function(res){
            if(res.success){
                alert('IPD case paper saved successfully!');
                if (actionValue === 'Save') {
                    $('#saveid').val(res.id);
                    $('#actionvalue').val('Edit');
                }
                // Optionally redirect to list page
                // window.location.href = "{{ url('ipdCasePaperList') }}";
            } else {
                alert('Error: ' + (res.error || 'Failed to save'));
            }
        },
        error: function(xhr){
            var errorMsg = 'Failed to save IPD case paper';
            if(xhr.responseJSON && xhr.responseJSON.error){
                errorMsg = xhr.responseJSON.error;
            }
            alert(errorMsg);
        }
    });
});

$(document).ready(function(){
    // Only generate IPD No if not in edit mode
    if (!editMode || !$('#IpdNo').val()) {
        generateIpdNo();
    }
    
    // Set current date and time only if not in edit mode
    if (!editMode || !$('input[name="AdmissionDate"]').val()) {
        var now = new Date();
        var dateStr = now.toISOString().split('T')[0];
        var timeStr = now.toTimeString().split(' ')[0].substring(0,5);
        
        $('input[name="AdmissionDate"]').val(dateStr);
        $('input[name="AdmissionTime"]').val(timeStr);
    }
});
</script>
