<!-- CSS -->

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@9/swiper-bundle.min.css" />

<!-- JavaScript -->

<script src="https://cdn.jsdelivr.net/npm/swiper@9/swiper-bundle.min.js"></script>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.css" />
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.js"></script>



<style>
    .after {
        color: blue;
    }

    .before {
        color: green;
    }

    .any {
        color: palevioletred;
    }

    /* datatavle section */
    .dataTables_wrapper .dataTables_length {
        display: none;
    }

    .dataTables_info {
        display: none;
    }

    /* datatavle section */

    /* Image Slider Section */
    .image-slider-container {
        display: flex;
        justify-content: flex-end;
    }

    .swiper-container {
        position: relative;
    }

    .swiper-button-prev,
    .swiper-button-next,
    .swiper-pagination-bullet {
        color: #696cff !important;
    }

    .swiper-pagination-bullet-active {
        background: #696cff !important;
    }

    /* Image Slider Section */

    /*Cart  table Section */
    .table-wrapper {
        max-width: 500px;
        overflow-x: auto;
    }

    .table {
        font-size: 14px;
        /* set a smaller font size */
    }


    .containers {
        width: 100%;
        height: 250px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        text-align: right;
    }

    .label {
        width: 150px;

        float: right;
        font-weight: bold;
    }

    .values {
        width: 80px;
        float: right;
    }

    .line {
        width: 70%;
        border-top: 1px solid #ccc;
        margin: 20px 0;
        align-self: flex-end;
    }

    .confirm-btn {
        padding: 10px 20px;
        background-color: #007bff;
        color: white;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        font-size: 16px;
    }

    /* grey cancel button css */
    .cancel-btn {
        padding: 10px 20px;
        background-color: #6f6f6f;
        color: white;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        font-size: 16px;
    }

    .spacer {
        flex-grow: 1;
    }

    /* space between keep and cancel button */
    .betweenSpacer {
        flex-grow: .3;
    }


    /*Cart  table Section */

    /*Cart popup Section */

    .form-popup-inputs {
        margin-top: 15px;
        display: flex;
        flex-direction: row;
        align-items: center;
    }

    .form-popup-inputs label {
        margin-right: 10px;
        min-width: 150;
    }

    .form-select {
        margin-top: 10px;
    }

    .form-check {
        width: 80px;
        align-items: left;
    }

    .form-price {
        text-align: right;
    }

    .form-price label {

        margin-right: 10px;
        font-size: 20px;
    }

    /*Cart popup Section */


    .fancybox-button--arrow_left,
    .fancybox-button--arrow_right {
        display: none !important;
    }

    /* .containers {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
}

.buttons-container {
  display: flex;
  gap: 10px;
}

.print-btn {
  width: 200px;
} */
</style>

<?php $__env->startSection('content'); ?>
    <div id="product_cart" class="container-xxl flex-grow-1 container-p-y">
        <div class="row">
            <div class="col-12 col-lg-12 order-2 order-md-3 order-lg-2 mb-4">
                <div class="card">
                    <div class="row row-bordered">
                        <div id="left_cart" class="col-md-4">

                            
                            <h5 style="padding: 20px 0; text-align: center; border-bottom: 1px solid #ccc;">

                                <?php if($PrescriptionOrderId->gen_status == 1): ?>
                                    <span class="badge rounded-pill bg-success"><?php echo e(__('genericMedicine')); ?>

                                        <?php echo e(__('yes')); ?></span>
                                <?php elseif($PrescriptionOrderId->gen_status == 0): ?>
                                    <span class="badge rounded-pill bg-danger"><?php echo e(__('genericMedicine')); ?>

                                        <?php echo e(__('no')); ?></span>
                                <?php else: ?>
                                    <span class="badge rounded-pill bg-primary"><?php echo e(__('genericMedicine')); ?> --</span>
                                <?php endif; ?>
                            </h5>

                            <div style="margin: 20px;">
                                <table id="medicineDataTable" class="table" cellspacing="0">

                                    <thead>
                                        <tr>
                                            <th><?php echo e(__('productList')); ?></th>
                                        </tr>
                                    </thead>

                                    <tbody class="table-border-bottom-0">
                                        <?php $__currentLoopData = $medicineListModel; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <tr>
                                                <td>
                                                    <div style="display: flex; align-items: start;">
                                                        <div style="margin-right: 10px;">
                                                            <img src="<?php echo e(asset('uploads/shop_' . $a_user_id->id . '/medicines/' . $item->image)); ?>"
                                                                width="50px" height="50px" alt="Img">
                                                        </div>
                                                        <div>
                                                            <div style="font-weight: bold;"><?php echo e($item->title); ?></div>
                                                            <div style="color: gray;"><?php echo e($item->type); ?></div>
                                                            <div>
                                                                Price: <?php echo e($item->price); ?>¥
                                                            </div>
                                                            
                                                            
                                                        </div>
                                                        <div style="margin-left: auto; display: flex; align-items: center;">
                                                            <div>
                                                                <button
                                                                    onclick="addClick( <?php echo e($item->id); ?>, '<?php echo e($item->title); ?>', '<?php echo e($item->type); ?>', '<?php echo e($item->image); ?>',  <?php echo e($item->price); ?>, <?php echo e($item->days); ?>,  <?php echo e($item->daily_dose); ?>,  <?php echo e($item->piese_per_dose); ?>,  <?php echo e($item->instruction); ?>,  <?php echo e($item->stock_status); ?>)"
                                                                     class="btn btn-primary"
                                                                    style="padding: 5px 5px;">
                                                                    <i class="fa fa-shopping-cart"
                                                                        style="margin-right: 5px;"></i>
                                                                    <?php echo e(__('add')); ?></button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </td>


                                            </tr>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>




                        <div id="mid_cart" class="col-md-4">
                            <h3 style="padding: 20px 0; text-align: center; border-bottom: 1px solid #ccc;">
                                <?php echo e(__('cart')); ?></h3>

                            <div class="card">
                                
                                <div class="table-wrapper" style="max-width: 100%">
                                    <table class="table" id="cart-table">

                                        <thead>
                                            <tr>
                                                <th>
                                                </th>
                                            </tr>
                                        </thead>

                                        

                                        <tbody class="table-border-bottom-0">
                                        </tbody>
                                    </table>
                                </div>


                                
                            </div>
                            <h3 style="padding: 10px;  border-bottom: 1px solid #ccc;"></h3>

                            <div class="containers">

                                <div class="technical-container" id="technicalContainer">
                                    <div class="values" id="technicalFee">0¥</div>
                                    <div class="label">(+) <?php echo e(__('technicalFee')); ?>:</div>

                                </div>
                                <div class="management-container" id="managementContainer">
                                    <div class="values" id="managementFee">0¥</div>
                                    <div class="label">(+) <?php echo e(__('managementFee')); ?>:</div>

                                </div>
                                <div class="material-container" id="materialContainer">
                                    <div class="values" id="materialCost">0¥</div>
                                    <div class="label">(+) <?php echo e(__('materialCost')); ?>:</div>

                                </div>

                                <div class="sub-container">
                                    <div class="values" id="idSubtotal">0¥</div>
                                    <div class="label"><?php echo e(__('subTotal')); ?>:</div>

                                </div>
                                <div class="Ins-container">
                                    <div class="values" id="idIns">0¥</div>
                                    <div class="label">(-) <?php echo e(__('insurance')); ?>:</div>

                                </div>

                                
                                <div class="line"></div>
                                <div class="sub-container">
                                    <div class="values" id="idTotal">0¥</div>
                                    <div class="label"><?php echo e(__('total')); ?>:</div>

                                </div>
                                <div class="spacer"></div>
                                <button onclick="confirm()" class="confirm-btn"
                                    style="margin-top: 10px"><?php echo e(__('confirm')); ?></button>
                                
                                <div class="betweenSpacer"></div>
                                <button onclick="cancel()" class="cancel-btn"
                                    style="margin-top: 10px"><?php echo e(__('cancel')); ?></button>


                                <!-- technicalFeemanagementFeematerialCost -->
                                <!-- <div class="mb-3" style="margin-right: 10px">
                                    <div style="padding: 5px; margin: 10px 0 0 0">
                                        <label for="technical" style="float: left;"><?php echo e(__('technicalFee')); ?></label>
                                    </div>
                                    <input type="text" name="technical" id="technical"
                                        class="form-control">
                                    <div style="padding: 5px; margin: 10px 0 0 0">
                                        <label for="management" style="float: left;"><?php echo e(__('managementFee')); ?></label>
                                    </div>
                                    <input type="text" name="management" id="management"
                                        class="form-control">
                                    <div style="padding: 5px; margin: 10px 0 0 0">
                                        <label for="material" style="float: left;"><?php echo e(__('materialCost')); ?></label>
                                    </div>
                                    <input type="text" name="material" id="material"
                                        class="form-control">
                                </div> -->


                                
                            </div>


                        </div>

                        <div id="right_cart" class="col-md-4">
                            <h3 style="padding: 20px 0; text-align: center; border-bottom: 1px solid #ccc;">
                                <?php echo e(__('prescriptions')); ?>

                            </h3>

                            <div class="image-slider-container">
                                <div class="swiper-container">
                                    <div class="swiper-wrapper">
                                        <?php
                                            $imglist = explode(';', $PrescriptionOrderId->p_image);
                                            foreach($imglist as $vlist) {
                                        ?>
                                        <div class="swiper-slide">
                                            <a data-fancybox="gallery" href="<?php echo e(asset($vlist)); ?>">
                                                <img src="<?php echo e(asset($vlist)); ?>" />
                                            </a>
                                        </div>
                                        <?php
                                            }
                                        ?>
                                    </div>
                                    <div class="swiper-button-prev"></div>
                                    <div class="swiper-button-next"></div>
                                    <div class="swiper-pagination"></div>
                                </div>
                            </div>



                            <h5 style="padding: 5px 0; text-align: center; border-bottom: 1px solid #ccc; margin-top:15px">
                                <?php echo e(__('insuranceCard')); ?>

                            </h5>
                            <div class="mb-3" style="margin-right: 10px" id="insurance">
                                <label for="card-number" style="float: left;"><?php echo e(__('typesOfHealth')); ?>.</label>
                                <select class="form-select" id="selectInsurance" aria-label="selectInsurance">
                                    <option value="0"><?php echo e(__('none')); ?></option>
                                    <option value="1"><?php echo e(__('nationalHealth')); ?></option>
                                    <option value="2"><?php echo e(__('socialInsurance')); ?></option>
                                    <option value="3"><?php echo e(__('nationalPublic')); ?></option>
                                    <option value="4"><?php echo e(__('mutualAid')); ?></option>
                                    <option value="5"><?php echo e(__('fedarationHealth')); ?></option>
                                    <option value="6"><?php echo e(__('selfDefence')); ?></option>
                                    <option value="7"><?php echo e(__('welfarePension')); ?></option>

                                </select>
                            </div>

                            <div class="mb-3" style="margin-right: 10px" id="limitDiv">
                                <label for="card-number" style=" float: left;"><?php echo e(__('limit')); ?>%</label>
                                <input class="form-control" type="number" list="datalistOptions" id="selectLimit"
                                    oninput="limitChange()" placeholder="Enter Limit" />
                                <datalist id="datalistOptions">
                                    <option value="70"></option>
                                    <option value="80"></option>
                                    <option value="90"></option>
                                    <option value="100"></option>
                                </datalist>
                            </div>


                            <div class="mb-3" style="margin-right: 10px">
                                <div style="padding: 5px; margin: 0 0 25px 0">
                                    <label for="card-number" style="float: left;"><?php echo e(__('cardNo')); ?>.</label>

                                    <input class="form-check-input" type="checkbox" id="verify_tik"
                                        style="float: right;">
                                    <label for="verified"
                                        style="float: right; margin-right:10px;"><?php echo e(__('verified')); ?></label>
                                </div>
                                <input type="text" name="ins_code" id="ins_code"
                                    class="form-control"placeholder="<?php echo e(__('enterCardNo')); ?>.">


                                <!-- technicalFeemanagementFeematerialCost -->
                                <div class="mb-3" style="margin-right: 10px">
                                    <div style="padding: 5px; margin: 10px 0 0 0">
                                        <label for="technical" style="float: left;"><?php echo e(__('technicalFee')); ?></label>
                                    </div>
                                    <input type="number" name="technical" id="technical" class="form-control"  oninput="technicalChange()" >
                                    <div style="padding: 5px; margin: 10px 0 0 0">
                                        <label for="management" style="float: left;"><?php echo e(__('managementFee')); ?></label>
                                    </div>
                                    <input type="number" name="management" id="management" class="form-control" oninput="managementChange()">
                                    <div style="padding: 5px; margin: 10px 0 0 0">
                                        <label for="material" style="float: left;"><?php echo e(__('materialCost')); ?></label>
                                    </div>
                                    <input type="number" name="material" id="material" class="form-control" oninput="materialChange()">
                                </div>

                            </div>



                            <h5 style="padding: 5px 0; text-align: center; border-bottom: 1px solid #ccc; margin-top:15px">
                                <?php echo e(__('orderBasicInfo')); ?>

                            </h5>
                            <div class="mb-3" style="margin-right: 10px">
                                <div style="padding: 5px; margin: 10px 0 0 0">
                                    <label for="hospital" style="float: left;"><?php echo e(__('hospitalName')); ?></label>
                                </div>
                                <input type="text" name="hospital" id="hospital"
                                    class="form-control"placeholder="<?php echo e(__('enterHospitalName')); ?>">
                                <div style="padding: 5px; margin: 10px 0 0 0">
                                    <label for="department" style="float: left;"><?php echo e(__('departmentName')); ?></label>
                                </div>
                                <input type="text" name="department" id="department"
                                    class="form-control"placeholder="<?php echo e(__('enterDepartmentName')); ?>">
                                <div style="padding: 5px; margin: 10px 0 0 0">
                                    <label for="doctor_name" style="float: left;"><?php echo e(__('doctorName')); ?></label>
                                </div>
                                <input type="text" name="doctor_name" id="doctor_name"
                                    class="form-control"placeholder="<?php echo e(__('enterDoctorName')); ?>">
                            </div>


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

            </div>

        </div>


        <!-- add Modal -->
        <div class="modal fade" id="addModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel"><?php echo e(__('addMedicineCart')); ?></h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>

                    <div class="modal-body">

                        <div class="form-group text-right">
                            <label><b class="font-weight-bold" id="Medicine-title">---</b></label>
                        </div>

                        <h3 style="padding: 10px;  border-bottom: 1px solid #ccc;"></h3>

                        <div class="form-popup-inputs">
                            <label for="quantity"><?php echo e(__('quantity')); ?> :</label>
                            <input type="number" class="form-control" id="quantity" value="1" min="1"
                                oninput="quantityChanged()">
                        </div>

                        <div class="form-popup-inputs">
                            <label for="days"><?php echo e(__('periodOfUse')); ?> :</label>
                            <input type="number" class="form-control" id="days" value="1" min="1"
                                oninput="daysChanged()">

                        </div>

                        <div class="form-popup-inputs">
                            <label for="daily_dose"><?php echo e(__('timeInDay')); ?> :</label>
                            <input type="number" class="form-control" id="daily_dose" value="1" min="1"
                                oninput="daily_doseChanged()">

                        </div>

                        <div class="form-popup-inputs">
                            <label for="piese_per_dose"><?php echo e(__('numberPieses')); ?> :</label>
                            <input type="number" class="form-control" id="piese_per_dose" value="1"
                                min="1" oninput="piese_per_dosehanged()">

                        </div>

                        <div class="form-popup-inputs">
                            <label for="instruction"><?php echo e(__('instruction')); ?> :</label>

                            <div class="form-check">
                                <input name="default-radio-1" class="form-check-input" type="radio" value=""
                                    id="defaultRadio1" checked="">
                                <label class="form-check-label" for="defaultRadio1"> <?php echo e(__('after')); ?> </label>
                            </div>

                            <div class="form-check">
                                <input name="default-radio-1" class="form-check-input" type="radio" value=""
                                    id="defaultRadio2">
                                <label class="form-check-label" for="defaultRadio2"> <?php echo e(__('before')); ?> </label>
                            </div>


                            <div class="form-check">
                                <input name="default-radio-1" class="form-check-input" type="radio" value=""
                                    id="defaultRadio3">
                                <label class="form-check-label" for="defaultRadio3"> <?php echo e(__('any')); ?> </label>
                            </div>

                        </div>

                        <select class="form-select" id="selectTimes" aria-label="SelectMeal">
                            <option selected=""><?php echo e(__('selectTimings')); ?></option>
                            <option value="1"><?php echo e(__('breakfast')); ?></option>
                            <option value="2"><?php echo e(__('lunch')); ?></option>
                            <option value="3"><?php echo e(__('dinner')); ?></option>
                            <option value="4"><?php echo e(__('breakfastDinner')); ?></option>
                            <option value="5"><?php echo e(__('morningLunch')); ?></option>
                            <option value="6"><?php echo e(__('lunchDinner')); ?></option>
                            <option value="7"><?php echo e(__('breakfastLunchDinner')); ?></option>
                            <option value="8"><?php echo e(__('everyMeal')); ?></option>
                            <option value="9"><?php echo e(__('betweenMeals')); ?></option>
                            <option value="10"><?php echo e(__('fasting')); ?></option>
                            <option value="11"><?php echo e(__('goingToBed')); ?></option>
                            <option value="12"><?php echo e(__('every4hours')); ?></option>
                            <option value="13"><?php echo e(__('every8hours')); ?></option>
                        </select>
                        <div id="warningMessage" style="display: none; color: red;">Please select a valid option.</div>


                        <div class="form-popup-inputs">
                            <label for="addNote"><?php echo e(__('addNote')); ?> :</label>
                        </div>
                        
                        <input type="text" class="form-control" id="addNote">

                        <h3 style="padding: 10px;  border-bottom: 1px solid #ccc;"></h3>

                        <div class="form-price">
                            <label><b class="font-weight-bold" id="price"><?php echo e(__('price')); ?> :</b></label>
                            <label id="price-value" for="price">2000¥</label>
                        </div>

                    </div>

                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary"
                            data-bs-dismiss="modal"><?php echo e(__('cancel')); ?></button>
                        
                        <button onclick="addtoCart()" type="button" class="btn btn-primary"
                            id="addToCart"><?php echo e(__('addCart')); ?></button>
                    </div>
                </div>
            </div>
        </div>

        <!--edit Modal -->
        <div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel"><?php echo e(__('editMedicineCart')); ?></h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>

                    <div class="modal-body">

                        <div class="form-group text-right">
                            <label><b class="font-weight-bold" id="medi_title"> --- </b></label>
                        </div>

                        <h3 style="padding: 10px;  border-bottom: 1px solid #ccc;"></h3>

                        <div class="form-popup-inputs">
                            <label for="quantity"><?php echo e(__('quantity')); ?> :</label>
                            <input type="number" class="form-control" id="edit-quantity" value="1" min="1"
                                oninput="editquantityChanged()">

                        </div>
                        <div class="form-popup-inputs">
                            <label for="days"><?php echo e(__('periodOfUse')); ?> :</label>
                            <input type="number" class="form-control" id="edit-days" value="1" min="1"
                                oninput="edit_daysChanged()">

                        </div>


                        <div class="form-popup-inputs">
                            <label for="daily_dose"><?php echo e(__('timeInDay')); ?> :</label>
                            <input type="number" class="form-control" id="edit_daily_dose" value="1"
                                min="1" oninput="edit_daily_doseChanged()">

                        </div>

                        <div class="form-popup-inputs">
                            <label for="piese_per_dose"><?php echo e(__('numberPieses')); ?> :</label>
                            <input type="number" class="form-control" id="edit_piese_per_dose" value="1"
                                min="1" oninput="edit_piese_per_dosehanged()">

                        </div>

                        <div class="form-popup-inputs">
                            <label for="instruction"><?php echo e(__('instruction')); ?> :</label>

                            <div class="form-check">
                                <input name="default-radio-1" class="form-check-input" type="radio" value=""
                                    id="edit_defaultRadio1" checked="">
                                <label class="form-check-label" for="edit_defaultRadio1"> <?php echo e(__('after')); ?> </label>
                            </div>

                            <div class="form-check">
                                <input name="default-radio-1" class="form-check-input" type="radio" value=""
                                    id="edit_defaultRadio2">
                                <label class="form-check-label" for="edit_defaultRadio2"> <?php echo e(__('before')); ?> </label>
                            </div>

                            <div class="form-check">
                                <input name="default-radio-1" class="form-check-input" type="radio" value=""
                                    id="edit_defaultRadio3">
                                <label class="form-check-label" for="edit_defaultRadio3"> <?php echo e(__('any')); ?> </label>
                            </div>

                        </div>

                        <select class="form-select" id="edit_selectTimes" aria-label="SelectMeal">
                            <option selected=""><?php echo e(__('selectTimings')); ?></option>
                            <option value="1"><?php echo e(__('breakfast')); ?></option>
                            <option value="2"><?php echo e(__('lunch')); ?></option>
                            <option value="3"><?php echo e(__('dinner')); ?></option>
                            <option value="4"><?php echo e(__('breakfastDinner')); ?></option>
                            <option value="5"><?php echo e(__('morningLunch')); ?></option>
                            <option value="6"><?php echo e(__('lunchDinner')); ?></option>
                            <option value="7"><?php echo e(__('breakfastLunchDinner')); ?></option>
                            <option value="8"><?php echo e(__('everyMeal')); ?></option>
                            <option value="9"><?php echo e(__('betweenMeals')); ?></option>
                            <option value="10"><?php echo e(__('fasting')); ?></option>
                            <option value="11"><?php echo e(__('goingToBed')); ?></option>
                            <option value="12"><?php echo e(__('every4hours')); ?></option>
                            <option value="13"><?php echo e(__('every8hours')); ?></option>

                        </select>

                        <div class="form-popup-inputs">
                            <label for="addNote"><?php echo e(__('addNote')); ?> :</label>
                        </div>

                        <input type="text" class="form-control" id="edit_addNotes">

                        <h3 style="padding: 10px;  border-bottom: 1px solid #ccc;"></h3>

                        <div class="form-price">
                            <label><b class="font-weight-bold" id="price"><?php echo e(__('price')); ?> :</b></label>
                            <label id="edit-price-value" for="price">2000¥</label>
                        </div>

                    </div>

                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary"
                            data-bs-dismiss="modal"><?php echo e(__('cancel')); ?></button>
                        <button onclick="updateCart()" type="button" class="btn btn-primary"
                            id="updateCart"><?php echo e(__('addCart')); ?></button>
                    </div>
                </div>
            </div>
        </div>

        <!--exist Modal -->
        <div class="modal fade" id="existModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel"><?php echo e(__('alreadyExists')); ?></h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body"> <?php echo e(__('removeItemOrEditExistingItem')); ?> </div>
                </div>
            </div>
        </div>


        <!--Verify Modal -->
        <div class="modal fade" id="verifyModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        
                        <h5 class="modal-title" id="exampleModalLabel">Health Insurance Verification</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    
                    <div class="modal-body">Please verify the 'Health Insurance' section before
                        saving the cart.</div>
                </div>
            </div>
        </div>
        <!--Invalid Cart Modal -->
        <div class="modal fade" id="invalidCartModal" tabindex="-1" aria-labelledby="exampleModalLabel"
            aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        
                        <h5 class="modal-title" id="exampleModalLabel">Empty cart can not be submitted !</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    
                    <div class="modal-body">An empty cart cannot be submitted. Please add medicine and try again.</div>
                </div>
            </div>
        </div>

        <!--outOfStock Modal -->
        <div class="modal fade" id="outOfStock" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel"><?php echo e(__('outStock')); ?></h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <?php echo e(__('itemOutStock')); ?>

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

        <!--fieldsEmptyModal -->
        <div class="modal fade" id="fieldsEmptyModal" tabindex="-1" aria-labelledby="exampleModalLabel"
            aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title"><?php echo e(__('fieldsEmpty')); ?></h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body" id="fieldsEmptyModalLabel">
                        Some fields are epmty
                    </div>
                </div>
            </div>
        </div>

        <script>
            $(document).ready(function() {
                $('#medicineDataTable').DataTable({
                    order: [0, 'asc'] // Sort by the first column (index 0) in ascending order
                });
            });

            var mySwiper = new Swiper('.swiper-container', {
                // Optional parameters
                direction: 'horizontal',
                // loop: true,

                // If you want to zoom in/out images
                zoom: {
                    maxRatio: 5,
                },

                pagination: {
                    el: '.swiper-pagination',
                    clickable: true,
                },

                // Navigation arrows
                navigation: {
                    nextEl: '.swiper-button-next',
                    prevEl: '.swiper-button-prev',
                },

                // Scrollbar
                scrollbar: {
                    //el: '.swiper-scrollbar',
                },
            });
        </script>


        <script>
            const checkbox = document.getElementById("verify_tik");
            const warningMessage = document.getElementById("warningMessage");

            var technicalContainer = document.getElementById('technicalContainer');
            technicalContainer.style.display = 'none';

            var managementContainer = document.getElementById('managementContainer');
            managementContainer.style.display = 'none';

            var materialContainer = document.getElementById('materialContainer');
            materialContainer.style.display = 'none';

            closeNav();
            var items = [];

            var subtotal = 0.0;
            var subMeditotal = 0.0;
            var tax = 0.0;
            var total = 0.0;
            var technicalInput = 0.0;
            var managementInput = 0.0;
            var materialInput = 0.0;

            var insCode = "";
            var insTotal = 0.0;
            var ins_type = 0;
            var ins_limit = 0;
            var hospital = "";
            var department = "";
            var doctor_name = "";



            var goForUpload = false;

            var orderDetailsModel = "<?php echo e($orderDetailsModel); ?>";
            var PrescriptionOrderId = "<?php echo e($PrescriptionOrderId); ?>";


            var orderDetails = JSON.parse(orderDetailsModel.replace(/&quot;/g, '"'));
            var PrescriptionOrderDetails = JSON.parse(PrescriptionOrderId.replace(/&quot;/g, '"'));
            console.log("-- -- -- -- -- -- -- -- -- -- -- -- -- -- --")

            // console.log(PrescriptionOrderDetails.m_types)
            console.log("<?php echo e($PrescriptionOrderId->department); ?>")
            console.log("-- -- -- -- -- -- -- -- -- -- -- -- -- -- --")
            getCartData();

            function medicineName(imageUrl) {

                imgdata = "<?php echo e(url('')); ?>/" + imageUrl;
                var base64Image;
                fetch(imgdata)
                    .then(response => response.blob())
                    .then(blob => {
                        const reader = new FileReader();
                        reader.onload = function() {
                            base64Image = reader.result.split(',')[1];
                            // console.log(base64Image);
                            var body = {
                                requests: [{
                                    image: {
                                        content: base64Image
                                    },
                                    features: [{
                                        type: "TEXT_DETECTION",
                                        maxResults: 1
                                    }],
                                    imageContext: {
                                        textDetectionParams: {
                                            enableTextDetectionConfidenceScore: false,
                                        },
                                    },
                                }]
                            };

                            $.ajax({
                                url: "https://vision.googleapis.com/v1/images:annotate?key=AIzaSyAFXREv1U-9Zjr0J6khYCYs1SLgpjzuYgM",
                                type: "POST",
                                contentType: "application/json",
                                data: JSON.stringify(body),
                                success: function(response) {
                                    var text = response.responses[0].textAnnotations[0].description;
                                    //extract necessary medicine name
                                    console.log(text);
                                    prescribedMed(text)
                                }
                            });
                        };
                        reader.readAsDataURL(blob);
                    })
                    .catch(error => {
                        console.error('Error fetching or converting the image:', error);
                    });
            }

            function prescribedMed(inputText) {
                var medicineListDiv = document.getElementById("med");
                var text = inputText
                const keywords = ["錠", "カプセル", "点眼", "点耳", "散剤", "シロップ", "注射", "軟膏", "吸入", "シール", "液体", "内服", "細粒", "ドロップス",
                    "ゼリー", "輸液", "粉末吸入", "貼付"
                ];
                const serials = ["。", "）", "\\)", ". ", "」", "①", "②", "③", "④", "⑤", "⑥", "⑦", "⑧"];
                const lines = text.split('\n');
                const linesWithKeywords = lines.filter(containsKeyword);

                function addSpaceBeforeMg(linesWithKeywords) {
                    return linesWithKeywords.replace(/(\d+)mg/g, '$1 mg');
                }

                function change125mg(linesWithKeywords) {
                    return linesWithKeywords.replace(/(\d+) (\d+)mg/g, '$1$2 mg');
                }
                let modifiedTexts = linesWithKeywords.map(text => change125mg(addSpaceBeforeMg(text)));
                const WithoutNumberofTablets = modifiedTexts.filter(containsNumberofTablets);
                const cleaninglines = WithoutNumberofTablets;
                const cleanedLines = WithoutNumberofTablets.map(removeIndexPrefix);
                const resultList = cleanedLines.join('\n');
                const medicineListText = resultList.split('\n');

                function removeIndexPrefix(cleaninglines) {
                    return cleaninglines.replace(/^\d+[).]/, '').trim();
                }

                function containsKeyword(line) {
                    return keywords.some(keyword => line.includes(keyword));
                }

                function containsNumberofTablets(linesWithKeyword) {
                    return !/\d+錠/.test(linesWithKeyword);
                }
                // console.log(medicineListText)
                //Checking Database for medicine after one has been found
                checkMedicine(medicineListText)
            }

            function checkMedicine(medicineListText) {
                var medicineList = <?php echo json_encode($medicineListModel); ?>;
                const foundItems = [];
                for (const titles of medicineListText) {
                    console.log('Medicine Checking', titles)
                    var foundMedicine = medicineList.find(function(medicine) {
                        return medicine.title === titles;

                    });
                    if (foundMedicine) {
                        // printing medicine info on cart
                        addMedicinesToCart(foundMedicine.id, foundMedicine.title, foundMedicine.type, foundMedicine.image,
                            foundMedicine.price, foundMedicine.daily_dose, foundMedicine.piese_per_dose, foundMedicine
                            .instruction, foundMedicine.stock_status)
                        console.log('Found medicine:', foundMedicine.title);
                    } else {
                        console.log('Medicine not found:', titles);
                    }
                    // break; // Exit the inner loop once a match is found for this item but this has multiple medicine in one presciption
                    // }
                }
            }


            function openNav() {
                if (window.screen.width > 1199) {
                    document.querySelector('.navbar-nav').classList.add('d-xl-none');
                    document.querySelector('.menu-link').classList.remove('d-xl-none');
                    document.getElementById("layout-menu").style.cssText = `

                    display: block;
                `;
                    document.getElementById("product_cart").style.cssText = `
                        display: block;
                        padding-right: var(--bs-gutter-x, 1.625rem);
                        padding-left: var(--bs-gutter-x, 1.625rem);
                        margin-right: auto;
                        margin-left: auto;
                        `;
                    document.getElementById("layout-navbar").style.cssText = `
                    position: relative;
                    padding-right: auto;
                    padding-left: auto;
                    margin-right: auto;
                    margin-left: auto;
                    padding-top: 0.25rem;
                    padding-bottom: 0.2rem;
                    height: 3.875rem;
                    flex-wrap: nowrap;
                    color: #697a8d;
                    z-index: 2;
                        `;
                    document.querySelector('.light-style').classList.remove('layout-menu-collapsed');


                }
            }

            function closeNav() {

                if (window.screen.width > 1199) {
                    document.querySelector('.menu-link').classList.add('d-xl-none');
                    document.querySelector('.navbar-nav').classList.remove('d-xl-none');
                    document.getElementById("layout-menu").style.cssText = `

                        display: none;
                    `;
                    document.getElementById("product_cart").style.cssText = `
                            display: block;
                            padding:0;
                            max-width: 100%;
                            padding-right: 3%;
                            padding-left: 3%;
                            margin-right: 0;
                            margin-left: 0;
                            flex-wrap: nowrap;
                            left: 0;
                            `;
                    document.getElementById("layout-navbar").style.cssText = `

                            padding-top: 0.25rem;
                            padding-bottom: 0.2rem;
                            max-width: 94%;
                            padding-right: 1%;
                            padding-left: 1%;
                            margin-right: 2%;
                            margin-left: 3%;
                            height: 3.875rem;
                            flex-wrap: nowrap;
                            color: #697a8d;
                            z-index: 2;
                            `;

                    document.querySelector('.light-style').classList.add('layout-menu-collapsed');


                }


            }

            var selectElement = document.getElementById("selectTimes");
            var selectinsurance = document.getElementById("selectInsurance");
            var selectlimit = document.getElementById("selectLimit");
            var limitDiv = document.getElementById("limitDiv");
            var insCardElement = document.getElementById("ins_code")


            var technicalElement = document.getElementById("technical")


            function getCartData() {

                console.log(PrescriptionOrderDetails.ins_code);
                console.log("incode");
                if (PrescriptionOrderDetails.ins_code != "" && PrescriptionOrderDetails.ins_code != null) {

                    console.log("incode if");
                    console.log(PrescriptionOrderDetails.ins_code);

                    document.getElementById("ins_code").value = PrescriptionOrderDetails.ins_code;
                    document.getElementById("selectLimit").value = PrescriptionOrderDetails.ins_limit;
                    ins_limit = PrescriptionOrderDetails.ins_limit;
                    document.getElementById("selectInsurance").value = PrescriptionOrderDetails.ins_type;

                } else if (PrescriptionOrderDetails.ins_code == null) {
                    console.log("incode else");
                    var limitDiv = document.getElementById("limitDiv");
                    var insCardElement = document.getElementById("ins_code")
                    limitDiv.style.display = "none";
                    insCardElement.disabled = true;
                    console.log(PrescriptionOrderDetails.ins_code);
                    document.getElementById('verify_tik').checked = false;
                }


                document.getElementById("hospital").value = PrescriptionOrderDetails.hospital;
                document.getElementById("department").value = PrescriptionOrderDetails.department;
                document.getElementById("doctor_name").value = PrescriptionOrderDetails.doctor_name;

                //technical , management, material

                if(PrescriptionOrderDetails.technicalInput != 0.0){

                     technicalInput = PrescriptionOrderDetails.technicalInput;
                    document.getElementById("technical").value = technicalInput;
                    // document.getElementById("technical").value = PrescriptionOrderDetails.technicalInput;
                    document.getElementById("technicalFee").innerText = technicalInput + "¥";
                    technicalContainer.style.display = 'block';

                }

                if(PrescriptionOrderDetails.managementInput != 0.0){

                     managementInput = PrescriptionOrderDetails.managementInput;
                    document.getElementById("management").value = managementInput;
                    // document.getElementById("management").value = PrescriptionOrderDetails.managementInput;
                    document.getElementById("managementFee").innerText = managementInput + "¥";
                    managementContainer.style.display = 'block';
                }

                if(PrescriptionOrderDetails.materialInput != 0.0){

                     materialInput = PrescriptionOrderDetails.materialInput;
                    document.getElementById("material").value = materialInput;
                    // document.getElementById("material").value = PrescriptionOrderDetails.materialInput;
                    document.getElementById("materialCost").innerText = materialInput + "¥";
                    materialContainer.style.display = 'block';
                }

                document.getElementById("doctor_name").value = PrescriptionOrderDetails.doctor_name;

                for (var i = 0; i < orderDetails.length; i++) {

                    let newItem = {
                        id: orderDetails[i].m_id,
                        name: orderDetails[i].m_title,
                        types: orderDetails[i].m_types,
                        image: orderDetails[i].m_image,
                        quantity: parseInt(orderDetails[i].quantity),
                        days: parseInt(orderDetails[i].m_days),
                        price: orderDetails[i].tottal_price,
                        menu: orderDetails[i].m_times,
                        notes: orderDetails[i].m_notes,
                        daily_dose: parseInt(orderDetails[i].m_daily_dose),
                        piese_per_dose: parseInt(orderDetails[i].m_piese_per_dose),
                        instruction: parseInt(orderDetails[i].m_instruction)
                    };
                    items.push(newItem);

                    showCart();
                }
                // read path on page open only when there is no data saved on cart
                if (orderDetails.length == 0) {
                    readPath(items)
                }



            }

            function readPath(items) {

                const paths = "<?php echo e($PrescriptionOrderId->p_image); ?>"
                const pathArray = paths.split(';');
                console.log(pathArray)

                console.log(items.length)
                if (items.length) {
                    showCart();
                } else {
                    pathArray.forEach(path => {
                        console.log(path)
                        //extract medicine name if cart is empty
                        medicineName(path)


                    });
                }
                console.log(items);

            }


            var c_id = 1;
            var c_title = "";
            var c_types = "";
            var c_image = "";
            var c_price = 1;
            var c_days = 1;
            var c_quantuty = 1;
            var c_daily_dose = 1;
            var c_piese_per_dose = 1;
            var c_instruction = 0;
            var c_menu = "";
            var c_notes = "";
            var initial_price = 1;


            function addMedicinesToCart(id, title, types, image, price, daily_dose, piese_per_dose, instruction, stock_status) {

                var options = [
                    "<?php echo e(__('breakfast')); ?>",
                    "<?php echo e(__('lunch')); ?>",
                    "<?php echo e(__('dinner')); ?>",
                    "<?php echo e(__('breakfastDinner')); ?>",
                    "<?php echo e(__('morningLunch')); ?>",
                    "<?php echo e(__('lunchDinner')); ?>",
                    "<?php echo e(__('breakfastLunchDinner')); ?>",
                    "<?php echo e(__('everyMeal')); ?>",
                    "<?php echo e(__('betweenMeals')); ?>",
                    "<?php echo e(__('fasting')); ?>",
                    "<?php echo e(__('goingToBed')); ?>",
                    "<?php echo e(__('every4hours')); ?>",
                    "<?php echo e(__('every8hours')); ?>",
                ];

                // Function to get a random string
                function getRandomString() {
                    var randomIndex = Math.floor(Math.random() * options.length);
                    return options[randomIndex];
                }

                // Usage example:
                var randomValue = getRandomString();
                console.log(randomValue);


                c_menu = "";
                c_notes = "";

                let newItem = {
                    id: id,
                    name: title,
                    types: types,
                    image: image,
                    quantity: 1,
                    days: 1,
                    daily_dose: daily_dose,
                    piese_per_dose: piese_per_dose,
                    instruction: 2,
                    menu: randomValue,
                    notes: " ",
                    price: price
                };
                console.log(newItem);

                var itemExists = false;

                for (var i = 0; i < items.length; i++) {
                    if (items[i].id === id) {
                        itemExists = true;
                        break;
                    }
                }

                if (itemExists) {

                    var modal = new bootstrap.Modal(document.getElementById("existModal"));
                    // modal.show();

                    return;

                }
                items.push(newItem);
                showCart();
            }




            function addClick(id, title, types, image, price, days, daily_dose, piese_per_dose, instruction, stock_status) {

                warningMessage.style.display = "none";
                var itemExists = false;

                for (var i = 0; i < items.length; i++) {
                    if (items[i].id === id) {
                        itemExists = true;
                        break;
                    }
                }

                if (itemExists) {

                    var modal = new bootstrap.Modal(document.getElementById("existModal"));
                    modal.show();

                    return;

                }
                if (stock_status == 0) {

                    var modal = new bootstrap.Modal(document.getElementById("outOfStock"));
                    modal.show();

                    return;

                } else {

                    var modal = new bootstrap.Modal(document.getElementById("addModal"));
                    modal.show();
                }

                console.log(id);
                console.log(title);
                console.log(price);
                console.log(days);
                console.log(daily_dose);
                console.log(piese_per_dose);
                console.log(instruction);
                c_id = id;
                c_title = title;
                c_types = types;
                c_image = image;
                c_price = price;
                c_daily_dose = daily_dose;
                c_piese_per_dose = piese_per_dose;
                c_instruction = instruction;
                c_menu = "";
                c_notes = "";
                initial_price = price;

                document.getElementById("Medicine-title").innerText = title;
                document.getElementById("price-value").innerText = price + "¥";
                document.getElementById("days").value = days;
                document.getElementById("daily_dose").value = daily_dose;
                document.getElementById("piese_per_dose").value = piese_per_dose;

                cart_automation();

                const afterMealRadio = document.getElementById("defaultRadio1");
                const beforeMealRadio = document.getElementById("defaultRadio2");
                const anyMealRadio = document.getElementById("defaultRadio3");

                if (instruction === 0) {
                    afterMealRadio.checked = true;
                } else if (instruction === 1) {
                    beforeMealRadio.checked = true;
                } else if (instruction === 2) {
                    anyMealRadio.checked = true;
                }


            }



            selectElement.addEventListener("change", function() {
                var selectedOption = selectElement.options[selectElement.selectedIndex];
                c_menu = selectedOption.text;


            });


            document.getElementById('selectLimit').addEventListener('input', function() {
                // Remove non-numeric characters
                this.value = this.value.replace(/\D/g, '');

                // Ensure the value is within the allowed range
                if (this.value < 0) {
                    this.value = 0;
                } else if (this.value > 100) {
                    this.value = 100;
                }

                ins_limit = this.value;

                insTotal = (subtotal * ins_limit) / 100;

            });

            function limitChange() {

                var inputValue = document.getElementById("selectLimit").value;
                inputValue = inputValue.replace(/\D/g, '');
                if (inputValue < 0) {
                    inputValue = 0;
                } else if (inputValue > 100) {
                    inputValue = 100;
                }
                ins_limit = inputValue;
                var newTotal = (subMeditotal+technicalInput + managementInput + materialInput);
                subtotal = newTotal;
                insTotal = (subtotal * ins_limit) / 100;
                console.log(insTotal);
                total = subtotal + tax - insTotal;
                // total = technicalInput + managementInput + materialInput + subtotal + tax - insTotal;
                document.getElementById("idTotal").innerText = total.toFixed(1) + "¥";
                document.getElementById("idIns").innerText = insTotal + "¥";
                console.log("Selected limit: " + inputValue);
            }


               function forTechMagMatChange() {

                var inputValue = document.getElementById("selectLimit").value;
                inputValue = inputValue.replace(/\D/g, '');
                if (inputValue < 0) {
                    inputValue = 0;
                } else if (inputValue > 100) {
                    inputValue = 100;
                }
                ins_limit = inputValue;
                insTotal = (subtotal * ins_limit) / 100;
                console.log(insTotal);
                total = subtotal + tax - insTotal;
                // total = technicalInput + managementInput + materialInput + subtotal + tax - insTotal;
                document.getElementById("idTotal").innerText = total.toFixed(1) + "¥";
                document.getElementById("idIns").innerText = insTotal + "¥";
                console.log("Selected limit: " + inputValue);
            }

            //technical , management, material

            //technicalElement
            function technicalChange() {

                var inputValue = document.getElementById("technical").value;

                if(inputValue == ""){
                    technicalInput = 0.0
                    technicalContainer.style.display = 'none';
                }else{
                    technicalInput = parseFloat(inputValue);
                    technicalContainer.style.display = 'block';
                }

                document.getElementById("technicalFee").innerText = technicalInput + "¥";
                // var newTotal = (total+technicalInput + managementInput + materialInput);
                var newTotal = (subMeditotal+technicalInput + managementInput + materialInput);
                subtotal = newTotal;
                console.log("newTotal "+newTotal);
                // document.getElementById("idTotal").innerText = newTotal.toFixed(1) + "¥";
                document.getElementById("idSubtotal").innerText = newTotal.toFixed(1) + "¥";
                forTechMagMatChange();
                console.log("technicalInput : " + technicalInput);
                console.log("total : " + total);
            }

            //managementChange
            function managementChange() {

                var inputValue = document.getElementById("management").value;

                if(inputValue == ""){
                    managementInput = 0.0
                    managementContainer.style.display = 'none';
                }else{
                    managementInput = parseFloat(inputValue);
                    managementContainer.style.display = 'block';
                }

                document.getElementById("managementFee").innerText = managementInput + "¥";
                // var newTotal = (total+technicalInput + managementInput + materialInput);
                var newTotal = (subMeditotal+technicalInput + managementInput + materialInput);
                subtotal = newTotal;
                console.log("newTotal "+newTotal);
                // document.getElementById("idTotal").innerText = newTotal.toFixed(1) + "¥";
                document.getElementById("idSubtotal").innerText = newTotal.toFixed(1) + "¥";
                forTechMagMatChange();
                console.log("managementInput : " + managementInput);
                console.log("total : " + total);
            }

              //materialChange
            function materialChange() {

                var inputValue = document.getElementById("material").value;

                if(inputValue == ""){
                    materialInput = 0.0
                    materialContainer.style.display = 'none';
                }else{
                    materialInput = parseFloat(inputValue);
                    materialContainer.style.display = 'block';
                }

                document.getElementById("materialCost").innerText = materialInput + "¥";
                // var newTotal = (total + technicalInput + managementInput + materialInput);
                var newTotal = (subMeditotal + technicalInput + managementInput + materialInput);
                subtotal = newTotal;
                console.log("newTotal "+newTotal);
                // document.getElementById("idTotal").innerText = newTotal.toFixed(1) + "¥";
                document.getElementById("idSubtotal").innerText = newTotal.toFixed(1) + "¥";
                forTechMagMatChange();
                console.log("managementInput : " + materialInput);
                console.log("total : " + total);
            }


            selectinsurance.addEventListener("change", function() {
                var selectedOption = selectinsurance.options[selectinsurance.selectedIndex];

                insurance_index = selectinsurance.selectedIndex;
                console.log(insurance_index);
                if (insurance_index == 0) {
                    limitDiv.style.display = "none";
                    insCardElement.disabled = true;
                    ins_limit = 0.0;
                    insTotal = (subtotal * ins_limit) / 100;
                    console.log(insTotal);
                    // total = subtotal + tax - insTotal;
                    total =  technicalInput + managementInput + materialInput + subtotal + tax - insTotal;
                    document.getElementById("idTotal").innerText = total.toFixed(1) + "¥";
                    document.getElementById("idIns").innerText = insTotal + "¥";
                } else {
                    limitDiv.style.display = "block";
                    insCardElement.disabled = false;
                }
                ins_type = insurance_index;
            });

            var textareaElement = document.getElementById("addNote");

            textareaElement.addEventListener("input", function() {
                var inputText = textareaElement.value;

                if (inputText.length > 30) {
                    textareaElement.value = inputText.substring(0, 30);
                }
            });

            var textareaElement2 = document.getElementById("edit_addNotes");

            textareaElement2.addEventListener("input", function() {
                var inputText = textareaElement2.value;

                if (inputText.length > 30) {
                    textareaElement2.value = inputText.substring(0, 30);
                }
            });

            function quantityChanged() {
                var quantity = document.getElementById("quantity").value;
                var price = initial_price * quantity;
                document.getElementById("price-value").innerText = price + "¥";
                c_price = price;
                c_quantuty = quantity;
            }

            document.getElementById("quantity").disabled = true;

            function daysChanged() {
                cart_automation();
            }

            function daily_doseChanged() {
                cart_automation();
            }

            function piese_per_dosehanged() {
                cart_automation();
            }

            function cart_automation() {
                var days = document.getElementById("days").value;
                var timeInDay = document.getElementById("daily_dose").value;
                var piese_per_dose = document.getElementById("piese_per_dose").value;
                var quantity = days * timeInDay * piese_per_dose;
                console.log("quantity");
                console.log(quantity);
                document.getElementById("quantity").value = quantity;
                var price = initial_price * quantity;
                document.getElementById("price-value").innerText = price + "¥";
                c_price = price;
                c_quantuty = quantity;
            }


            function addtoCart() {


                c_days = document.getElementById("days").value;
                c_daily_dose = document.getElementById("daily_dose").value;
                c_piese_per_dose = document.getElementById("piese_per_dose").value;
                c_notes = document.getElementById("addNote").value;
                let instructionRadio1 = document.getElementById("defaultRadio1");
                let instructionRadio2 = document.getElementById("defaultRadio2");
                let instructionRadio3 = document.getElementById("defaultRadio3");

                if (instructionRadio1.checked) {
                    c_instruction = 0;
                } else if (instructionRadio2.checked) {
                    c_instruction = 1;
                } else if (instructionRadio3.checked) {
                    c_instruction = 2;
                }



                if (c_menu === "") {
                    warningMessage.style.display = "block";
                    return;
                } else {
                    warningMessage.style.display = "none";
                }


                let newItem = {
                    id: c_id,
                    name: c_title,
                    types: c_types,
                    image: c_image,
                    quantity: parseInt(c_quantuty),
                    days: parseInt(c_days),
                    daily_dose: parseInt(c_daily_dose),
                    piese_per_dose: parseInt(c_piese_per_dose),
                    instruction: parseInt(c_instruction),
                    menu: c_menu,
                    notes: c_notes,
                    price: c_price
                };

                items.push(newItem);

                c_id = 1;
                c_title = "";
                c_types = "";
                c_image = "";
                c_price = 1;
                c_days = 1;
                c_quantuty = 1;

                c_daily_dose = 1;
                c_piese_per_dose = 1;
                c_instruction = 0;

                c_menu = "";
                var edit_selectTimes = document.getElementById("selectTimes");
                edit_selectTimes.options[0].selected = true;

                c_notes = "";

                document.getElementById("quantity").value = c_quantuty;
                document.getElementById("days").value = c_days;
                console.log(items);
                showCart();

                var modal = document.getElementById("addModal");
                var bootstrapModal = bootstrap.Modal.getInstance(modal);
                bootstrapModal.hide();
            }

            function createTableRow(item, index) {

                var index;
                var mPiesePerDose;

                var instructionText;
                if (item.instruction == 0) {
                    instructionText = '<?php echo e(__('after')); ?>';
                } else if (item.instruction == 1) {
                    instructionText = '<?php echo e(__('before')); ?>';
                } else {
                    instructionText = '<?php echo e(__('any')); ?>';
                }

                var notesText = item.notes;
                var truncatedText = "";
                if (notesText) {
                    truncatedText = notesText;
                }

                var row = document.createElement("tr");

                var cell = document.createElement("td");
                cell.innerHTML = `
            <div style="display: flex; align-items: start;">

                                                        <div>
                                                        <div style="display: flex; align-items: center;" >
                                                            <div style="font-weight: bold;">${item.quantity}x</div>
                                                            <div style="width:5px;"></div>
                                                            <div style="color:palevioletred;">${item.name} (1<?php echo e(__('times')); ?>${item.piese_per_dose}${item.types})</div>
                                                        </div>


                                                            <div style="color: gray;">1<?php echo e(__('day')); ?>${item.daily_dose}<?php echo e(__('times')); ?> ${item.menu}${instructionText} (${item.days}<?php echo e(__('cartDays')); ?>)

                                                                </div>

                                                                <div >
                                                            ${truncatedText}
                                                            </div>

                                                                <div style="margin-top: 10px; display:flex; ">
                                                            <div>
                                                                <button onclick="createEditHandler(${index})"
                                                                     class="btn btn-primary"
                                                                    style="padding: 0 0px 2px 5px; width: 30px; height: 30px;">
                                                                    <i class="fa fa-edit"></i></button>
                                                            </div>
                                                            <div style="width:5px;"></div>
                                                            <div>
                                                                    <button onclick="deleteHandler(${index})"
                                                                     class="btn btn-danger"
                                                                    style="padding: 0 0px 2px 2px; width: 30px; height: 30px;">
                                                                    <i class="fa fa-trash"></i></button>
                                                            </div>
                                                        </div>

                                                        </div>
                                                        <div style="font-weight: bold; font-size: 18px;margin-left: auto; align-items: center;">
                                                            ¥${item.price}
                                                            </div>

                                                    </div>
        `;

                row.appendChild(cell);
                return row;
            }



            function showCart() {

                subtotal = 0.0;
                subMeditotal = 0.0;

                var tableBody = document.querySelector("#cart-table tbody");

                tableBody.innerHTML = ""; // clear existing rows

                for (var i = 0; i < items.length; i++) {
                    var item = items[i];
                    var row = createTableRow(item, i);
                    tableBody.appendChild(row);

                    console.log("sub ", subtotal);
                    console.log("subMeditotal ", subMeditotal);
                    console.log("sub ", item.price);

                    subtotal = subtotal + item.price;
                    subMeditotal = subtotal;
                    console.log("sub late- ", subtotal);
                    console.log("subMeditotal late- ", subMeditotal);
                }

                var newTotal = (subMeditotal+technicalInput + managementInput + materialInput);
                subtotal = newTotal;

                document.getElementById("idSubtotal").innerText = subtotal + "¥";

                insTotal = (subtotal * ins_limit) / 100;
                tax = 0;
                // total =  technicalInput + managementInput + materialInput + subtotal + tax - insTotal;
                total = subtotal + tax - insTotal;
                document.getElementById("idIns").innerText = insTotal + "¥";
                // document.getElementById("idTax").innerText = tax + "¥";
                document.getElementById("idTotal").innerText = total.toFixed(1) + "¥";
            }

            checkbox.addEventListener('change', function() {
                if (this.checked) {
                    console.log("Checkbox is checked.");

                } else {
                    // insTotal = 0.0;
                    console.log("Checkbox is unchecked.");
                    //insCode = "";
                    //document.getElementById("ins_code").value = insCode;
                }
                console.log(insTotal);
                // total = subtotal + tax - insTotal;
                // document.getElementById("ins_code").innerText = insCode;
                // document.getElementById("idTotal").innerText = total.toFixed(1) + "¥";
                // document.getElementById("idIns").innerText = insTotal + "¥";
            });

            function createEditHandler(index) {
                // return function() {

                var modal = new bootstrap.Modal(document.getElementById("editModal"));
                modal.show();
                editCart(items[index]);
                console.log("Editing item at index", index);
                console.log("Item details:", items[index]);
                // };
            }

            function editCart(item_s) {

                console.log(item_s.id);
                console.log(item_s.name);
                console.log(item_s.price);
                console.log(item_s.instruction);
                console.log(item_s.menu);
                console.log(item_s.notes);
                console.log("------");
                c_id = item_s.id;
                c_title = item_s.name;
                c_types = item_s.types;
                c_image = item_s.image;
                c_price = item_s.price;
                c_quantuty = item_s.quantity
                c_days = item_s.days;
                c_daily_dose = item_s.daily_dose;
                c_piese_per_dose = item_s.piese_per_dose;
                c_instruction = item_s.instruction;
                c_menu = item_s.menu
                c_notes = item_s.notes
                initial_price = item_s.price / item_s.quantity;

                document.getElementById("medi_title").innerText = c_title;
                document.getElementById("edit-price-value").innerText = c_price + "¥";
                document.getElementById("edit-quantity").value = c_quantuty;
                document.getElementById("edit-days").value = c_days;
                document.getElementById("edit_daily_dose").value = c_daily_dose;
                document.getElementById("edit_piese_per_dose").value = c_piese_per_dose;
                document.getElementById("edit_addNotes").value = c_notes;

                var edit_selectTimes = document.getElementById("edit_selectTimes");
                for (var i = 0; i < edit_selectTimes.options.length; i++) {
                    if (edit_selectTimes.options[i].text === c_menu) {
                        edit_selectTimes.options[i].selected = true;
                        break;
                    }
                }

                const afterMealRadio = document.getElementById("edit_defaultRadio1");
                const beforeMealRadio = document.getElementById("edit_defaultRadio2");
                const anyMealRadio = document.getElementById("edit_defaultRadio3");

                console.log(c_instruction);

                if (c_instruction === "0") {
                    afterMealRadio.checked = true;
                } else if (c_instruction === "1") {
                    beforeMealRadio.checked = true;
                } else if (c_instruction === "2") {
                    anyMealRadio.checked = true;
                }

                if (c_instruction === 0) {

                    console.log("0 print");
                    afterMealRadio.checked = true;
                } else if (c_instruction === 1) {
                    console.log("1 print");
                    beforeMealRadio.checked = true;
                } else if (c_instruction === 2) {
                    console.log("2 print");
                    anyMealRadio.checked = true;
                }

            }


            function updateCart() {
                c_days = document.getElementById("edit-days").value;
                c_daily_dose = document.getElementById("edit_daily_dose").value;
                c_piese_per_dose = document.getElementById("edit_piese_per_dose").value;
                var edit_selectTimes = document.getElementById("edit_selectTimes");
                c_menu = edit_selectTimes.options[edit_selectTimes.value].text;

                if (c_menu === "") {

                    return;
                }

                c_notes = document.getElementById("edit_addNotes").value;
                let instructionRadio1 = document.getElementById("edit_defaultRadio1");
                let instructionRadio2 = document.getElementById("edit_defaultRadio2");
                let instructionRadio3 = document.getElementById("edit_defaultRadio3");

                if (instructionRadio1.checked) {
                    c_instruction = 0;
                } else if (instructionRadio2.checked) {
                    c_instruction = 1;
                } else if (instructionRadio3.checked) {
                    c_instruction = 2;
                }


                let newItem = {
                    id: c_id,
                    name: c_title,
                    types: c_types,
                    image: c_image,
                    quantity: parseInt(c_quantuty),
                    days: parseInt(c_days),
                    daily_dose: parseInt(c_daily_dose),
                    piese_per_dose: parseInt(c_piese_per_dose),
                    instruction: parseInt(c_instruction),
                    menu: c_menu,
                    notes: c_notes,
                    price: c_price
                };

                let index = items.findIndex(item => item.id === c_id);
                if (index !== -1) {
                    items.splice(index, 1, newItem);
                }

                c_id = 1;
                c_title = "";
                c_types = "";
                c_image = "";
                c_price = 1;
                c_days = 1;
                c_quantuty = 1;

                c_daily_dose = 1;
                c_piese_per_dose = 1;
                c_instruction = 0;
                c_notes = "";

                c_menu = "";
                var edit_selectTimes = document.getElementById("edit_selectTimes");
                edit_selectTimes.options[0].selected = true;

                showCart();

                var modal = document.getElementById("editModal");
                var bootstrapModal = bootstrap.Modal.getInstance(modal);
                bootstrapModal.hide();
            }

            function editquantityChanged() {



                var quantity = document.getElementById("edit-quantity").value;

                var price = initial_price * quantity;
                document.getElementById("edit-price-value").innerText = price + "¥";
                c_price = price;
                c_quantuty = quantity;

            }

            document.getElementById("edit-quantity").disabled = true;

            function edit_daysChanged() {
                edit_cart_automation();
            }

            function edit_daily_doseChanged() {
                edit_cart_automation();
            }

            function edit_piese_per_dosehanged() {
                edit_cart_automation();
            }

            function edit_cart_automation() {
                var days = document.getElementById("edit-days").value;
                var timeInDay = document.getElementById("edit_daily_dose").value;
                var piese_per_dose = document.getElementById("edit_piese_per_dose").value;
                var quantity = days * timeInDay * piese_per_dose;
                console.log("quantity");
                console.log(quantity);
                document.getElementById("edit-quantity").value = quantity;
                var price = initial_price * quantity;
                document.getElementById("edit-price-value").innerText = price + "¥";
                c_price = price;
                c_quantuty = quantity;
            }

            var delete_items_id = [];

            function deleteHandler(index) {


                try {
                    delete_items_id.push(items[index].id)
                    items.splice(index, 1);
                } catch (err) {
                    console.log("An error occurred while deleting item:", err);
                }
                showCart();

            }



            function processForm() {
                const fields = [{
                        id: "hospital",
                        label: "<?php echo e(__('hospitalName')); ?>"
                    },
                    {
                        id: "department",
                        label: "<?php echo e(__('departmentName')); ?>"
                    },
                    {
                        id: "doctor_name",
                        label: "<?php echo e(__('doctorName')); ?>"
                    }
                ];

                if (document.getElementById("verify_tik").checked) {

                    const insCardElement = document.getElementById("ins_code").value;
                    insCode = insCardElement ? insCardElement : "";
                } else {
                    insCode = "";
                }

                const emptyFields = fields.filter(field => !document.getElementById(field.id).value.trim());
                if (emptyFields.length > 0) {
                    const emptyFieldNames = emptyFields.map(field => field.label);
                    console.log(`Fields are empty: ${emptyFieldNames.join(", ")}`);
                    document.getElementById("fieldsEmptyModalLabel").innerText = `${emptyFieldNames.join(", ")}`;
                    var modal = new bootstrap.Modal(document.getElementById("fieldsEmptyModal"));
                    modal.show();
                    goForUpload = false;
                } else {

                    hospital = document.getElementById("hospital").value.trim() || "";
                    department = document.getElementById("department").value.trim() || "";
                    doctor_name = document.getElementById("doctor_name").value.trim() || "";

                    goForUpload = true;
                    console.log(hospital);
                    console.log(department);
                    console.log(doctor_name);

                }
            }
            //function for the cancel button in the middle column
            function cancel() {
                console.log("Going to pending presciption page");
                // delete_items_id = [];
                window.location.href = "<?php echo e(url('admin/Goto-pending_prescrip')); ?>";
            }

            function confirm() {



                if (checkbox.checked == false) {

                    var modal = new bootstrap.Modal(document.getElementById("verifyModal"));
                    modal.show();
                    return;
                } else {

                    if (document.getElementById("selectInsurance").value != 0) {
                        if (document.getElementById("ins_code").value == "" || document.getElementById("ins_code").value ==
                            null ||
                            document.getElementById("selectLimit").value == "" || document.getElementById("selectLimit")
                            .value ==
                            null) {

                            var modal = new bootstrap.Modal(document.getElementById("verifyModal"));
                            modal.show();
                            return;
                        }
                    }

                }


                processForm();

                if (document.getElementById("ins_code").disabled == true) {
                    ins_limit = 0;
                    insCode = "";
                }

                if (goForUpload == false) {
                    return;
                }

                console.log(items);
                // if(delete_items_id){

                // }

                if (items.length == 0) {
                    var modal = new bootstrap.Modal(document.getElementById("invalidCartModal"));
                    modal.show();
                    return;
                }


                let prescriptionOrderId = "<?php echo e($PrescriptionOrderId->id); ?>";


                //insert in the database
                if (orderDetails.length == 0) {


                    console.log(<?php echo e($PrescriptionOrderId->id); ?>);
                    console.log(subtotal);
                    console.log(insTotal);
                    console.log(tax);
                    console.log(total);
                    console.log(insCode);
                    console.log(hospital);
                    console.log(department);
                    console.log(doctor_name);
                    console.log(ins_type);
                    console.log(ins_limit);

                    //technicalInput + managementInput + materialInput +

                    $.ajax({
                        url: "<?php echo e(url('admin/insert-product-cart')); ?>",
                        method: 'POST',
                        data: {
                            items: items,
                            id: <?php echo e($PrescriptionOrderId->id); ?>,
                            subtotal: subtotal,
                            insTotal: insTotal,
                            tax: tax,

                            technicalInput: technicalInput,
                            managementInput: managementInput,
                            materialInput: materialInput,

                            total: total,

                            insCode: insCode,
                            ins_type: ins_type,
                            ins_limit: ins_limit,
                            hospital: hospital,
                            department: department,
                            doctor_name: doctor_name
                        },
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        success: function(response) {
                            console.log(response.message);
                            window.location.href = "<?php echo e(url('admin/Goto-pending_prescrip')); ?>";
                        },
                        error: function(xhr, status, error) {
                            console.log(error);
                        }
                    });
                }
                //update in the database
                else {

                    console.log(<?php echo e($PrescriptionOrderId->id); ?>);
                    console.log(subtotal);
                    console.log(insTotal);
                    console.log(tax);
                    console.log(total);
                    console.log(insCode);
                    console.log(hospital);
                    console.log(department);
                    console.log(doctor_name);
                    console.log(ins_type);
                    console.log(ins_limit);


                    $.ajax({
                        url: "<?php echo e(url('admin/update-product-cart')); ?>",
                        method: 'POST',
                        data: {
                            items: items,
                            id: <?php echo e($PrescriptionOrderId->id); ?>,
                            subtotal: subtotal,
                            insTotal: insTotal,
                            tax: tax,

                            technicalInput: technicalInput,
                            managementInput: managementInput,
                            materialInput: materialInput,

                            total: total,

                            insCode: insCode,
                            ins_type: ins_type,
                            ins_limit: ins_limit,
                            hospital: hospital,
                            department: department,
                            doctor_name: doctor_name,
                            delete_items: delete_items_id
                        },
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        success: function(response) {
                            console.log(response.message);
                            delete_items_id = [];
                            window.location.href = "<?php echo e(url('admin/Goto-pending_prescrip')); ?>";
                        },
                        error: function(xhr, status, error) {
                            console.log(error);
                        }
                    });
                }



            }
        </script>

        <style>
            .image-slider-container {
                overflow: hidden;
            }

            .image-slider-container .swiper-container {
                /* position: absolute; */
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;

            }

            .image-slider-container .swiper-slide img {

                padding: 0px 20px 5px 5px;
                width: 100%;
                height: 100%;


            }
        </style>
    <?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.master', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /home/xorgeekc/public_html/medishop/resources/views/admin/prescription/add_product_cart.blade.php ENDPATH**/ ?>