<?php 
session_start();
require_once 'config.php';
require_once 'auth.php';
$MainPage="OPD";
$Page = "Queue-Management";

/* -----------------------
   Server-side variables
   (kept as in original)
   ----------------------- */
if($_REQUEST['visitdate']){
    $VisitDate = $_REQUEST['visitdate'];
} else {
    $VisitDate = date('Y-m-d');    
}

if($_REQUEST['mrd'] == ''){
    $sql = "SELECT MAX(MrdNo) As MrdNo FROM tbl_patients";
    $row = getRecord($sql);
    if($row['MrdNo'] == ''){
        $MrdNo = 1;
    } else if($_GET['val'] == 'new'){
        $MrdNo = $row['MrdNo']+1;
    } else {
        $MrdNo = $row['MrdNo']+1;
    }
} else {
    $MrdNo = $_REQUEST['mrd'];
}

if($_REQUEST['visitdate'] == ''){
    $sql4 = "SELECT MAX(VisitNo) As VisitNo FROM tbl_visits WHERE MrdNo='$MrdNo'";
    $row4 = getRecord($sql4);
    $VisitNo = $row4['VisitNo']+1;
} else {
    $sql4 = "SELECT * FROM tbl_visits WHERE MrdNo='$MrdNo' AND VisitDate='".$_REQUEST['visitdate']."'";
    $rnct4 = getRow($sql4);
    $row4 = getRecord($sql4);
    if($rnct4 > 0){
        $VisitNo = $row4['VisitNo'];   
    } else {
        $sql4 = "SELECT MAX(VisitNo) As VisitNo FROM tbl_visits WHERE MrdNo='$MrdNo'";
        $row4 = getRecord($sql4);
        $VisitNo = $row4['VisitNo']+1;  
    }
}

$sql2 = "SELECT * FROM tbl_visits WHERE MrdNo='$MrdNo'";
$rncnt2 = getRow($sql2);

$sql7 = "SELECT * FROM tbl_consultant WHERE MrdNo='$MrdNo' AND VisitDate='$VisitDate'";
$row7 = getRecord($sql7);
$rncnt7 = getRow($sql7);

if($rncnt7 > 0){
    $VisitTime = $row7['VisitTime'];
    $RefBy = $row7['RefBy'];
    $Patient_Name = $row7['PatientName'];
    $Gender = $row7['Gender'];
    $Age = $row7['Age'];
    $EmailId = $row7['EmailId'];
    $Phone = $row7['Phone'];
    $MarritalStatus = $row7['MarritalStatus'];
    $Address = $row7['Address'];
    $Duration = $row7['Duration'];
} else {
    $VisitTime = date('h:i');
    $sql66 = "SELECT RefBy FROM tbl_consultant WHERE id=(SELECT MAX(id) FROM `tbl_consultant` WHERE RefBy!='')";
    $row66 = getRecord($sql66);
    $RefBy = $row66['RefBy'];
    $sql8 = "SELECT * FROM tbl_patients WHERE MrdNo='$MrdNo'";
    $row8 = getRecord($sql8);
    $Patient_Name = $row8['PatientName'];
    $Gender = $row8['Gender'];
    $Age = $row8['Age'];
    $EmailId = $row8['EmailId'];
    $Phone = $row8['Phone'];
    $MarritalStatus = $row8['MarritalStatus'];
    $Address = $row8['Address'];
    $Duration = 0;
}

$sql8 = "SELECT ptnotes FROM tbl_patients WHERE MrdNo='$MrdNo'";
$row8 = getRecord($sql8);

?>
<!DOCTYPE html>
<html lang="en" class="default-style">
<head>
    <title><?php echo $Proj_Title; ?></title>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
    <?php include_once 'header_script.php'; ?>

    <!-- Optimized CSS (keeps everything compact + consistent widths) -->
    <style>
        /* Utility widths for consistent layout */
        .opd-small { max-width: 90px; width: 100%; }
        .opd-medium { max-width: 180px; width: 100%; }
        .opd-large { max-width: 320px; width: 100%; }
        .opd-full { width: 100%; }

        /* Table adjustments */
        .opd-table th, .opd-table td {
            padding: 0.45rem;
            font-size: 15px;
            vertical-align: middle;
            white-space: nowrap;
        }
        .opd-table .wrap { white-space: normal; }

        /* Form control sizing: uniform and slightly taller for touch */
        .form-control {
            min-height: 30px;
            height: 34px;
            font-size: 15px;
            padding: .375rem .5rem;
            box-sizing: border-box;
            background-color: #fff;
        }
        textarea.form-control { height: auto; min-height: 80px; }

        /* Make fieldsets visually distinct */
        fieldset { border: 1px solid #dcdcdc; padding: .65rem; margin-bottom: .75rem; }
        legend { font-size: 1rem; padding: 0 .5rem; width: auto; }

        /* Fix modal stacking and remove nested placement issues */
        .modal { z-index: 1050; }

        /* Small visual tweaks */
        .card-body-tight { padding: .35rem .65rem .9rem; }
        .btn-sm { padding: .25rem .45rem; font-size: .85rem; }
        #myBtn { display: none; position: fixed; bottom: 20px; right: 30px; z-index: 99; font-size: 14px; border: none; outline: none; background-color: #e55353; color: white; cursor: pointer; padding: 10px 12px; border-radius: 4px; }
        #myBtn:hover { background-color: #7a7a7a; }

        /* Responsive: allow wrapping on smaller screens */
        @media (max-width: 768px) {
            .opd-table th, .opd-table td { font-size: 14px; }
            .form-control { font-size: 14px; height: 36px; }
            .opd-medium, .opd-large { max-width: none; }
        }
    </style>
</head>
<body>
<div class="layout-wrapper layout-1 layout-without-sidenav">
    <div class="layout-inner">
        <div class="layout-container">
            <!-- Page content -->
            <div class="container-fluid flex-grow-1">
                <!-- OPD Summary Modal (moved top-level) -->
                <div class="modal fade" id="modal-report22" tabindex="-1" role="dialog"
                     aria-labelledby="modal-report22-label" aria-hidden="true">
                    <div class="modal-dialog modal-lg" role="document" style="max-width: 70%;">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">OPD Summary</h5>
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                  <span aria-hidden="true">&times;</span>
                                </button>
                            </div>
                            <div class="modal-body">
                                <?php //include 'opd-patient-summary.php'; ?>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Page card -->
                <form method="post" action="ajax_files/ajax_opto_form.php" autocomplete="off">
                    <input type="hidden" id="CurrDate" value="<?php echo date('Y-m-d');?>">
                    <input type="hidden" name="action" id="action" value="Save">
                    <input type="hidden" name="id" id="id" value="">

                    <div class="row">
                        <div class="col-md-12">
                            <div class="card mb-2">
                                <div class="card-body card-body-tight" style="background-color: cadetblue;">
                                    <div class="card-header" style="padding-top:5px;">
                                        <ul class="nav nav-tabs card-header-tabs nav-responsive-md">
                                            <li class="nav-item">
                                                <a class="nav-link active" data-toggle="tab" href="#navs-wc-home" onclick="pressTab(1)" style="color:black;">Patient Info</a>
                                            </li>
                                            <li class="nav-item">
                                                <a class="nav-link" onclick="patientSummary()" href="javascript:void(0)" style="color:black;">Patient Summary</a>
                                            </li>
                                            <li class="nav-item">
                                                <a class="nav-link" onclick="briefSummary()" href="javascript:void(0)" style="color:black;">Brief Summary</a>
                                            </li>

                                            <?php if($_SESSION['CopyPaste'] == 'copy'){?>
                                            <li class="nav-item ml-auto">
                                                <a href="<?php echo $_SERVER['PHP_SELF']; ?>?mrd=<?php echo $_REQUEST['mrd']; ?>&visitdate=<?php echo $_REQUEST['visitdate'];?>&action=paste" class="btn btn-info btn-sm">Paste</a>
                                            </li>
                                            <?php } ?>

                                            <li class="nav-item" style="margin-left:8px;">
                                                <a href="dashboard.php" class="btn btn-success btn-sm">Back To Home</a>
                                            </li>
                                            <li class="nav-item" style="margin-left:8px;">
                                                <button class="btn btn-info btn-sm" type="button" onclick="printOpd()" id="print">Print</button>
                                            </li>
                                            <li class="nav-item" style="margin-left:8px;">
                                                <button class="btn btn-danger btn-sm" type="button" onclick="deletePatient()">Delete Patient</button>
                                            </li>
                                            <li class="nav-item" style="margin-left:8px;">
                                                <button class="btn btn-success btn-sm" type="submit" name="submit" id="submit">Save</button>
                                            </li>
                                        </ul>
                                    </div>

                                    <div class="tab-content" style="margin-top:8px;">
                                        <!-- TAB: HOME -->
                                        <div class="tab-pane fade show active" id="navs-wc-home">
                                            <div class="form-row">
                                                <div class="form-group col-md-12" style="margin-bottom:0;">
                                                    <fieldset>
                                                        <legend>Search Patient</legend>

                                                        <!-- Search Patient Table -->
                                                        <div class="table-responsive">
                                                            <table class="table table-bordered table-striped mb-0 opd-table">
                                                                <thead>
                                                                    <tr>
                                                                        <th class="opd-small">MRD NO</th>
                                                                        <th class="opd-large">Add Search Criteria</th>
                                                                        <th class="opd-medium">Visit Date</th>
                                                                        <th class="opd-medium">Visit Date List</th>
                                                                        <th class="opd-small"></th>
                                                                        <th class="opd-small">Telugu</th>
                                                                    </tr>
                                                                </thead>
                                                                <tbody>
                                                                    <tr>
                                                                        <td>
                                                                            <input type="hidden" id="newmrdno" value="<?php echo $MrdNo; ?>">
                                                                            <div class="input-group">
                                                                                <input type="text" name="MrdNo" id="MrdNo" class="form-control opd-small"
                                                                                       value="<?php echo $MrdNo; ?>"
                                                                                       onClick="this.select();" oninput="getPatientDetails()" onKeyPress="return isNumberKey(event)">
                                                                                <div class="input-group-append">
                                                                                    <button class="btn btn-secondary btn-sm" type="button" onclick="getNewMrdNo()">New</button>
                                                                                </div>
                                                                            </div>
                                                                            <input type="hidden" name="VisitNo" id="VisitNo" value="<?php echo $VisitNo;?>">
                                                                        </td>

                                                                        <td>
                                                                            <input class="form-control datalist opd-full" list="DataList2" name="PatientId" id="PatientId"
                                                                                   onchange="getPatientDetails2(this.value)" value="<?php echo $row7['PatientId'];?>"
                                                                                   style="background:<?php echo ($row8['ptnotes']!='') ? 'red' : 'chartreuse'; ?>;">
                                                                            <datalist id="DataList2">
                                                                                <?php 
                                                                                $sql4 = "SELECT MrdNo,PatientName,ConsultantName,Phone FROM tbl_patients";
                                                                                $row4 = getList($sql4);
                                                                                foreach($row4 as $result){
                                                                                    $PatientName = $result['MrdNo']." / ".$result['PatientName'];
                                                                                    if($result['Phone'] != ''){
                                                                                       $PatientName .= "/".$result['Phone'];
                                                                                    }
                                                                                ?>
                                                                                    <option value="<?php echo $PatientName; ?>"></option>
                                                                                <?php } ?>
                                                                            </datalist>
                                                                        </td>

                                                                        <td>
                                                                            <input type="date" class="form-control" name="VisitDate2" id="VisitDate2"
                                                                                   value="<?php echo $VisitDate;?>" onchange="checkVisitDate(this.value)">
                                                                        </td>

                                                                        <td>
                                                                            <select class="form-control" name="VisitDate" id="VisitDate" onchange="getConsultRec(this.value)">
                                                                                <?php 
                                                                                $CurrDate = date('Y-m-d');
                                                                                $sql55 = "SELECT * FROM tbl_visits WHERE MrdNo='$MrdNo' AND VisitDate='$CurrDate' ORDER BY VisitDate DESC";
                                                                                $rncnt55 = getRow($sql55);

                                                                                $sql4 = "SELECT MAX(VisitNo) AS VisitNo FROM tbl_visits WHERE MrdNo='$MrdNo'";
                                                                                $row4 = getRecord($sql4);
                                                                                $VisitNo22 = $row4['VisitNo'] + 1;

                                                                                if(!$rncnt55){
                                                                                ?>
                                                                                <option selected value="<?php echo $CurrDate; ?>">
                                                                                    <?php echo $VisitNo22." / ".date("d/m/Y",strtotime($CurrDate)); ?>
                                                                                </option>
                                                                                <?php } ?>

                                                                                <?php 
                                                                                $sql5 = "SELECT * FROM tbl_visits WHERE MrdNo='$MrdNo' AND DeleteFlag=0 ORDER BY VisitDate DESC";
                                                                                $row5 = getList($sql5);
                                                                                foreach($row5 as $result){
                                                                                ?>
                                                                                <option value="<?php echo $result['VisitDate'];?>" <?php if($result['VisitDate']==$VisitDate){ echo "selected"; } ?>>
                                                                                    <?php echo $result['VisitNo']." / ".date("d/m/Y",strtotime($result['VisitDate'])); ?>
                                                                                </option>
                                                                                <?php } ?>
                                                                            </select>
                                                                        </td>

                                                                        <input type="hidden" name="VisitTime" id="VisitTime" value="<?php echo $VisitTime; ?>">

                                                                        <td>
                                                                            <button class="btn btn-danger btn-sm" type="button" data-toggle="modal" data-target="#myModal">Note</button>
                                                                        </td>

                                                                        <td>
                                                                            <input type="checkbox" value="1" name="Telugu" <?php echo ($row7['Telugu']=='1') ? 'checked' : ''; ?>> Telugu
                                                                        </td>
                                                                    </tr>
                                                                </tbody>
                                                            </table>
                                                        </div>

                                                        <!-- note modal trigger is handled above; modal itself is outside table -->
                                                    </fieldset>
                                                </div>
                                            </div>

                                            <!-- Patient General Info -->
                                            <div class="form-group col-md-12" style="margin-bottom:0;">
                                                <fieldset>
                                                    <legend>Patient General Info</legend>
                                                    <div class="table-responsive">
                                                        <table class="table table-bordered table-striped mb-0 opd-table">
                                                            <thead>
                                                                <tr>
                                                                    <th>Full Name</th>
                                                                    <th>New Name</th>
                                                                    <th style="width:13%;">Sex</th>
                                                                    <th style="width:7%;">Age</th>
                                                                    <th>Email</th>
                                                                </tr>
                                                            </thead>
                                                            <tbody>
                                                                <tr>
                                                                    <td>
                                                                        <div class="input-group">
                                                                            <input type="text" class="form-control opd-full" list="Dllname" id="PatientName" name="PatientName" placeholder="Patient Name"
                                                                                   value="<?php echo $Patient_Name;?>" oninput="getFnameCap2('PatientName'),ShortPtName33('PatientName')">
                                                                            <datalist id="Dllname">
                                                                                <?php 
                                                                                $sql4 = "SELECT DISTINCT(PatientName) As PatientName FROM tbl_patients";
                                                                                $row4 = getList($sql4);
                                                                                foreach($row4 as $result){
                                                                                ?>
                                                                                    <option value="<?php echo $result['PatientName']; ?>"></option>
                                                                                <?php } ?>
                                                                            </datalist>
                                                                            <div class="input-group-append">
                                                                                <button class="btn btn-secondary btn-sm" type="button" onclick="getUpRecordList()">...</button>
                                                                            </div>
                                                                        </div>

                                                                        <!-- Updated Record Modal -->
                                                                        <div class="modal fade" id="myModal22" role="dialog">
                                                                            <div class="modal-dialog">
                                                                                <div class="modal-content">
                                                                                    <div class="modal-header"><h4 class="modal-title">Patient Updated Record History</h4></div>
                                                                                    <div class="modal-body">
                                                                                        <style>
                                                                                            #customers { font-family: Arial, Helvetica, sans-serif; border-collapse: collapse; width: 100%; }
                                                                                            #customers td, #customers th { border: 1px solid #ddd; padding: 8px; }
                                                                                            #customers tr:nth-child(even){ background-color: #f2f2f2; }
                                                                                            #customers tr:hover { background-color: #ddd; }
                                                                                            #customers th { padding-top: 12px; padding-bottom: 12px; text-align: left; background-color: #04AA6D; color: white; }
                                                                                        </style>
                                                                                        <table id="customers"></table>
                                                                                    </div>
                                                                                    <div class="modal-footer">
                                                                                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                                                                                    </div>
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                    </td>

                                                                    <td>
                                                                        <input type="text" class="form-control opd-full" id="NewName" name="NewName" oninput="getFnameCap2('PatientName')">
                                                                    </td>

                                                                    <td>
                                                                        <select class="form-control" id="Gender" name="Gender" required>
                                                                            <option value="Male" <?php if($Gender == 'Male'){?> selected <?php } ?>>Male</option>
                                                                            <option value="Female" <?php if($Gender == 'Female'){?> selected <?php } ?>>Female</option>
                                                                        </select>
                                                                    </td>

                                                                    <td>
                                                                        <input type="text" class="form-control opd-small" id="Age" name="Age" onKeyPress="return isNumberKey(event)" value="<?php echo $Age;?>">
                                                                    </td>

                                                                    <td>
                                                                        <input type="email" class="form-control opd-medium" id="EmailId" name="EmailId" value="<?php echo $EmailId;?>">
                                                                    </td>
                                                                </tr>
                                                            </tbody>

                                                            <thead>
                                                                <tr>
                                                                    <th>Mobile No</th>
                                                                    <th>New Mobile No</th>
                                                                    <th>Marital Status</th>
                                                                    <th colspan="2">Address</th>
                                                                </tr>
                                                            </thead>

                                                            <tbody>
                                                                <tr>
                                                                    <td>
                                                                        <input type="text" class="form-control opd-medium" id="Phone" name="Phone" onKeyPress="return isNumberKey(event)" value="<?php echo $Phone;?>">
                                                                    </td>
                                                                    <td>
                                                                        <input type="text" class="form-control opd-medium" id="NewPhone" name="NewPhone" onKeyPress="return isNumberKey(event)">
                                                                    </td>
                                                                    <td>
                                                                        <select class="form-control opd-medium" name="MarritalStatus" id="MarritalStatus">
                                                                            <option <?php if($MarritalStatus == 'M'){ ?> selected <?php } ?> value="M">Married</option>
                                                                            <option <?php if($MarritalStatus == 'UN'){ ?> selected <?php } ?> value="UN">Unmarried</option>
                                                                            <option <?php if($MarritalStatus == 'D'){ ?> selected <?php } ?> value="D">Divorcee</option>
                                                                            <option <?php if($MarritalStatus == 'W'){ ?> selected <?php } ?> value="W">Widow</option>
                                                                            <option <?php if($MarritalStatus == 'Disputed'){ ?> selected <?php } ?> value="Disputed">Disputed</option>
                                                                        </select>
                                                                    </td>
                                                                    <td colspan="2">
                                                                        <input class="form-control opd-full" list="Cities" name="Address" id="Address" value="<?php echo $Address;?>" oninput="getFnameCap('Address')">
                                                                        <datalist id="Cities">
                                                                            <?php 
                                                                            $sql = "SELECT DISTINCT(Address) As Address FROM tbl_patients";
                                                                            $row = getList($sql);
                                                                            foreach($row as $result){
                                                                            ?>
                                                                                <option value="<?php echo $result['Address']; ?>"></option>
                                                                            <?php } ?>
                                                                        </datalist>
                                                                    </td>
                                                                </tr>
                                                            </tbody>

                                                            <thead>
                                                                <tr>
                                                                    <th>Name of Objective Data</th>
                                                                    <th>Foot Note</th>
                                                                    <th colspan="2">Comorbities: known case of</th>
                                                                    <th></th>
                                                                </tr>
                                                            </thead>

                                                            <tbody>
                                                                <tr>
                                                                    <td class="wrap">
                                                                        <div class="input-group">
                                                                            <input class="form-control opd-medium" list="relation_ship" name="Relationship" id="Relationship" value="<?php echo $row7['Relationship'];?>" oninput="ShortPtName33('Relationship');">
                                                                            <datalist id="relation_ship">
                                                                                <?php 
                                                                                $sql4 = "SELECT * FROM tbl_drugs WHERE ShortKeyFor=3";
                                                                                $row4 = getList($sql4);
                                                                                foreach($row4 as $result){
                                                                                ?>
                                                                                    <option value="<?php echo $result['Name']; ?>"></option>
                                                                                <?php } ?>
                                                                            </datalist>

                                                                            <input type="text" class="form-control opd-medium" placeholder="Relative Name" name="RelativeName" id="RelativeName" value="<?php echo $row7['RelativeName'];?>">
                                                                        </div>
                                                                    </td>

                                                                    <td>
                                                                        <input type="text" class="form-control opd-medium" list="FootNote" id="RefBy" name="RefBy" value="<?php echo $RefBy;?>">
                                                                        <datalist id="FootNote">
                                                                            <?php 
                                                                            $sql4 = "SELECT DISTINCT(RefBy) As RefBy FROM tbl_consultant";
                                                                            $row4 = getList($sql4);
                                                                            foreach($row4 as $result){
                                                                            ?>
                                                                                <option value="<?php echo $result['RefBy']; ?>"></option>
                                                                            <?php } ?>
                                                                        </datalist>
                                                                    </td>

                                                                    <td colspan="3">
                                                                        <label class="mr-2"><input type="checkbox" name="DM" value="1" <?php if($row7['DM'] == '1'){?> checked <?php } ?> /> DM</label>
                                                                        <label class="mr-2"><input type="checkbox" name="HT" value="1" <?php if($row7['HT'] == '1'){?> checked <?php } ?> /> HT</label>
                                                                        <label class="mr-2"><input type="checkbox" name="IHD" value="1" <?php if($row7['IHD'] == '1'){?> checked <?php } ?> /> IHD</label>
                                                                        <label class="mr-2"><input type="checkbox" name="PILES" value="1" <?php if($row7['PILES'] == '1'){?> checked <?php } ?> /> PILES</label>
                                                                        <label class="mr-2"><input type="checkbox" name="Thyroid" value="1" <?php if($row7['Thyroid'] == '1'){?> checked <?php } ?> /> Thyroid</label>
                                                                        <label class="mr-1"><input type="checkbox" name="Other" value="1" <?php if($row7['Other'] == '1'){?> checked <?php } ?> /> Other</label>
                                                                        <input type="text" name="OtherTxt" value="<?php echo $row7['OtherTxt'];?>" class="form-control opd-medium mt-1" />
                                                                    </td>
                                                                </tr>
                                                            </tbody>
                                                        </table>
                                                    </div>
                                                </fieldset>
                                            </div>

                                            <!-- Notes, Investigations, Treatments, Language -->
                                            <div class="row">
                                                <div class="col-lg-8">
                                                    <fieldset>
                                                        <legend>Detail Notes</legend>
                                                        <div class="row">
                                                            <div class="col-lg-11">
                                                                <textarea class="form-control" id="Notes" rows="10" name="Notes" style="height:146px;"><?php echo $row7['Notes'];?></textarea>
                                                            </div>
                                                            <div class="col-lg-1">
                                                                <span class="input-group-append">
                                                                    <button class="btn btn-secondary btn-sm" type="button" data-toggle="modal" data-target="#modal-report" id="add_button" onclick="getValue('Notes','Notes')">...</button>
                                                                </span>
                                                            </div>
                                                        </div>
                                                    </fieldset>

                                                    <fieldset>
                                                        <div id="accordion2">
                                                            <div class="card mb-2">
                                                                <div class="card-header">
                                                                    <a class="collapsed d-flex justify-content-between text-dark" data-toggle="collapse" href="#accordion2-2">Investigation<div class="collapse-icon"></div></a>
                                                                </div>
                                                                <div id="accordion2-2" class="collapse" data-parent="#accordion2">
                                                                    <div class="card-body">
                                                                        <table class="table table-bordered table-striped mb-0 opd-table">
                                                                            <tbody>
                                                                                <tr>
                                                                                    <th style="width:130px;">
                                                                                        <label><input type="checkbox" name="ChkBlood" value="1" <?php if($row7['ChkBlood'] == '1'){?> checked <?php } ?> style="transform: scale(1.2); margin-right:6px;" /> Blood</label>
                                                                                    </th>
                                                                                    <td><input type="text" class="form-control" name="TxtBlood" value="<?php echo $row7['TxtBlood'];?>" oninput="chkInvst('ChkBlood','TxtBlood')"></td>
                                                                                </tr>
                                                                                <tr>
                                                                                    <th style="width:130px;"><label><input type="checkbox" name="Eeg" value="1" <?php if($row7['Eeg'] == '1'){?> checked <?php } ?> style="transform: scale(1.2); margin-right:6px;" /> EEG</label></th>
                                                                                    <td><input type="text" class="form-control" name="TxtEeg" value="<?php echo $row7['TxtEeg'];?>" oninput="chkInvst('Eeg','TxtEeg')"></td>
                                                                                </tr>
                                                                                <tr>
                                                                                    <th><label><input type="checkbox" name="ChkCT" value="1" <?php if($row7['ChkCT'] == '1'){?> checked <?php } ?> style="transform: scale(1.2); margin-right:6px;" /> CT Brain</label></th>
                                                                                    <td><input type="text" class="form-control" name="TxtCT" value="<?php echo $row7['TxtCT'];?>" oninput="chkInvst('ChkCT','TxtCT')"></td>
                                                                                </tr>
                                                                                <tr>
                                                                                    <th><label><input type="checkbox" name="ChkMRI" value="1" <?php if($row7['ChkMRI'] == '1'){?> checked <?php } ?> style="transform: scale(1.2); margin-right:6px;" /> MRI Brain</label></th>
                                                                                    <td><input type="text" class="form-control" name="TxtMRI" value="<?php echo $row7['TxtMRI'];?>" oninput="chkInvst('ChkMRI','TxtMRI')"></td>
                                                                                </tr>
                                                                                <tr>
                                                                                    <th><label><input type="checkbox" name="ChkUSG" value="1" <?php if($row7['ChkUSG'] == '1'){?> checked <?php } ?> style="transform: scale(1.2); margin-right:6px;" /> USG</label></th>
                                                                                    <td><input type="text" class="form-control" name="TxtUSG" value="<?php echo $row7['TxtUSG'];?>" oninput="chkInvst('ChkUSG','TxtUSG')"></td>
                                                                                </tr>
                                                                                <tr>
                                                                                    <th><label><input type="checkbox" name="ChkOthers" value="1" <?php if($row7['ChkOthers'] == '1'){?> checked <?php } ?> style="transform: scale(1.2); margin-right:6px;" /> Others</label></th>
                                                                                    <td><input type="text" class="form-control" name="TxtOthers" value="<?php echo $row7['TxtOthers'];?>" oninput="chkInvst('ChkOthers','TxtOthers')"></td>
                                                                                </tr>
                                                                            </tbody>
                                                                        </table>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </fieldset>

                                                    <fieldset>
                                                        <legend>Treatment</legend>
                                                        <div class="table-responsive">
                                                            <?php include 'inctreatments.php'; ?>
                                                        </div>
                                                    </fieldset>

                                                    <fieldset>
                                                        <legend>Language</legend>
                                                        <table class="table table-bordered table-striped mb-0 opd-table">
                                                            <tbody>
                                                                <?php if($rncnt7 > 0){?>
                                                                <tr>
                                                                    <td><label><input type="radio" name="Language" value="M" <?php if($row7['Language'] == 'M'){?> checked <?php } ?> style="transform:scale(1.2);" /> Marathi</label></td>
                                                                    <td><label><input type="radio" name="Language" value="E" <?php if($row7['Language'] == 'E'){?> checked <?php } ?> style="transform:scale(1.2);" /> English</label></td>
                                                                    <td><label><input type="radio" name="Language" value="H" <?php if($row7['Language'] == 'H'){?> checked <?php } ?> style="transform:scale(1.2);" /> Hindi</label></td>
                                                                </tr>
                                                                <?php } else { ?>
                                                                <tr>
                                                                    <td><label><input type="radio" name="Language" id="Mlanguage" value="M" checked style="transform:scale(1.2);" /> Marathi</label></td>
                                                                    <td><label><input type="radio" name="Language" id="Elanguage" value="E" style="transform:scale(1.2);" /> English</label></td>
                                                                    <td><label><input type="radio" name="Language" id="Hlanguage" value="H" style="transform:scale(1.2);" /> Hindi</label></td>
                                                                </tr>
                                                                <?php } ?>
                                                            </tbody>
                                                        </table>
                                                    </fieldset>
                                                </div>

                                                <div class="col-lg-4">
                                                    <fieldset>
                                                        <legend>Instructions</legend>
                                                        <div class="table-responsive">
                                                            <table class="table table-bordered table-striped mb-0 opd-table">
                                                                <tbody>
                                                                    <tr>
                                                                        <td>
                                                                            <label><input type="checkbox" name="Prognosis" value="1" <?php if($row7['Prognosis'] == '1'){?> checked <?php } ?> /> Poor Prognosis</label>
                                                                            <br/>
                                                                            <label><input type="checkbox" name="DSH" value="1" <?php if($row7['DSH'] == '1'){?> checked <?php } ?> /> DSH Risk Informed to OD</label>
                                                                        </td>
                                                                    </tr>
                                                                    <tr><td><label><input type="checkbox" name="FollowUp" value="1" <?php if($row7['FollowUp'] == '1'){?> checked <?php } ?> /> Follow up with responsible relative</label></td></tr>
                                                                    <tr>
                                                                        <td>
                                                                            <label><input type="checkbox" name="Irregular" value="1" <?php if($row7['Irregular'] == '1'){?> checked <?php } ?> /> Irregular Treatment</label>
                                                                            <br/>
                                                                            <label><input type="checkbox" name="Medication" value="1" <?php if($row7['Medication'] == '1'){?> checked <?php } ?> /> Self Medication</label>
                                                                        </td>
                                                                    </tr>
                                                                    <tr><td><label><input type="checkbox" name="StrictSupervision" value="1" <?php if($row7['StrictSupervision'] == '1'){?> checked <?php } ?> /> Maintain strict supervision on patient</label></td></tr>
                                                                    <tr><td><label><input type="checkbox" name="Admission" value="1" <?php if($row7['Admission'] == '1'){?> checked <?php } ?> /> Admission / Relatives not willing at present</label></td></tr>
                                                                </tbody>
                                                            </table>
                                                        </div>
                                                    </fieldset>

                                                    <fieldset>
                                                        <div class="table-responsive">
                                                            <table class="table table-bordered table-striped mb-0 opd-table">
                                                                <tbody>
                                                                    <tr>
                                                                        <td><label><input type="checkbox" value="1" name="ChkPrevTreat" <?php if($row7['ChkPrevTreat'] == '1'){?> checked <?php } ?> /> Previous Treatment</label></td>
                                                                    </tr>
                                                                    <tr>
                                                                        <td>
                                                                            <input type="text" id="PrevTreatment" name="PrevTreatment" value="<?php echo $row7['PrevTreatment'];?>" list="prevtreat" class="form-control" oninput="ShortPtName33('PrevTreatment')">
                                                                        </td>
                                                                    </tr>
                                                                </tbody>
                                                            </table>
                                                        </div>
                                                    </fieldset>

                                                    <fieldset>
                                                        <div class="table-responsive">
                                                            <table class="table table-bordered table-striped mb-0 opd-table">
                                                                <tbody>
                                                                    <tr><td><label><input type="checkbox" value="1" name="ChkSpecialNote" <?php if($row7['ChkSpecialNote'] == '1'){?> checked <?php } ?> /> Special Note</label></td></tr>
                                                                    <tr><td><textarea class="form-control" id="SpecialNote" name="SpecialNote" oninput="ShortPtName33('SpecialNote')"><?php echo $row7['SpecialNote'];?></textarea></td></tr>
                                                                </tbody>
                                                            </table>
                                                        </div>
                                                    </fieldset>

                                                    <fieldset>
                                                        <div class="table-responsive">
                                                            <table class="table table-bordered table-striped mb-0 opd-table">
                                                                <tbody>
                                                                    <tr>
                                                                        <th style="width:115px;">Duration</th>
                                                                        <th>Follow up Date</th>
                                                                    </tr>
                                                                    <tr>
                                                                        <td><input type="number" class="form-control" id="Duration" name="Duration" value="<?php echo $Duration;?>" oninput="findFollowDate()" required></td>
                                                                        <td><input onchange="checkFollowDate(this.value)" type="date" class="form-control" name="FollowUpDate" id="FollowUpDate" value="<?php echo $row7['FollowUpDate'];?>" required></td>
                                                                    </tr>
                                                                    <tr><td colspan="2"><span id="followcheck" style="color:red;"></span></td></tr>
                                                                </tbody>
                                                            </table>
                                                        </div>
                                                    </fieldset>

                                                    <fieldset>
                                                        <div class="table-responsive">
                                                            <table class="table table-bordered table-striped mb-0 opd-table">
                                                                <tbody>
                                                                    <tr>
                                                                        <td colspan="2"><label><input type="checkbox" value="1" name="ChkDiagnosis" <?php if($row7['ChkDiagnosis'] == '1'){?> checked <?php } ?> /> Diagnosis</label></td>
                                                                    </tr>
                                                                    <tr>
                                                                        <td><input type="text" id="Diagnosis" name="Diagnosis" value="<?php echo $row7['Diagnosis'];?>" list="diagnosislist" class="form-control"></td>
                                                                    </tr>
                                                                </tbody>
                                                            </table>
                                                            <datalist id="diagnosislist">
                                                                <?php 
                                                                $sql_11 = "SELECT DISTINCT(Diagnosis) AS Diagnosis FROM tbl_consultant";
                                                                $row_11 = getList($sql_11);
                                                                foreach($row_11 as $result){?>
                                                                    <option value="<?php echo $result['Diagnosis'];?>">
                                                                <?php } ?>
                                                            </datalist>
                                                        </div>
                                                    </fieldset>

                                                    <fieldset>
                                                        <div class="table-responsive">
                                                            <table class="table table-bordered table-striped mb-0 opd-table">
                                                                <tbody>
                                                                    <tr><td><label><input type="checkbox" value="1" name="ChkAdvice" <?php if($row7['ChkAdvice'] == '1'){?> checked <?php } ?> /> Advised</label></td></tr>
                                                                    <tr>
                                                                        <td>
                                                                            <input type="text" id="Remark" name="Remark" value="<?php echo $row7['Remark'];?>" list="rmk" class="form-control" oninput="ShortPtName33('Remark')">
                                                                        </td>
                                                                    </tr>
                                                                </tbody>
                                                            </table>
                                                        </div>
                                                    </fieldset>

                                                    <fieldset>
                                                        <div class="col-sm-12 sub_btn" style="padding-top:10px;">
                                                            <label><input type="checkbox" value="1" name="NameUnder" <?php if($row7['NameUnder'] == '1'){?> checked <?php } ?> /> PNB</label><br><br>
                                                            <button class="btn btn-success" type="submit" name="submit" id="submit">Save </button>
                                                            <button class="btn btn-danger" type="button" onclick="deleteRecord()">Delete</button>
                                                            <button class="btn btn-info" type="button" onclick="printOpd()" id="print">Print</button>
                                                        </div>
                                                    </fieldset>

                                                </div>
                                            </div>
                                        </div>

                                        <!-- TAB: SUMMARY -->
                                        <div class="tab-pane fade" id="navs-wc-summary">
                                            <?php include 'opd-patient-summary.php';?>
                                        </div>
                                    </div>

                                </div> <!-- card-body -->
                            </div>
                        </div>
                    </div>
                </form>

            </div> <!-- container -->
        </div>
    </div>
</div>

<!-- Patient Note Modal (moved outside table) -->
<div id="myModal" class="modal fade" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Patient Note</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <input type="hidden" name="ptmrdno" id="ptmrdno" value="<?php echo $MrdNo; ?>">
                <input type="hidden" name="ptvisitdate" id="ptvisitdate" value="<?php echo $VisitDate; ?>">
                <textarea class="form-control" id="ptnotes" name="ptnotes" rows="3"><?php echo $row8['ptnotes'];?></textarea>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-info" onclick="savePtNotes()">Save</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<!-- Include footer scripts -->
<?php include_once 'footer_script.php'; include 'inccommonmodal.php'; ?>

<!-- JS: keep functions same but place at bottom to speed initial render -->
<script>
    // small utilities
    function isNumberKey(evt) {
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) return false;
        return true;
    }

    // Page functions (kept behavior intact)
    function patientSummary(){
        var MrdNo = $('#MrdNo').val();
        setTimeout(function() {
            window.open('view-patient-summary.php?mrdno='+MrdNo, 'PatientSummary', 'toolbar=1, scrollbars=1, location=1,statusbar=0, menubar=1, resizable=1, width=1500, height=1000');
        }, 1);
    }

    function briefSummary(){
        var MrdNo = $('#MrdNo').val();
        setTimeout(function() {
            window.open('view-brief-summary.php?mrdno='+MrdNo, 'PatientSummary', 'toolbar=1, scrollbars=1, location=1,statusbar=0, menubar=1, resizable=1, width=1500, height=1000');
        }, 1);
    }

    function deletedPatients() {
        setTimeout(function() {
            window.open('view-deleted-patients.php', 'deletedPatients', 'toolbar=1, scrollbars=1, location=1,statusbar=0, menubar=1, resizable=1, width=1500, height=1000');
        }, 1);
    }

    function deletePatient(){
        var action = "deletePatient";
        var MrdNo = $('#MrdNo').val();
        if(confirm("Are you sure?")){
            $.ajax({
                type: "POST",
                url: "ajax_files/ajax_patients.php",
                data: { action: action, MrdNo: MrdNo },
                success: function(data) {
                    alert("Patient Record Deleted!");
                    window.location.href ="patientdetailform.php";
                }
            });
        }
    }

    function checkVisitDate(val) {
        var action = "checkVisitDate";
        var MrdNo = $('#MrdNo').val();
        $.ajax({
            type: "POST",
            url: "ajax_files/ajax_patients.php",
            data: { action: action, val: val, MrdNo: MrdNo },
            success: function(data) {
                $('#VisitNo').val(data);
                window.location.href = "patientdetailform.php?mrd=" + MrdNo + "&visitdate=" + val;
            }
        });
    }

    function checkShortKey(id) {
        var ShortKey = $('#ShortKey' + id).val();
        var action = "checkShortKey";
        $.ajax({
            type: "POST",
            url: "ajax_files/ajax_patients.php",
            data: { action: action, TreatName: ShortKey },
            success: function(data) {
                var res = JSON.parse(data);
                var Status = res.Status;
                var TreatName = res.TreatName;
                if (Status == 1) {
                    $('#TreatName' + id).val(TreatName);
                }
            }
        });
    }

    function savePtNotes() {
        var ptmrdno = $('#ptmrdno').val();
        var ptvisitdate = $('#ptvisitdate').val();
        var ptnotes = $('#ptnotes').val();
        var action = "savePtNotes";
        $.ajax({
            type: "POST",
            url: "ajax_files/ajax_patients.php",
            data: { action: action, MrdNo: ptmrdno, VisitDate: ptvisitdate, ptnotes: ptnotes },
            success: function(data) {
                if (data == 1) {
                    $('#myModal').modal('hide');
                }
            }
        });
    }

    function getNewMrdNo() {
        window.location.href = 'patientdetailform.php?val=new';
    }

    function getPatientDetails() {
        var MrdNo = $('#MrdNo').val();
        var action = 'getPatientDetails';
        $('#PatientId').val('');
        $.ajax({
            type: "POST",
            url: "ajax_files/ajax_patients.php",
            data: { action: action, id: MrdNo },
            success: function(data) {
                var res = JSON.parse(data);
                var dataRow = res.row;
                var Age = res.Age;
                $('#PatientName').val(dataRow.PatientName);
                $('#Fname').val(dataRow.Fname);
                $('#Mname').val(dataRow.Mname);
                $('#Lname').val(dataRow.Lname);
                $('#Gender').val(dataRow.Gender).attr('selected', true);
                $('#Age').val(Age);
                $('#Phone').val(dataRow.Phone);
                $('#Address').val(dataRow.Address);
                $('#Notes').val(dataRow.History);
                $('#Remark').val(dataRow.Stressor);
                $('#City').val(dataRow.City);
                if(dataRow.Language == 'E'){
                    $('#Mlanguage').prop('checked',false);
                    $('#Hlanguage').prop('checked',false);
                    $('#Elanguage').val('E').prop('checked',true);
                } else if(dataRow.Language == 'H'){
                    $('#Hlanguage').val('H').prop('checked',true);
                    $('#Mlanguage').prop('checked',false);
                    $('#Elanguage').prop('checked',false);
                } else {
                    $('#Mlanguage').val('M').prop('checked',true);
                    $('#Hlanguage').prop('checked',false);
                    $('#Elanguage').prop('checked',false);
                }

                if(dataRow.ptnotes == undefined || dataRow.ptnotes == ''){
                    $('#PatientId').css("background-color","chartreuse");
                    $('#myModal').modal("hide");
                    $('#ptnotes').val('');
                } else {
                    $('#PatientId').css("background-color","red");
                    $('#myModal').modal("show");
                    $('#ptnotes').val(dataRow.ptnotes);
                }
                getVisitDate(MrdNo);
                getPatientSummary(MrdNo);
                $('#ptmrdno').val(MrdNo);
                getMaxMrdno(MrdNo);
                blankPrevDate();
            }
        });
    }

    function checkCounsultant(MrdNo) {
        var action = 'checkCounsultant';
        $.ajax({
            type: "POST",
            url: "ajax_files/ajax_patients.php",
            data: { action: action, id: MrdNo },
            success: function(data) {
                var res = JSON.parse(data);
                $('#Notes').val(res.History);
                $('#Remark').val(res.Stressor);
            }
        });
    }

    function getMaxMrdno(MrdNo) {
        var action = 'getMaxMrdno';
        var VisitDate = $('#VisitDate2').val();
        $.ajax({
            type: "POST",
            url: "ajax_files/ajax_patients.php",
            data: { action: action, MrdNo: MrdNo, VisitDate: VisitDate },
            success: function(data) {
                $('#VisitNo').val(data);
            }
        });
    }

    function blankPrevDate() {
        var CurrDate = $('#CurrDate').val();
        $("input[name='Telugu']").val(0).attr('checked', false);
        $("input[name='DM']").val(0).attr('checked', false);
        $("input[name='HT']").val(0).attr('checked', false);
        $("input[name='IHD']").val(0).attr('checked', false);
        $("input[name='PILES']").val(0).attr('checked', false);
        $("input[name='Thyroid']").val(0).attr('checked', false);
        $("input[name='Other']").val(0).attr('checked', false);
        $("input[name='OtherTxt']").val('');
        $("input[name='Prognosis']").val(0).attr('checked', false);
        $("input[name='DSH']").val(0).attr('checked', false);
        $("input[name='FollowUp']").val(0).attr('checked', false);
        $("input[name='Irregular']").val(0).attr('checked', false);
        $("input[name='Medication']").val(0).attr('checked', false);
        $("input[name='StrictSupervision']").val(0).attr('checked', false);
        $("input[name='Admission']").val(0).attr('checked', false);
        $("input[name='ChkBlood']").val(0).attr('checked', false);
        $("input[name='Eeg']").val(0).attr('checked', false);
        $("input[name='ChkCT']").val(0).attr('checked', false);
        $("input[name='ChkMRI']").val(0).attr('checked', false);
        $("input[name='ChkUSG']").val(0).attr('checked', false);
        $("input[name='ChkOthers']").val(0).attr('checked', false);
        $("input[name='TxtBlood']").val('');
        $("input[name='TxtEeg']").val('');
        $("input[name='TxtCT']").val('');
        $("input[name='TxtMRI']").val('');
        $("input[name='TxtUSG']").val('');
        $("input[name='TxtOthers']").val('');
        $('#Diagnosis').val('');
        $('#SpecialNote').val('');
        $('#Duration').val(0);
        $('#FollowUpDate').val(CurrDate);
        $('#prevtreatments').html('');
        $('#PrevTreatment').val('');
    }

    function getPatientDetails2(MrdNo) {
        var action = 'getPatientDetails';
        $.ajax({
            type: "POST",
            url: "ajax_files/ajax_patients.php",
            data: { action: action, id: MrdNo },
            success: function(data) {
                var res = JSON.parse(data);
                var dataRow = res.row;
                var Age = res.Age;
                $('#PatientName').val(dataRow.PatientName);
                $('#MrdNo').val(dataRow.MrdNo);
                $('#Fname').val(dataRow.Fname);
                $('#Mname').val(dataRow.Mname);
                $('#Lname').val(dataRow.Lname);
                $('#Gender').val(dataRow.Gender).attr('selected', true);
                $('#Age').val(Age);
                $('#Phone').val(dataRow.Phone);
                $('#Address').val(dataRow.Address);
                if(dataRow.Language == 'E'){
                    $('#Mlanguage').prop('checked',false);
                    $('#Hlanguage').prop('checked',false);
                    $('#Elanguage').val('E').prop('checked',true);
                } else if(dataRow.Language == 'H'){
                    $('#Hlanguage').val('H').prop('checked',true);
                    $('#Mlanguage').prop('checked',false);
                    $('#Elanguage').prop('checked',false);
                } else {
                    $('#Mlanguage').val('M').prop('checked',true);
                    $('#Hlanguage').prop('checked',false);
                    $('#Elanguage').prop('checked',false);
                }
                $('#City').val(dataRow.City);
                getVisitDate(dataRow.MrdNo);
                getPatientSummary(dataRow.MrdNo);
                checkCounsultant(dataRow.MrdNo);
                $('#ptmrdno').val(dataRow.MrdNo);
                getMaxMrdno(dataRow.MrdNo);
                blankPrevDate();

                if(dataRow.ptnotes == undefined || dataRow.ptnotes == ''){
                    $('#PatientId').css("background-color","chartreuse");
                    $('#myModal').modal("hide");
                    $('#ptnotes').val('');
                } else {
                    $('#PatientId').css("background-color","red");
                    $('#myModal').modal("show");
                    $('#ptnotes').val(dataRow.ptnotes);
                }
            }
        });
    }

    function getNewMrdNo2() {
        if ($('#getNewMrdNo').prop('checked') == true) {
            var newmrdno = $('#newmrdno').val();
            $('#MrdNo').val(newmrdno);
        } else {
            $('#MrdNo').val('');
        }
    }

    function copyRecord() {
        var MrdNo = $('#MrdNo').val();
        var VisitDate = $('#VisitDate').val();
        var action = 'copyRecord';
        $.ajax({
            type: "POST",
            url: "ajax_files/ajax_patients.php",
            data: { action: action, MrdNo: MrdNo, VisitDate: VisitDate },
            beforeSend: function() {
                $('#copybtn').attr('disabled', 'disabled');
                $('#copybtn').text('Copied...');
            },
            success: function(data) {
                $('.pastebtn').show();
                $('#copybtn').attr('disabled', false);
                $('#copybtn').text('Copy');
            }
        });
    }

    function getPatientSummary(MrdNo) {
        var action = 'getPatientSummary';
        $.ajax({
            type: "POST",
            url: "ajax_files/ajax_patients.php",
            data: { action: action, id: MrdNo },
            success: function(data) {
                $('#navs-wc-summary').html(data);
            }
        });
    }

    function getVisitDate(MrdNo) {
        var action = 'getVisitDate';
        $.ajax({
            type: "POST",
            url: "ajax_files/ajax_patients.php",
            data: { action: action, MrdNo: MrdNo },
            success: function(data) {
                $('#VisitDate').html(data);
            }
        });
    }

    function getUpRecordList() {
        var MrdNo = $('#MrdNo').val();
        var action = 'getUpRecordList';
        $.ajax({
            type: "POST",
            url: "ajax_files/ajax_opto_form.php",
            data: { action: action, MrdNo: MrdNo },
            success: function(data) {
                $('#customers').html(data);
                $('#myModal22').modal("show");
            }
        });
    }

    function chkInvst(chk, val) {
        var val = $("input[name=" + val + "]").val();
        if (val == '') {
            $("input[name=" + chk + "]").val(0).attr('checked', false);
        } else {
            $("input[name=" + chk + "]").val(1).attr('checked', true);
        }
    }

    function ShortPtName33(val){
        var ShortKey = $('#'+val).val();
        var action = "checkShortKey";
        $.ajax({
            type: "POST",
            url: "ajax_files/ajax_patients.php",
            data: { action: action, TreatName: ShortKey },
            success: function(data) {
                var res = JSON.parse(data);
                var Status = res.Status;
                var TreatName = res.TreatName;
                if (Status == 1) {
                    $('#'+val).val(TreatName);
                }
            }
        });
    }

    $('.datalist').on('click', function() { $(this).val(''); });

    function deleteRecord() {
        var MrdNo = $('#MrdNo').val();
        var VisitDate = $('#VisitDate2').val();
        var action = 'deleteRecord';
        if(confirm("Are you sure?")){
            $.ajax({
                type: "POST",
                url: "ajax_files/ajax_opto_form.php",
                data: { action: action, MrdNo: MrdNo, VisitDate: VisitDate },
                success: function(data) {
                    alert('Record Deleted!');
                    window.location.href = 'patientdetailform.php';
                }
            });
        }
    }

    function removeTreatment(name, freq) { $('#' + name).val(''); $('#' + freq).val(''); }
    function removeTreatment2(name, freq,id) { $('#svtr'+id).hide(); $('#' + name).val(''); $('#' + freq).val(''); }

    function getValue(val, idval) {
        $('#ModalValue').val(val);
        $('#ValueId').val(idval);
        $('#OldValue').val('');
        desc_lists(val);
    }

    function checkFollowDate(val) {
        var action = 'checkFollowDate';
        $.ajax({
            type: "POST",
            url: "ajax_files/ajax_follow_date.php",
            data: { action: action, val: val },
            success: function(data) {
                if (data == '') {
                    $('#submit').attr("disabled", false);
                    $('#print').attr("disabled", false);
                    $('#followcheck').html(data);
                } else {
                    $('#submit').attr("disabled", true);
                    $('#print').attr("disabled", true);
                    $('#followcheck').html(data);
                }
            }
        });
    }

    function getFnameCap(val) {
        const str = $('#' + val).val();
        const str2 = str.charAt(0).toUpperCase() + str.slice(1);
        $('#' + val).val(str2);
    }

    function getFnameCap2(val) {
        const str = $('#' + val).val();
        const str2 = str.toUpperCase();
        $('#' + val).val(str2);
    }

    function printOpd() {
        var MrdNo = $('#MrdNo').val();
        var VisitDate = $('#VisitDate').val();
        window.open('opd-print.php?mrd=' + MrdNo + '&visitdate=' + VisitDate, 'name', 'toolbar=1, scrollbars=1, location=1,statusbar=0, menubar=1, resizable=1, width=800, height=600');
    }

    function pressTab(val) {
        if (val == 3) $('.sub_btn').hide(); else $('.sub_btn').show();
    }

    function getConsultRec(val) {
        var MrdNo = $('#MrdNo').val();
        window.location.href = "patientdetailform.php?mrd=" + MrdNo + "&visitdate=" + val;
    }

    function findFollowDate() {
        var action = 'findFollowDate';
        var Duration = $('#Duration').val();
        $.ajax({
            type: "POST",
            url: "ajax_files/ajax_opto_form.php",
            data: { action: action, Duration: Duration },
            success: function(data) {
                var res = JSON.parse(data);
                var Status = res.Status;
                var Followdate = res.FollowDate;
                if (Status == 0) {
                    $('#submit').attr("disabled", true);
                    $('#print').attr("disabled", true);
                    $('#followcheck').html('Sunday Holiday');
                    $('#FollowUpDate').val(Followdate);
                } else {
                    $('#FollowUpDate').val(Followdate);
                    checkFollowDate(Followdate);
                    $('#submit').attr("disabled", false);
                    $('#print').attr("disabled", false);
                }
            }
        });
    }

    // ready
    $(document).ready(function() {
        $('#MrdNo').focus();
        $('#MrdNo').select();

        $('#add_more').click(function() {
            var action = 'addMore';
            $.ajax({ type: "POST", url: "ajax_files/ajax_treatments.php", data: { action: action }, success: function(data) { $('#dynamic_field').append(data); } });
        });

        $(document).on('click', '.btn_remove', function() {
            var button_id = $(this).attr("id");
            $('#row' + button_id + '').remove();
        });
    });

    // scroll to top button
    var mybutton = document.getElementById("myBtn");
    window.onscroll = function() { scrollFunction(); };
    function scrollFunction() {
        if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) mybutton.style.display = "block"; else mybutton.style.display = "none";
    }
    function topFunction() { document.body.scrollTop = 0; document.documentElement.scrollTop = 0; }
</script>

<button onclick="topFunction()" id="myBtn" title="Go to top">Top</button>
</body>
</html>
