<!DOCTYPE html>
<html>

<head>
<!-- TABLES CSS CODE -->
<?php include"comman/code_css.php"; ?>
<!-- Toastr CSS -->
<link rel="stylesheet" href="<?php echo $theme_link; ?>toastr/toastr.min.css">
<!-- </copy> -->  
<style type="text/css">
   table.table-bordered > thead > tr > th {
   /* border:1px solid black;*/
   text-align: center;
   }
   .table > tbody > tr > td, 
   .table > tbody > tr > th, 
   .table > tfoot > tr > td, 
   .table > tfoot > tr > th, 
   .table > thead > tr > td, 
   .table > thead > tr > th 
   {
   padding-left: 2px;
   padding-right: 2px;  

   }

/* Currency Badge - White Bold Text Only */
.enterprise-currency-badge{display:inline-flex!important;align-items:center;gap:6px;padding:6px 12px;background:transparent!important;color:#ffffff!important;border:none!important;font-size:12px;font-weight:700!important;text-transform:uppercase;letter-spacing:0.5px}
.enterprise-currency-badge i{color:#ffffff!important;font-size:13px}

/* Override any existing green currency styling - White Bold Text Only */
#supplier_currency_info .label-success,
#supplier_currency_info .label,
#supplier_currency_info_totals .label-success,
#supplier_currency_info_totals .label{background:transparent!important;color:#ffffff!important;border:none!important;font-weight:700!important}

/* Force white bold text styling ONLY for currency-related elements */
#supplier_currency_info *,
#supplier_currency_info_totals *,
[class*="currency"][class*="badge"],
[id*="currency"][id*="badge"],
.enterprise-currency-badge{background:transparent!important;color:#ffffff!important;border:none!important;font-weight:700!important}

/* Enterprise Alert System */
.enterprise-alert {
    position: fixed;
    top: 20px;
    right: 20px;
    z-index: 9999;
    padding: 12px 20px;
    border-radius: 6px;
    font-size: 13px;
    font-weight: 600;
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    max-width: 350px;
    animation: slideInRight 0.3s ease;
}

.enterprise-alert.warning {
    background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
    color: #92400e;
    border: 1px solid #f59e0b;
}

.enterprise-alert.success {
    background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%);
    color: #065f46;
    border: 1px solid #10b981;
}

.enterprise-alert.error {
    background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%);
    color: #991b1b;
    border: 1px solid #ef4444;
}

@keyframes slideInRight {
    from {
        transform: translateX(100%);
        opacity: 0;
    }
    to {
        transform: translateX(0);
        opacity: 1;
    }
}

/* Read-only currency fields styling */
#from_currency:disabled, #to_currency:disabled {
    background-color: #f8f9fa !important;
    color: #495057 !important;
    border-color: #ced4da !important;
    cursor: not-allowed !important;
    opacity: 0.8 !important;
}
</style>
</head>



<body class="hold-transition skin-blue sidebar-mini">
  
<div class="wrapper">
 
 
 <?php include"sidebar.php"; ?>
 
 <?php
    if(!isset($purchase_id)){
      $supplier_id  = $pur_date = $purchase_status = $warehouse_id =
      $reference_no  =
      $other_charges_input          = $other_charges_tax_id =
      $discount_input = $discount_type  = $purchase_note=$store_id='';
      $pur_date=show_date(date("d-m-Y"));
    }
    else{
      $q2 = $this->db->query("select * from db_purchase where id=$purchase_id");
      $supplier_id=$q2->row()->supplier_id;
      $warehouse_id=$q2->row()->warehouse_id;
      $pur_date=show_date($q2->row()->purchase_date);
      $purchase_status=$q2->row()->purchase_status;
      $reference_no=$q2->row()->reference_no;
      $discount_input=store_number_format($q2->row()->discount_to_all_input,2);
      $discount_type=$q2->row()->discount_to_all_type;
      $other_charges_input=store_number_format($q2->row()->other_charges_input,0);
      $other_charges_tax_id=$q2->row()->other_charges_tax_id;
      $purchase_note=$q2->row()->purchase_note;
      $store_id=$q2->row()->store_id;

      $items_count = $this->db->query("select count(*) as items_count from db_purchaseitems where purchase_id=$purchase_id")->row()->items_count;
    }
    
    ?>

 

  <!-- Content Wrapper. Contains page content -->
  <div class="content-wrapper">
    <!-- **********************MODALS***************** -->
    <?php include"modals/modal_supplier.php"; ?>
    <?php include"modals/modal_purchase_item.php"; ?>
    <?php include"modals/modal_item.php"; ?>
    <?php include"modals/modal_item_or_service.php"; ?>
    <?php include"modals/modal_batch_details.php"; ?>
   <?php /*include"modals/modal_service.php";*/ ?>
    <!-- **********************MODALS END***************** -->
    <!-- Content Header (Page header) -->
    <section class="content-header">
         <h1>
            <?=$page_title;?>
            <small>Add/Update Purchase</small>
         </h1>
         <ol class="breadcrumb">
            <li><a href="<?php echo $base_url; ?>dashboard"><i class="fa fa-dashboard"></i> Home</a></li>
            <li><a href="<?php echo $base_url; ?>purchase"><?= $this->lang->line('purchase_list'); ?></a></li>
            <li><a href="<?php echo $base_url; ?>purchase/add"><?= $this->lang->line('new_purchase'); ?></a></li>
            <li class="active"><?=$page_title;?></li>
         </ol>
      </section>

    <!-- Main content -->
     <section class="content">
               <div class="row">
                <!-- ********** ALERT MESSAGE START******* -->
               <?php include"comman/code_flashdata.php"; ?>
               <!-- ********** ALERT MESSAGE END******* -->
                  <!-- right column -->
                  <div class="col-md-12">
                     <!-- Horizontal Form -->
                     <div class="box box-primary " >
                        <!-- style="background: #68deac;" -->
                        
                        <!-- form start -->
                         <!-- OK START -->
                        <?= form_open('#', array('class' => 'form-horizontal', 'id' => 'purchase-form', 'enctype'=>'multipart/form-data', 'method'=>'POST'));?>
                           <input type="hidden" id="base_url" value="<?php echo $base_url;; ?>">
                           <input type="hidden" id="base_currency_symbol" value="<?php echo get_base_currency()->symbol ?? '$'; ?>">
                           <input type="hidden" value='1' id="hidden_rowcount" name="hidden_rowcount">
                           <input type="hidden" value='0' id="hidden_update_rowid" name="hidden_update_rowid">
                           <input type="hidden" value='Received' id="purchase_status" name="purchase_status">
                           <input type="hidden" id="base_currency_id" value="<?php echo get_base_currency_id(); ?>">

                          
                           <div class="box-body">
                              <!-- Store Code -->
                              <?php 
                              /*if(store_module() && is_admin()) {$this->load->view('store/store_code',array('show_store_select_box'=>true,'store_id'=>$store_id,'div_length'=>'col-sm-3')); }else{*/
                                echo "<input type='hidden' name='store_id' id='store_id' value='".get_current_store_id()."'>";
                              /*}*/
                              ?>
                              <!-- Store Code end -->
                              <!-- Warehouse Code -->
                              <?php 
                               if(warehouse_module() && warehouse_count()>1) {$this->load->view('warehouse/warehouse_code',array('show_warehouse_select_box'=>true,'warehouse_id'=>$warehouse_id,'div_length'=>'col-sm-3','show_select_option'=>false)); }else{
                                echo "<input type='hidden' name='warehouse_id' id='warehouse_id' value='".get_store_warehouse_id()."'>";
                               }
                              ?>
                              <!-- Warehouse Code end -->

                              <div class="form-group">
                                 <label for="supplier_id" class="col-sm-2 control-label"><?= $this->lang->line('supplier_name'); ?><label class="text-danger">*</label></label>
                                 <div class="col-sm-3">
                                    <div class="input-group">
                                       <select class="form-control select2" id="supplier_id" name="supplier_id"  style="width: 100%;" >
                                       </select>
                                       <span class="input-group-addon pointer" data-toggle="modal" data-target="#supplier-modal" title="New Supplier?"><i class="fa fa-user-plus text-primary fa-lg"></i></span>
                                    </div>
                                    <span id="supplier_id_msg" style="display:none" class="text-danger"></span>
                                    <div id="supplier_currency_info" style="display: none; margin-top: 8px;">
                                        <span class="enterprise-currency-badge">
                                            <i class="fa fa-money"></i> <span id="supplier_currency_name"></span>
                                        </span>
                                    </div>
                                 </div>
                                 <label for="pur_date" class="col-sm-2 control-label"><?= $this->lang->line('purchase_date'); ?> <label class="text-danger">*</label></label>
                                 <div class="col-sm-3">
                                    <div class="input-group date">
                                       <div class="input-group-addon">
                                          <i class="fa fa-calendar"></i>
                                       </div>
                                       <input type="text" class="form-control pull-right datepicker"  id="pur_date" name="pur_date" readonly onkeyup="shift_cursor(event,'purchase_status')" value="<?= $pur_date;?>">
                                    </div>
                                    <span id="pur_date_msg" style="display:none" class="text-danger"></span>
                                 </div>
                              </div>
                              <div class="form-group">
                                  <label for="reference_no" class="col-sm-2 control-label"><?= $this->lang->line('reference_no'); ?> </label>
                                 <div class="col-sm-3">
                                    <input type="text" value="<?php echo  $reference_no; ?>" class="form-control " id="reference_no" name="reference_no" placeholder="" >
                  <span id="reference_no_msg" style="display:none" class="text-danger"></span>
                                 </div>
                                 
                              </div>
                             
                           </div>
                           <!-- /.box-body -->
                           
                           <div class="row">
                              <div class="col-md-12">
                                <div class="col-md-12">
                                  <div class="box">
                                    <div class="box-info">
                                      <div class="box-header">
                                        <div class="col-md-8 col-md-offset-2 d-flex justify-content" >
                                         <div class="input-group">
                                                <span class="input-group-addon" title="Select Items"><i class="fa fa-barcode"></i></span>
                                                 <input type="text" class="form-control " placeholder="Item name/Barcode/Itemcode" autofocus id="item_search">
                                                 <span class="input-group-addon pointer text-green show_item_service" title="Click to Add New Item or Service"><i class="fa fa-plus"></i></span>
                                              </div>
                                        </div>
                                      </div>
                                      <div class="box-body">
                                        <div class="table-responsive" style="width: 100%">
                                        <table class="table table-hover table-bordered" style="width:100%" id="purchase_table">
                                             <thead class="custom_thead">
                                                <tr class="bg-primary" >
                                                   <th rowspan='2' style="width:15%"><?= $this->lang->line('item_name'); ?></th>
                                                   <th rowspan='2' style="width:15%;min-width: 180px;"><?= $this->lang->line('quantity'); ?></th>
                                                   <th rowspan='2' style="width:10%"><?= $this->lang->line('purchase_price'); ?>(<span id="purchase_price_currency_symbol"><?= !empty($this->session->userdata('currency')) ? $this->session->userdata('currency') : '$' ?></span>)</th>
                                                  <!--  <th rowspan='2' style="width:7.5%"><?= $this->lang->line('tax'); ?> %</th> -->
                                                   <th rowspan='2' style="width:10%"><?= $this->lang->line('discount'); ?>(<span id="discount_currency_symbol"><?= !empty($this->session->userdata('currency')) ? $this->session->userdata('currency') : '$' ?></span>)</th>
                                                   <th rowspan='2' style="width:7.5%"><?= $this->lang->line('tax_amount'); ?></th>
                                                   <th rowspan='2' style="width:7.5%"><?= $this->lang->line('unit_cost'); ?></th>
                                                   <th rowspan='2' style="width:7.5%"><?= $this->lang->line('total_amount'); ?></th>
                                                   <!-- <th rowspan='2' style="width:7.5%"><?= $this->lang->line('profit_margin'); ?>(%)</th>
                                                   <th rowspan='2' style="width:7.5%"><?= $this->lang->line('unit_sales_price'); ?>(<?=$CURRENCY;?>)</th> -->
                                                   <th rowspan='2' style="width:7.5%"><?= $this->lang->line('action'); ?></th>
                                                </tr>
                                             </thead>
                                             <tbody>
                                               
                                             </tbody>
                                          </table>
                                      </div>
                                      </div>
                                    </div>
                                  </div>
                                  

                                </div>
                              </div>
                              
                              
                              <div class="col-md-6">
                                <div class="row">
                                    <div class="col-md-12">
                                       <div class="form-group">
                                          <label for="" class="col-sm-4 control-label"><?= $this->lang->line('total_quantities'); ?></label>    
                                          <div class="col-sm-4">
                                             <label class="control-label total_quantity text-success" style="font-size: 15pt;">0</label>
                                          </div>
                                       </div>
                                    </div>
                                 </div>
                                 <div class="row">
                                    <div class="col-md-12">
                                       <div class="form-group">
                                          <label for="other_charges_input" class="col-sm-4 control-label"><?= $this->lang->line('other_charges'); ?></label>    
                                          <div class="col-sm-4">
                                             <input type="text" class="form-control text-right only_currency" id="other_charges_input" name="other_charges_input" onkeyup="final_total();" value="<?php echo  $other_charges_input; ?>">
                                          </div>
                                          <div class="col-sm-4">
                                             <select class="form-control " id="other_charges_tax_id" name="other_charges_tax_id" onchange="final_total();" style="width: 100%;">
                                                <?= get_tax_select_list($other_charges_tax_id,get_current_store_id());?>
                                             </select>
                                          </div>
                                       </div>
                                    </div>
                                 </div>
                                 <div class="row">
                                    <div class="col-md-12">
                                       <div class="form-group">
                                          <label for="discount_to_all_input" class="col-sm-4 control-label"><?= $this->lang->line('discount_on_all'); ?></label>    
                                          <div class="col-sm-4">
                                             <input type="text" class="form-control  text-right only_currency" id="discount_to_all_input" name="discount_to_all_input" onkeyup="enable_or_disable_item_discount();" value="<?php echo  $discount_input; ?>">
                                          </div>
                                          <div class="col-sm-4">
                                             <select class="form-control" onchange="final_total();" id='discount_to_all_type' name="discount_to_all_type">
                                                <option value='in_percentage'>Per%</option>
                                                <option value='in_fixed'>Fixed</option>
                                             </select>
                                          </div>
                                          <!-- Dynamicaly select Supplier name -->
                                          <script type="text/javascript">
                                             <?php if($discount_type!=''){ ?>
                                                 document.getElementById('discount_to_all_type').value='<?php echo  $discount_type; ?>';
                                             <?php }?>
                                          </script>
                                          <!-- Dynamicaly select Supplier name end-->
                                       </div>
                                    </div>
                                 </div>
                                <div class="row">
                                    <div class="col-md-12">
                                       <div class="form-group">
                                          <label for="purchase_note" class="col-sm-4 control-label"><?= $this->lang->line('note'); ?></label>    
                                          <div class="col-sm-8">
                                             <textarea class="form-control text-left" id='purchase_note' name="purchase_note"><?=$purchase_note;?></textarea>
                                            <span id="purchase_note_msg" style="display:none" class="text-danger"></span>
                                          </div>
                                       </div>
                                    </div>
                                 </div>

                                 
                              </div>
                              

                              <div class="col-md-6">
                                 <div class="row">
  <div class="col-md-12">
    <div class="form-group">

      <!-- Supplier currency display removed - only showing near supplier selection -->

      <table class="col-md-9">
        <tr>
          <th class="text-right" style="font-size:17px;"><?= $this->lang->line('subtotal'); ?></th>
          <th class="text-right" style="padding-left:10%;font-size:17px;">
            <h4>
              <span id="subtotal_currency_symbol">
                $
              </span>
              <b id="subtotal_amt" name="subtotal_amt">0.00</b>
            </h4>
          </th>
        </tr>
        <tr>
          <th class="text-right" style="font-size:17px;"><?= $this->lang->line('other_charges'); ?></th>
          <th class="text-right" style="padding-left:10%;font-size:17px;">
            <h4>
              <span id="other_charges_currency_symbol">
                $
              </span>
              <b id="other_charges_amt" name="other_charges_amt">0.00</b>
            </h4>
          </th>
        </tr>
        <tr>
          <th class="text-right" style="font-size:17px;"><?= $this->lang->line('discount_on_all'); ?></th>
          <th class="text-right" style="padding-left:10%;font-size:17px;">
            <h4>
              <span id="discount_to_all_currency_symbol">
                $
              </span>
              <b id="discount_to_all_amt" name="discount_to_all_amt">0.00</b>
            </h4>
          </th>
        </tr>
        <tr style="<?= (!is_enabled_round_off()) ? 'display: none;' : '';?>">
          <th class="text-right" style="font-size:17px;">
            <?= $this->lang->line('round_off'); ?>
            <i class="hover-q" data-container="body" data-toggle="popover" data-placement="top"
               data-content="Go to Site Settings-> Site -> Disable the Round Off(Checkbox)."
               data-html="true" data-trigger="hover" title="Do you wants to Disable Round Off ?">
               <i class="fa fa-info-circle text-maroon text-black hover-q"></i>
            </i>
          </th>
          <th class="text-right" style="padding-left:10%;font-size:17px;">
            <h4>
              <span id="round_off_currency_symbol">
                $
              </span>
              <b id="round_off_amt" name="tot_round_off_amt">0.00</b>
            </h4>
          </th>
        </tr>
        <tr>
          <th class="text-right" style="font-size:17px;"><?= $this->lang->line('grand_total'); ?></th>
          <th class="text-right" style="padding-left:10%;font-size:17px;">
            <h4>
              <span id="total_amt_currency_symbol">
                $
              </span>
              <b id="total_amt" name="total_amt">0.00</b>
            </h4>
          </th>
        </tr>
      </table>

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

                              <div class="col-xs-12 ">
                                 <div class="col-sm-12">
                                       <div class="box-body ">
                                        <div class="col-md-12">
                                          <table class="table table-hover table-bordered" style="width:100%" id="payments_table"><h4 class="box-title text-info"><?= $this->lang->line('previous_payments_information'); ?> : </h4>
                                             <thead>
                                                <tr class="bg-gray " >
                                                   <th>#</th>
                                                   <th><?= $this->lang->line('date'); ?></th>
                                                   <th><?= $this->lang->line('payment_type'); ?></th>
                                                   <th><?= $this->lang->line('payment_note'); ?></th>
                                                   <th><?= $this->lang->line('payment'); ?></th>
                                                   <th><?= $this->lang->line('action'); ?></th>
                                                </tr>
                                             </thead>
                                             <tbody>
                                                <?php 
                                                  if(isset($purchase_id)){
                                                    $q3 = $this->db->query("select * from db_purchasepayments where purchase_id=$purchase_id");
                                                    if($q3->num_rows()>0){
                                                      $i=1;
                                                      $total_paid = 0;
                                                      foreach ($q3->result() as $res3) {
                                                        echo "<tr class='text-center text-bold' id='payment_row_".$res3->id."'>";
                                                        echo "<td>".$i."</td>";
                                                        echo "<td>".show_date($res3->payment_date)."</td>";
                                                        echo "<td>".$res3->payment_type."</td>";
                                                        echo "<td>".$res3->payment_note."</td>";
                                                        echo "<td class='text-right' id='paid_amt_$i'>".
                                                         $CI->currency($res3->payment)."</td>";
                                                        echo '<td><i class="fa fa-trash text-red pointer" onclick="delete_payment('.$res3->id.')"> Delete</i></td>';
                                                        echo "</tr>";
                                                        $total_paid +=$res3->payment;
                                                        $i++;
                                                      }
                                                      echo "<tr class='text-right text-bold'><td colspan='4' >Total</td><td data-rowcount='$i' id='paid_amt_tot'>".
                                                      $CI->currency(number_format($total_paid,2,'.',''))."</td><td></td></tr>";
                                                    }
                                                    else{
                                                      echo "<tr><td colspan='6' class='text-center text-bold'>No Previous Payments Found!!</td></tr>";
                                                    }

                                                  }
                                                  else{
                                                    echo "<tr><td colspan='6' class='text-center text-bold'>Payments Pending!!</td></tr>";
                                                  }
                                                ?>
                                             </tbody>
                                          </table>
                                        </div>
                                       </div>
                                       <!-- /.box-body -->
                                    </div>
                                 <!-- /.box -->
                              </div>

                              <div class="col-xs-12 ">
                                 <div class="col-sm-12">
                                       <div class="box-body ">

                                          <div class="col-md-12 payments_div payments_div_">
                                            <h4 class="box-title text-info"><?= $this->lang->line('make_payment'); ?> : </h4>
                                          <div class="box box-solid bg-gray">
                                            <div class="box-body">
                                              <div class="row">
                                         
                                                <div class="col-md-4">
                                                  <div class="">
                                                  <label for="amount"><?= $this->lang->line('amount'); ?></label>
                                                    <input type="text" class="form-control text-right paid_amt only_currency" id="amount" name="amount" placeholder="" onkeyup="checkAccountBalance()">
                                                      <span id="amount_msg" style="display:none" class="text-danger"></span>
                                                </div>
                                               </div>
                                                <div class="col-md-4">
                                                  <div class="">
                                                    <label for="payment_type"><?= $this->lang->line('payment_type'); ?></label>
                                                    <select class="form-control select2" id='payment_type' name="payment_type">
                                                      <?php
                                                        $q1=$this->db->query("select * from db_paymenttypes where status=1 and store_id=".get_current_store_id());
                                                         if($q1->num_rows()>0){
                                                            echo "<option value=''>-Select-</option>";
                                                             foreach($q1->result() as $res1){
                                                             echo "<option value='".$res1->payment_type."'>".$res1->payment_type ."</option>";
                                                           }
                                                         }
                                                         else{
                                                            echo "<option>None</option>";
                                                         }
                                                        ?>
                                                    </select>
                                                    <span id="payment_type_msg" style="display:none" class="text-danger"></span>
                                                  </div>
                                                </div>
                                                <div class="col-md-4">
                                                    <label for="account_id"><?= $this->lang->line('account'); ?></label>
                                                    <select class="form-control select2" id='account_id' name="account_id" onchange="checkAccountBalance()">
                                                      <?php
                                                        echo '<option value="">-None-</option>'; 
                                                        echo get_accounts_select_list();
                                                        ?>
                                                    </select>
                                                    <span id="account_id_msg" style="display:none" class="text-danger"></span>
                                                    <div id="account_balance_display" class="text-info" style="margin-top: 5px; font-size: 12px; min-height: 20px;"></div>
                                                </div>
                                            <div class="clearfix"></div>
                                        </div>  
                                        <div class="row">
                                               <div class="col-md-12">
                                                  <div class="">
                                                    <label for="payment_note"><?= $this->lang->line('payment_note'); ?></label>
                                                    <textarea type="text" class="form-control" id="payment_note" name="payment_note" placeholder="" ></textarea>
                                                    <span id="payment_note_msg" style="display:none" class="text-danger"></span>
                                                  </div>
                                               </div>
                                                
                                            <div class="clearfix"></div>
                                        </div>   
                                        </div>
                                        </div>
                                        </div><!-- col-md-12 -->
                                       </div>
                                       <!-- /.box-body -->
                                    </div>
                                 <!-- /.box -->
                              </div>

                              

                           </div>
                           
                           <!-- /.box-body -->
                           <div class="box-footer col-sm-12">
                              <center>
                                <?php
                                if(isset($purchase_id)){
                                  $btn_id='update';
                                  $btn_name="Update";
                                  echo '<input type="hidden" name="purchase_id" id="purchase_id" value="'.$purchase_id.'"/>';
                                }
                                else{
                                  $btn_id='save';
                                  $btn_name="Save";
                                }

                                ?>
                                 <div class="col-md-3 col-md-offset-3">
                                    <button type="button" id="<?php echo $btn_id;?>" class="btn btn-block btn-success payments_modal" title="Save Data"><?php echo $btn_name;?></button>
                                 </div>
                                 <div class="col-sm-3"><a href="<?= base_url()?>dashboard">
                                    <button type="button" class="btn btn-block btn-warning" title="Go Dashboard">Close</button>
                                  </a>
                                </div>
                              </center>
                           </div>
                           

                           <?= form_close(); ?>
                           <!-- OK END -->
                     </div>
                  </div>
                  <!-- /.box-footer -->
                 
               </div>
               <!-- /.box -->
             </section>
            <!-- /.content -->
  </div>
  <!-- /.content-wrapper -->
  
 <?php include"footer.php"; ?>
<!-- SOUND CODE -->
<?php include"comman/code_js_sound.php"; ?>
<!-- GENERAL CODE -->
<?php include"comman/code_js.php"; ?>
<!-- Toastr JS -->
<script src="<?php echo $theme_link; ?>toastr/toastr.min.js"></script>

 <script src="<?php echo $theme_link; ?>js/modals.js"></script>
 <script src="<?php echo $theme_link; ?>js/modals/modal_item.js"></script>
  <!-- Add the sidebar's background. This div must be placed
       immediately after the control sidebar -->
  <div class="control-sidebar-bg"></div>
</div>
<!-- ./wrapper -->

<script src="<?php echo $theme_link; ?>js/purchase.js"></script>  
<script src="<?php echo $theme_link; ?>js/ajaxselect/supplier_select_ajax.js"></script>  

<script>

         //supplier Selection Box Search
         function getsupplierSelectionId() {
           return '#supplier_id';
         }

         $(document).ready(function () {

            // Initialize Toastr
            toastr.options = {
                "closeButton": true,
                "debug": false,
                "newestOnTop": false,
                "progressBar": true,
                "positionClass": "toast-top-right",
                "preventDuplicates": false,
                "onclick": null,
                "showDuration": "300",
                "hideDuration": "1000",
                "timeOut": "5000",
                "extendedTimeOut": "1000",
                "showEasing": "swing",
                "hideEasing": "linear",
                "showMethod": "fadeIn",
                "hideMethod": "fadeOut"
            };

            var supplier_id = "<?= (!empty($supplier_id)) ? $supplier_id : '';  ?>";

            if(supplier_id!=''){
               autoLoadFirstsupplier(supplier_id);
               // Check currency after supplier is loaded - handled by purchase.js
               // setTimeout(function() {
               //   check_supplier_currency_for_purchase();
               // }, 500);
            }
            
            // Check account balance when page loads (for payment modal)
            setTimeout(function() {
                if (typeof checkAccountBalance === 'function') {
                    checkAccountBalance();
                }
            }, 1000);

            // Auto-fill form with converted requisition data
            <?php if (isset($converted_requisition)): ?>
            var convertedRequisition = <?= json_encode($converted_requisition); ?>;
            
            // Show success message
            toastr.success('Requisition converted to purchase. Please review and adjust the details as needed.', 'Converted Successfully', {
                timeOut: 5000,
                progressBar: true
            });
            
            // Auto-fill form fields
            setTimeout(function() {
                // Set a flag to prevent clearing during requisition conversion
                window.isConvertingRequisition = true;
                
                // Fill warehouse
                if (convertedRequisition.warehouse_id) {
                    $('#warehouse_id').val(convertedRequisition.warehouse_id).trigger('change');
                }
                
                // Fill store
                if (convertedRequisition.store_id) {
                    $('#store_id').val(convertedRequisition.store_id).trigger('change');
                }
                
                // Fill currency
                if (convertedRequisition.currency_id) {
                    $('#currency_id').val(convertedRequisition.currency_id).trigger('change');
                }
                
                // Fill notes
                if (convertedRequisition.notes) {
                    $('#notes').val(convertedRequisition.notes);
                }
                
                // Add items to purchase table using AJAX (after all form fields are set)
                if (convertedRequisition.requisition_id) {
                    console.log('Loading requisition items for ID:', convertedRequisition.requisition_id);
                    
                    // Load requisition items via AJAX
                    $.post(base_url + "purchase/return_requisition_list/" + convertedRequisition.requisition_id, {}, function(result) {
                        console.log('AJAX result:', result);
                        
                        if (result && result.trim() !== '') {
                            $('#purchase_table tbody').append(result);
                            
                            // Count the number of rows added
                            var addedRows = $('#purchase_table tbody tr').length;
                            $("#hidden_rowcount").val(addedRows);
                            
                            // Enable item discount functionality
                            if (typeof enable_or_disable_item_discount === 'function') {
                                enable_or_disable_item_discount();
                            }
                            
                            console.log('Items loaded successfully. Row count:', addedRows);
                        } else {
                            console.error('No items returned from server');
                            toastr.error('No items found in the requisition', 'Error');
                        }
                        
                        // Clear the flag after items are loaded
                        window.isConvertingRequisition = false;
                    }).fail(function(xhr, status, error) {
                        console.error('AJAX error:', error);
                        console.error('Response:', xhr.responseText);
                        toastr.error('Failed to load requisition items: ' + error, 'Error');
                        window.isConvertingRequisition = false;
                    });
                } else {
                    console.log('No requisition ID found');
                    // Clear the flag if no requisition
                    window.isConvertingRequisition = false;
                }
                
                // Calculate totals
                setTimeout(function() {
                    if (typeof calculateTotal === 'function') {
                        calculateTotal();
                    }
                }, 1000);
                
            }, 500);
            <?php endif; ?>

         });
         //supplier Selection Box Search - END


        var base_url=$("#base_url").val();
        $("#store_id").on("change",function(){
          var store_id=$(this).val();
          $.post(base_url+"purchase/get_suppliers_select_list",{store_id:store_id},function(result){
              $("#supplier_id").html('').append(result).select2();
              // Don't clear table during requisition conversion
              if (!window.isConvertingRequisition) {
                  $("#purchase_table > tbody").empty();
              }
              final_total();
              // Check currency after suppliers are loaded - handled by purchase.js
              // setTimeout(function() {
              //   check_supplier_currency_for_purchase();
              // }, 300);
          });
          $.post(base_url+"sales/get_tax_select_list",{store_id:store_id},function(result){
              $("#other_charges_tax_id").html('').append(result).select2();
              final_total();
          });
          
        });

        // Set base currency data for JavaScript
        window.baseCurrencyName = '<?= get_base_currency()->currency_name ?>';
        window.baseCurrencyCode = '<?= get_base_currency()->currency_code ?>';
        window.baseCurrencySymbol = '$';
        window.baseCurrencyId = '<?= get_base_currency()->id ?>';

        // Supplier change event listener - handled by purchase.js show_supplier_currency() function
        // $("#supplier_id").on("change select2:select", function() {
        //   // Check if supplier has different currency than base currency
        //   check_supplier_currency_for_purchase();
        // });

        /*Warehouse*/
        $("#warehouse_id").on("change",function(){
          var warehouse_id=$(this).val();
          // Don't clear table during requisition conversion
          if (!window.isConvertingRequisition) {
              $("#purchase_table > tbody").empty();
          }
          final_total();
        });
        /*Warehouse end*/


         $(".close_btn").on("click",function(){
           if(confirm('Are you sure you want to navigate away from this page?')){
               window.location='<?php echo $base_url; ?>dashboard';
             }
         });
         //Initialize Select2 Elements
             $(".select2").select2();
         //Date picker
             $('.datepicker').datepicker({
               autoclose: true,
            format: 'dd-mm-yyyy',
              todayHighlight: true
             });
          
       


         
         /* ---------- CALCULATE TAX -------------*/
         function calculate_tax(i){ //i=Row
           set_tax_value(i);

           //Find the Tax type and Tax amount
           var tax_type = $("#tr_tax_type_"+i).val();
           var tax_amount = get_float_type_data("#td_data_"+i+"_5");
           var qty=get_float_type_data("#td_data_"+i+"_3")
           var purchase_price=get_float_type_data("#td_data_"+i+"_4");
           var discount =get_float_type_data("#td_data_"+i+"_8");
           var tax=get_float_type_data("#tr_tax_value_"+i);
           
           var amt=qty * purchase_price;//Taxable
         
           var total_amt=amt-discount;

          

           total_amt = (tax_type=='Inclusive') ? total_amt : total_amt + tax_amount;
           
           //CAlculate Item wise price and tax and discount
           var tax_each = (tax_type=='Inclusive') ? 0 : calculate_exclusive(purchase_price-discount,tax);
           
           $("#td_data_"+i+"_10").val('').val(to_Fixed(total_amt/qty));
           $("#td_data_"+i+"_9").val('').val(to_Fixed(total_amt));
           final_total();
         }
         
         // Calculate from total amount (reverse calculation)
         var calculating_total = {}; // Track which rows are being calculated to prevent loops
         function calculate_from_total(i){
           // Prevent recursion
           if(calculating_total[i]){
             return;
           }
           
           var total_amt_str = $("#td_data_"+i+"_9").val().replace(/[^0-9.-]/g, ''); // Get raw value without formatting
           var total_amt = parseFloat(total_amt_str) || 0;
           
           if(total_amt <= 0 || isNaN(total_amt) || total_amt_str === ''){
             return;
           }
           
           calculating_total[i] = true; // Set flag
           
           var qty = get_float_type_data("#td_data_"+i+"_3");
           if(qty <= 0 || isNaN(qty)){
             calculating_total[i] = false;
             return;
           }
           
           var tax_type = $("#tr_tax_type_"+i).val();
           var tax_amount = get_float_type_data("#td_data_"+i+"_5");
           var discount = get_float_type_data("#td_data_"+i+"_8");
           
           // Reverse calculate: total_amt = (qty * purchase_price - discount) + tax_amount (for exclusive)
           // For Inclusive: total_amt = qty * purchase_price - discount
           // For Exclusive: total_amt = (qty * purchase_price - discount) + tax_amount
           // So: qty * purchase_price - discount = total_amt - tax_amount (for exclusive) or = total_amt (for inclusive)
           var amt_before_tax = (tax_type=='Inclusive') ? total_amt : total_amt - tax_amount;
           var amt_before_discount = amt_before_tax + discount;
           
           // Calculate purchase price per unit
           var purchase_price = amt_before_discount / qty;
           
           if(purchase_price <= 0 || isNaN(purchase_price)){
             calculating_total[i] = false;
             return;
           }
           
           // Temporarily disable calculation on price field
           $("#td_data_"+i+"_4").off('keyup');
           $("#td_data_"+i+"_9").off('keyup');
           
           // Update purchase price field
           $("#td_data_"+i+"_4").val(to_Fixed(purchase_price));
           
           // Recalculate tax and unit cost WITHOUT updating total (to preserve user input)
           set_tax_value(i);
           var tax_type_calc = $("#tr_tax_type_"+i).val();
           var tax_amount_calc = get_float_type_data("#td_data_"+i+"_5");
           var purchase_price_calc = get_float_type_data("#td_data_"+i+"_4");
           var discount_calc = get_float_type_data("#td_data_"+i+"_8");
           var amt_calc = qty * purchase_price_calc;
           var total_amt_calc = amt_calc - discount_calc;
           total_amt_calc = (tax_type_calc=='Inclusive') ? total_amt_calc : total_amt_calc + tax_amount_calc;
           
           // Update unit cost only
           $("#td_data_"+i+"_10").val(to_Fixed(total_amt_calc/qty));
           
           // DON'T update total field - keep user's input
           // $("#td_data_"+i+"_9").val(to_Fixed(total_amt_calc));
           
           final_total();
           
           // Re-enable after a delay
           setTimeout(function(){
             $("#td_data_"+i+"_4").on('keyup', function(){ calculate_tax(i); });
             $("#td_data_"+i+"_9").on('keyup', function(){ calculate_from_total(i); });
             calculating_total[i] = false;
           }, 200);
         }
         
         /* ---------- CALCULATE GST END -------------*/

        
         /* ---------- Final Description of amount ------------*/
         function final_total(){
           

           var rowcount=$("#hidden_rowcount").val();
           var subtotal=parseFloat(0);
           
           var other_charges_per_amt=parseFloat(0);
           var other_charges_total_amt=0;
           var taxable=0;
          if($("#other_charges_input").val()!=null && $("#other_charges_input").val()!=''){
             
              other_charges_tax_id =$('option:selected', '#other_charges_tax_id').attr('data-tax');
             other_charges_input=$("#other_charges_input").val();
             if(other_charges_tax_id>0){

               other_charges_per_amt=(other_charges_tax_id * other_charges_input)/100;
             }
             
             taxable=parseFloat(other_charges_per_amt)+parseFloat(other_charges_input);//Other charges input
             other_charges_total_amt=parseFloat(other_charges_per_amt)+parseFloat(other_charges_input);
           }
           else{
             //$("#other_charges_amt").html('0.00');
           }
           
         
           var tax_amt=0;
           var actual_taxable=0;
           var total_quantity=0;
         
           for(i=1;i<=rowcount;i++){
         
             if(document.getElementById("td_data_"+i+"_3")){
               //supplier_id must exist
               if($("#td_data_"+i+"_3").val()!=null && $("#td_data_"+i+"_3").val()!=''){
                    actual_taxable=actual_taxable+ + +(parseFloat($("#td_data_"+i+"_13").val()) * parseFloat($("#td_data_"+i+"_3").val()));
                    subtotal=subtotal+ + +parseFloat($("#td_data_"+i+"_9").val());
                    if($("#td_data_"+i+"_7").val()>=0){
                      tax_amt=tax_amt+ + +$("#td_data_"+i+"_7").val();
                    }   
                    total_quantity +=parseFloat($("#td_data_"+i+"_3").val());
                }
                   
             }//if end
           }//for end
           
          
          //Show total Purchase Quantitys
           $(".total_quantity").html(format_qty(total_quantity));

           //Apply Output on screen
           //subtotal
           if((subtotal!=null || subtotal!='') && (subtotal!=0)){
             
             //subtotal
             $("#subtotal_amt").html(to_Fixed(subtotal));
             
             //other charges total amount
             $("#other_charges_amt").html(to_Fixed(other_charges_total_amt));
             
             //other charges total amount
            

             taxable=taxable+subtotal;
             
             //discount_to_all_amt
            // if($("#discount_to_all_input").val()!=null && $("#discount_to_all_input").val()!=''){
                 var discount_input=parseFloat($("#discount_to_all_input").val());
                 discount_input = isNaN(discount_input) ? 0 : discount_input;
                 var discount=0;
                 if(discount_input>0){
                     var discount_type=$("#discount_to_all_type").val();
                     if(discount_type=='in_fixed'){
                       taxable-=discount_input;
                       discount=discount_input;
                       //Minus
                     }
                     else if(discount_type=='in_percentage'){
                         discount=(taxable*discount_input)/100;
                        taxable-=discount;
             
                     }
                 }
                 else{
                    //discount += $("#")
                 }
                   discount=parseFloat(discount);
                   
                    $("#discount_to_all_amt").html(to_Fixed(discount));  
                    $("#hidden_discount_to_all_amt").val(to_Fixed(discount));  
             //}
             //subtotal_round=Math.round(taxable);
             subtotal_round=round_off(taxable);//round_off() method custom defined
             subtotal_diff=subtotal_round-taxable;
         
             $("#round_off_amt").html(to_Fixed(subtotal_diff)); 
             $("#total_amt").html(to_Fixed(subtotal_round)); 
             $("#hidden_total_amt").val(to_Fixed(subtotal_round)); 
           }
           else{
             $("#subtotal_amt").html('0.00'); 
             
             $("#tax_amt").html('0.00'); 
           }
           
          // adjust_payments();
          //alert("final_total() end");
         }
         /* ---------- Final Description of amount end ------------*/
          
         function removerow(id){//id=Rowid
           
         $("#row_"+id).remove();
         final_total();
         failed.currentTime = 0;
        failed.play();
         }
               
     

    function enable_or_disable_item_discount(){
      /*var discount_input=parseFloat($("#discount_to_all_input").val());
      discount_input = isNaN(discount_input) ? 0 : discount_input;
      if(discount_input>0){
        $(".item_discount").attr({
          'readonly': true,
          'style': 'border-color:red;cursor:no-drop',
        });
      }
      else{
        $(".item_discount").attr({
          'readonly': false,
          'style': '',
        });
      }*/

      var rowcount=$("#hidden_rowcount").val();
      for(k=1;k<=rowcount;k++){
       if(document.getElementById("tr_item_id_"+k)){
         calculate_tax(k);
       }//if end
     }//for end

      //final_total();
    }

    //Purchase Items Modal Operations Start


    function show_purchase_item_modal(row_id){

      $('#purchase_item').modal('toggle');
      $("#popup_tax_id").select2();

      //Find the item details
      var item_name = $("#td_data_"+row_id+"_1").html();
      var tax_type = $("#tr_tax_type_"+row_id).val();
      var tax_id = $("#tr_tax_id_"+row_id).val();
      var description = $("#description_"+row_id).val();

      /*Discount*/
      var item_discount_input = $("#item_discount_input_"+row_id).val();
      var item_discount_type = $("#item_discount_type_"+row_id).val();

      //Set to Popup
      $("#item_discount_input").val(item_discount_input);
      $("#item_discount_type").val(item_discount_type).select2();

      $("#popup_item_name").html(item_name);
      $("#popup_tax_type").val(tax_type).select2();
      $("#popup_tax_id").val(tax_id).select2();
      $("#popup_description").val(description);
      $("#popup_row_id").val(row_id);

    }


     function set_info(){
      var row_id = $("#popup_row_id").val();
      var tax_type = $("#popup_tax_type").val();
      var tax_id = $("#popup_tax_id").val();
      var description = $("#popup_description").val();
      var tax_name = ($('option:selected', "#popup_tax_id").attr('data-tax-value'));
      var tax = parseFloat($('option:selected', "#popup_tax_id").attr('data-tax'));

      /*Discounr*/
      var item_discount_input = $("#item_discount_input").val();
      var item_discount_type = $("#item_discount_type").val();

      //Set it into row 
      $("#item_discount_input_"+row_id).val(item_discount_input);
      $("#item_discount_type_"+row_id).val(item_discount_type);

      $("#tr_tax_type_"+row_id).val(tax_type);
      $("#tr_tax_id_"+row_id).val(tax_id);
      $("#tr_tax_value_"+row_id).val(tax);//%
      $("#description_"+row_id).val(description);
      $("#td_data_"+row_id+"_15").html(tax_name);
      
      calculate_tax(row_id);
      $('#purchase_item').modal('toggle');
    }

    
    function set_tax_value(row_id){
      //get the purchase price of the item
      var tax_type = $("#tr_tax_type_"+row_id).val();
      var tax = $("#tr_tax_value_"+row_id).val(); //%
      var qty=$("#td_data_"+row_id+"_3").val();
          qty = (isNaN(qty)) ? 0 :qty;
      var purchase_price = parseFloat($("#td_data_"+row_id+"_4").val());
          purchase_price = (isNaN(purchase_price)) ? 0 :purchase_price;
          purchase_price = purchase_price * qty;

      /*Discount*/
      var item_discount_type = $("#item_discount_type_"+row_id).val();
      var item_discount_input = parseFloat($("#item_discount_input_"+row_id).val());
          item_discount_input = (isNaN(item_discount_input)) ? 0 :item_discount_input;

      //Calculate discount      
      var discount_amt=(item_discount_type=='Percentage') ? ((purchase_price) * item_discount_input)/100 : (item_discount_input*qty);
      purchase_price-=parseFloat(discount_amt);

      var tax_amount = (tax_type=='Inclusive') ? calculate_inclusive(purchase_price,tax) : calculate_exclusive(purchase_price,tax);
      
      $("#td_data_"+row_id+"_8").val(to_Fixed(discount_amt));

      $("#td_data_"+row_id+"_5").val(to_Fixed(tax_amount));
    }
    //Purchase Items Modal Operations End
    
</script>
      <!-- UPDATE OPERATIONS -->
      <script type="text/javascript">
         <?php if(isset($purchase_id)){ ?> 
             $(document).ready(function(){
                /*$("#warehouse_id").attr('readonly',true);*/
                $("#store_id").attr('readonly',true);
                var base_url='<?= base_url();?>';
                var purchase_id='<?= $purchase_id;?>';
                $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
                $.post(base_url+"purchase/return_purchase_list/"+purchase_id,{},function(result){
                  //alert(result);
                  $('#purchase_table tbody').append(result);
                  $("#hidden_rowcount").val(parseInt(<?=$items_count;?>)+1);
                  success.currentTime = 0;
                  success.play();
                  enable_or_disable_item_discount();
                  $(".overlay").remove();
              }); 
             });
         <?php }?>

         // Runs on page load - check currency and exchange rate immediately
         $(document).ready(function () {
           // Small delay to ensure all elements are loaded
           setTimeout(function() {
             // Only check if supplier is already selected and not already checked
             var supplier_id = $("#supplier_id").val();
             if (supplier_id && supplier_id !== last_checked_supplier_id) {
               check_supplier_currency_for_purchase();
             }
           }, 500);
           
           // Exchange rate modal save handler
           $('#saveExchangeRate').on('click', function() {
               saveExchangeRate();
           });
           
           // Exchange rate modal form validation
           $('#exchangeRateForm').on('submit', function(e) {
               e.preventDefault();
               saveExchangeRate();
           });
         });

         // supplier change hook - trigger exchange rate check immediately
         $("#supplier_id").on("change select2:select", function () {
           check_supplier_currency_for_purchase();
         });

         // NEW helper to set all symbols at once
         function setAllCurrencySymbols(symbol) {
           $("#purchase_price_currency_symbol").text(symbol);
           $("#discount_currency_symbol").text(symbol);
           $("#subtotal_currency_symbol").text(symbol);
           $("#other_charges_currency_symbol").text(symbol);
           $("#discount_to_all_currency_symbol").text(symbol);
           $("#round_off_currency_symbol").text(symbol);
           $("#total_amt_currency_symbol").text(symbol);
         }

         // UPDATED: also updates the totals-box currency badge
         function check_supplier_currency_for_purchase() {
           var supplier_id = $("#supplier_id").val();
           var base_url    = $("#base_url").val();
           
           // Skip if same supplier was already checked
           if (supplier_id === last_checked_supplier_id) {
               return;
           }
           
           // Skip if no supplier selected
           if (!supplier_id || supplier_id === '') {
               return;
           }
           
           // Update last checked supplier
           last_checked_supplier_id = supplier_id;

           // Hide both badges by default
           $("#supplier_currency_info").hide();
           $("#supplier_currency_info_totals").hide();

           if (!supplier_id || supplier_id === '' ) {
             // Reset to base currency symbols if nothing selected
             var baseSymbol = '$';
             setAllCurrencySymbols(baseSymbol);
             return;
           }

           $.ajax({
             url: base_url + 'purchase/get_supplier_currency',
             type: 'POST',
             data: { supplier_id: supplier_id },
             dataType: 'json',
             success: function (res) {
               if (!res || !res.status) return;

               // Decide which symbol we should display on the form
               var symbol = res.supplier_currency_symbol || res.currency_symbol;

               // Badge text (name + code) - fix the display format
               var supplierText = '';
               if (res.supplier_currency_name && res.supplier_currency_code) {
                 supplierText = res.supplier_currency_name + ' (' + res.supplier_currency_code + ')';
               } else if (res.currency_name && res.currency_code) {
                 supplierText = res.currency_name + ' (' + res.currency_code + ')';
               } else {
                 supplierText = 'Unknown Currency';
               }

               // Show badges in BOTH places
               $("#supplier_currency_name").text(supplierText);
               $("#supplier_currency_info").show();

               $("#supplier_currency_name_totals").text(supplierText);
               $("#supplier_currency_info_totals").show();

               // Check exchange rate IMMEDIATELY if supplier has different currency
               if (res.supplier_currency_id && 
                   res.base_currency_id && 
                   res.supplier_currency_id != res.base_currency_id) {
                   // Pass supplier currency as FROM and base currency as TO with names and codes
                   checkExchangeRate(
                       res.supplier_currency_id, 
                       res.base_currency_id,
                       res.supplier_currency_name,
                       res.supplier_currency_code,
                       res.base_currency_name,
                       res.base_currency_code
                   );
               }

               // Update all currency symbols across the form and totals box
               setAllCurrencySymbols(symbol);

               // Multi-currency is now allowed in purchase
               // No restrictions - just show the currency info and allow the transaction
             },
             error: function () {
               toastr["warning"]("Unable to verify supplier currency. Please try again.");
             }
           });
         }

         // Global flag to track exchange rate validation
         var exchangeRateValid = true;
         var exchangeRateCheckInProgress = false;
         
         // Track last checked supplier to prevent duplicate calls
         var last_checked_supplier_id = null;
         
         // Track if alert is already being shown to prevent duplicates
         var alertCurrentlyShowing = false;

         // Function to check exchange rate between currencies
         function checkExchangeRate(from_currency_id, to_currency_id, from_currency_name, from_currency_code, to_currency_name, to_currency_code) {
             if (!from_currency_id || !to_currency_id || from_currency_id == to_currency_id) {
                 exchangeRateValid = true;
                 return; // No need to check if same currency or missing data
             }
             
             // Prevent duplicate calls if already in progress
             if (exchangeRateCheckInProgress) {
                 return;
             }

             // Store current currency IDs and details for modal - ALWAYS store them
             window.currentFromCurrencyId = from_currency_id;
             window.currentToCurrencyId = to_currency_id;
             window.currentFromCurrencyName = from_currency_name || 'Supplier Currency';
             window.currentFromCurrencyCode = from_currency_code || 'CUR';
             window.currentToCurrencyName = to_currency_name || 'System Currency';
             window.currentToCurrencyCode = to_currency_code || 'SYS';

             var base_url = $("#base_url").val();
             exchangeRateCheckInProgress = true;
             
             $.ajax({
                 url: base_url + 'exchange_rates/check_exchange_rate',
                 type: 'POST',
                 data: { 
                     from_currency_id: from_currency_id,
                     to_currency_id: to_currency_id
                 },
                 dataType: 'json',
                 success: function(response) {
                     exchangeRateCheckInProgress = false;
                     
                     if (!response || !response.exists) {
                         exchangeRateValid = false;
                         // Only show alert if rate is actually missing
                         showEnterpriseAlert(
                             'Rate missing, please add exchange rate for this currency conversion.',
                             'warning'
                         );
                     } else {
                         exchangeRateValid = true;
                         // Rate exists, no alert needed
                     }
                 },
                 error: function(xhr, status, error) {
                     exchangeRateCheckInProgress = false;
                     exchangeRateValid = false;
                     // Don't show alert on error - let the success handler handle it
                 }
             });
         }

         // Function to show exchange rate modal
         function showExchangeRateModal() {
             // Pre-populate the modal with the actual currency data we have
             var fromCurrencyName = window.currentFromCurrencyName || 'Supplier Currency';
             var fromCurrencyCode = window.currentFromCurrencyCode || 'CUR';
             var toCurrencyName = window.currentToCurrencyName || 'System Currency';
             var toCurrencyCode = window.currentToCurrencyCode || 'SYS';
             
             // Set the dropdowns immediately with the known currency data
             $('#from_currency').html('<option value="' + window.currentFromCurrencyId + '">' + fromCurrencyName + ' (' + fromCurrencyCode + ')</option>');
             $('#to_currency').html('<option value="' + window.currentToCurrencyId + '">' + toCurrencyName + ' (' + toCurrencyCode + ')</option>');
             
             // Select the currencies
             $('#from_currency').val(window.currentFromCurrencyId);
             $('#to_currency').val(window.currentToCurrencyId);
             
             // Show the modal
             $('#exchangeRateModal').modal({
                 backdrop: 'static',
                 keyboard: false
             });
         }

         // Function to load currencies into dropdowns
         function loadCurrencies() {
             var baseUrl = $("#base_url").val();
             
             // Always load currencies fresh to ensure we have the latest data
             $.ajax({
                 url: baseUrl + 'currencies/get_all_currencies',
                 type: 'POST',
                 dataType: 'json',
                 success: function(response) {
                     if (response && response.currencies) {
                         window.availableCurrencies = response.currencies;
                         populateCurrencyDropdowns(response.currencies);
                     } else {
                         // Fallback - create currencies from known data
                         var currencies = [
                             {
                                 id: window.currentFromCurrencyId,
                                 currency_name: 'Supplier Currency',
                                 currency_code: 'CUR'
                             },
                             {
                                 id: window.currentToCurrencyId,
                                 currency_name: 'System Currency', 
                                 currency_code: 'SYS'
                             }
                         ];
                         populateCurrencyDropdowns(currencies);
                     }
                 },
                 error: function(xhr, status, error) {
                     // Fallback - create currencies from known data
                     var currencies = [
                         {
                             id: window.currentFromCurrencyId,
                             currency_name: 'Supplier Currency',
                             currency_code: 'CUR'
                         },
                         {
                             id: window.currentToCurrencyId,
                             currency_name: 'System Currency',
                             currency_code: 'SYS'
                         }
                     ];
                     populateCurrencyDropdowns(currencies);
                 }
             });
         }

         // Helper function to populate currency dropdowns
         function populateCurrencyDropdowns(currencies) {
             var fromSelect = $('#from_currency');
             var toSelect = $('#to_currency');
             
             fromSelect.empty().append('<option value="">Select Supplier Currency</option>');
             toSelect.empty().append('<option value="">Select System Currency</option>');
             
             $.each(currencies, function(index, currency) {
                 var option = '<option value="' + currency.id + '">' + 
                            currency.currency_name + ' (' + currency.currency_code + ')</option>';
                 fromSelect.append(option);
                 toSelect.append(option);
             });
             
             // Set the currencies based on stored IDs with retry mechanism
             if (window.currentFromCurrencyId) {
                 fromSelect.val(window.currentFromCurrencyId);
                 
                 // If selection failed, try again after a short delay
                 if (!fromSelect.val()) {
                     setTimeout(function() {
                         fromSelect.val(window.currentFromCurrencyId);
                     }, 100);
                 }
             }
             
             if (window.currentToCurrencyId) {
                 toSelect.val(window.currentToCurrencyId);
                 
                 // If selection failed, try again after a short delay
                 if (!toSelect.val()) {
                     setTimeout(function() {
                         toSelect.val(window.currentToCurrencyId);
                     }, 100);
                 }
             }
         }

         // Function to save exchange rate
         function saveExchangeRate() {
             var rateSource = $('input[name="rate_source"]:checked').val();
             var formData = {
                 from_currency_id: $('#from_currency').val() || window.currentFromCurrencyId,
                 to_currency_id: $('#to_currency').val() || window.currentToCurrencyId,
                 exchange_rate: $('#exchange_rate').val(),
                 rate_date: $('#rate_date').val(),
                 rate_note: $('#rate_note').val(),
                 rate_source: rateSource
             };
             
             // Validate form
             if (!formData.from_currency_id || !formData.to_currency_id) {
                 alert('Please select both currencies.');
                 return;
             }
             
             if (formData.from_currency_id == formData.to_currency_id) {
                 alert('From and To currencies cannot be the same.');
                 return;
             }
             
             if (rateSource === 'manual' && !formData.exchange_rate) {
                 alert('Please enter the exchange rate.');
                 return;
             }
             
             var baseUrl = $("#base_url").val();
             
             // Show loading state
             $('#saveExchangeRate').prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Saving...');
             
             // If API source, fetch rate first
             if (rateSource === 'api') {
                 fetchExchangeRateFromAPI(formData, baseUrl);
             } else {
                 // Manual entry - save directly
                 saveExchangeRateData(formData, baseUrl);
             }
         }

         // Function to fetch exchange rate from API
         function fetchExchangeRateFromAPI(formData, baseUrl) {
             $.ajax({
                 url: baseUrl + 'exchange_rates/fetch_from_api',
                 type: 'POST',
                 data: {
                     from_currency_id: formData.from_currency_id,
                     to_currency_id: formData.to_currency_id,
                     rate_date: formData.rate_date
                 },
                 dataType: 'json',
                 success: function(response) {
                     if (response.success && response.exchange_rate) {
                         formData.exchange_rate = response.exchange_rate;
                         formData.rate_note = (formData.rate_note || '') + ' (Fetched from API)';
                         saveExchangeRateData(formData, baseUrl);
                     } else {
                         // Switch to manual entry mode automatically
                         $('input[name="rate_source"][value="manual"]').prop('checked', true);
                         $('#exchange_rate').focus();
                         showEnterpriseAlert('API rate fetch failed: ' + (response.message || 'Unknown error') + '. Switched to manual entry mode.', 'warning');
                         $('#saveExchangeRate').prop('disabled', false).html('<i class="fa fa-save"></i> Save Exchange Rate');
                     }
                 },
                 error: function() {
                     // Switch to manual entry mode automatically
                     $('input[name="rate_source"][value="manual"]').prop('checked', true);
                     $('#exchange_rate').focus();
                     showEnterpriseAlert('API rate fetch failed. Switched to manual entry mode. Please enter the exchange rate manually.', 'warning');
                     $('#saveExchangeRate').prop('disabled', false).html('<i class="fa fa-save"></i> Save Exchange Rate');
                 }
             });
         }

         // Function to save exchange rate data
         function saveExchangeRateData(formData, baseUrl) {
             $.ajax({
                 url: baseUrl + 'exchange_rates/save_exchange_rate',
                 type: 'POST',
                 data: formData,
                 dataType: 'json',
                 success: function(response) {
                     if (response.success) {
                         // Close modal
                         $('#exchangeRateModal').modal('hide');
                         
                         // Show success message
                         showEnterpriseAlert('Exchange rate saved successfully!', 'success');
                         
                         // Re-check exchange rate
                         if (window.currentFromCurrencyId && window.currentToCurrencyId) {
                             checkExchangeRate(
                                 window.currentFromCurrencyId, 
                                 window.currentToCurrencyId,
                                 window.currentFromCurrencyName,
                                 window.currentFromCurrencyCode,
                                 window.currentToCurrencyName,
                                 window.currentToCurrencyCode
                             );
                         }
                         
                         // Reset form
                         $('#exchangeRateForm')[0].reset();
                         $('input[name="rate_source"][value="manual"]').prop('checked', true);
                     } else {
                         alert('Error saving exchange rate: ' + (response.message || 'Unknown error'));
                     }
                 },
                 error: function(xhr, status, error) {
                     alert('Error saving exchange rate. Please try again.');
                 },
                 complete: function() {
                     // Reset button state
                     $('#saveExchangeRate').prop('disabled', false).html('<i class="fa fa-save"></i> Save Exchange Rate');
                 }
             });
         }

         // Enterprise Alert System
         function showEnterpriseAlert(message, type) {
             // Prevent duplicate alerts
             if (alertCurrentlyShowing) {
                 return;
             }
             
             // Set flag to prevent duplicates
             alertCurrentlyShowing = true;
             
             // Remove any existing alerts
             $('.enterprise-alert').remove();
             
             var alertClass = 'warning';
             if (type === 'success') alertClass = 'success';
             if (type === 'error') alertClass = 'error';
             
             var alertHtml = '<div class="enterprise-alert ' + alertClass + '">' +
                 '<i class="fa fa-exclamation-triangle"></i> ' + message +
                 '<br><br>' +
                 '<a href="' + $("#base_url").val() + 'exchange_rates" class="btn btn-sm btn-warning" style="margin-top: 8px;">' +
                 '<i class="fa fa-plus"></i> Add Exchange Rate</a>' +
                 '</div>';
             
             $('body').append(alertHtml);
             
             // Auto remove after 8 seconds (longer to allow user to click button)
             setTimeout(function() {
                 $('.enterprise-alert').fadeOut(300, function() {
                     $(this).remove();
                     // Reset flag when alert is removed
                     alertCurrentlyShowing = false;
                 });
             }, 8000);
         }



      </script>
      <!-- UPDATE OPERATIONS end-->

      <!-- Removed keyboard shortcuts script -->

      <!-- Make sidebar menu hughlighter/selector -->
      <script>$(".<?php echo basename(__FILE__,'.php');?>-active-li").addClass("active");</script>

      <!-- Exchange Rate Modal -->
      <div class="modal fade" id="exchangeRateModal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-lg" role="document">
          <div class="modal-content">
            <div class="modal-header bg-warning">
              <h4 class="modal-title">
                <i class="fa fa-exclamation-triangle"></i> Add Exchange Rate
              </h4>
            </div>
            <div class="modal-body">
              <div class="alert alert-warning">
                <strong>Exchange Rate Missing!</strong> Please add the exchange rate for this currency conversion to proceed.
              </div>
              
              <!-- Rate Source Selection -->
              <div class="form-group">
                <label>Rate Source</label>
                <div class="radio">
                  <label>
                    <input type="radio" name="rate_source" value="manual" checked> Manual Entry
                  </label>
                </div>
                <div class="radio">
                  <label>
                    <input type="radio" name="rate_source" value="api"> Fetch from API
                  </label>
                </div>
              </div>
              
              <form id="exchangeRateForm">
                <div class="row">
                  <div class="col-md-6">
                    <div class="form-group">
                      <label for="from_currency">From Currency (Supplier Currency)</label>
                      <select class="form-control" id="from_currency" name="from_currency" required readonly disabled>
                        <option value="">Select Supplier Currency</option>
                      </select>
                    </div>
                  </div>
                  <div class="col-md-6">
                    <div class="form-group">
                      <label for="to_currency">To Currency (System Currency)</label>
                      <select class="form-control" id="to_currency" name="to_currency" required readonly disabled>
                        <option value="">Select System Currency</option>
                      </select>
                    </div>
                  </div>
                </div>
                
                <div class="row">
                  <div class="col-md-6">
                    <div class="form-group">
                      <label for="exchange_rate">Exchange Rate</label>
                      <input type="number" class="form-control" id="exchange_rate" name="exchange_rate" 
                             step="0.000001" min="0" placeholder="Enter exchange rate" required>
                    </div>
                  </div>
                  <div class="col-md-6">
                    <div class="form-group">
                      <label for="rate_date">Rate Date</label>
                      <input type="date" class="form-control" id="rate_date" name="rate_date" 
                             value="<?= date('Y-m-d') ?>" required>
                    </div>
                  </div>
                </div>
                
                <div class="form-group">
                  <label for="rate_note">Notes (Optional)</label>
                  <textarea class="form-control" id="rate_note" name="rate_note" rows="2" 
                            placeholder="Add any notes about this exchange rate"></textarea>
                </div>
              </form>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
              <button type="button" class="btn btn-warning" id="saveExchangeRate">
                <i class="fa fa-save"></i> Save Exchange Rate
              </button>
            </div>
          </div>
        </div>
      </div>
</body>
</html>
