<!DOCTYPE html>
<html>
   <head>
      <!-- TABLES CSS CODE -->      
      <?php $this->load->view('comman/code_css.php');?>
      <!-- </copy> -->  
   </head>
   <body class="hold-transition skin-blue sidebar-mini">
      <div class="wrapper">
         <?php $this->load->view('sidebar');?>
         <?php
            if(!isset($q_id)){
                 $payment_type=$amount=$note="";
                 $customer_id='';
                 $payment_date =show_date(date("d-m-Y"));
            }
            ?>
         <!-- Content Wrapper. Contains page content -->
         <div class="content-wrapper">
            <!-- Content Header (Page header) -->
            <section class="content-header">
               <h1>
                  <?=$page_title;?>
                  <small>Add/Update Brand</small>
               </h1>
               <ol class="breadcrumb">
                  <li><a href="<?php echo $base_url; ?>dashboard"><i class="fa fa-dashboard"></i> Home</a></li>
                  <li><a data-toggle='tooltip' title='Do you want Import Customers ?' href="<?php echo $base_url; ?>customers"> <?= $this->lang->line('customers_list'); ?></a></li>
                  <li><a href="<?php echo $base_url; ?>customers_advance"><?= $this->lang->line('advance_payments_list'); ?></a></li>
                  <li class="active"><?=$page_title;?></li>
               </ol>
            </section>

            <!-- **********************MODALS***************** -->
            <?php $this->load->view('modals/modal_customer');?>
            <!-- **********************MODALS END***************** -->
            <!-- Main content -->
            <section class="content">
               <div class="row">
                  <!-- right column -->
                  <div class="col-md-12">
                     <!-- Horizontal Form -->
                     <div class="box box-primary ">
                        <div class="box-header with-border">
                           <h3 class="box-title">Please Enter Valid Data</h3>
                        </div>
                        <!-- /.box-header -->
                        <!-- form start -->
                        <form class="form-horizontal" id="advance-form">
                           <input type="hidden" name="<?php echo $this->security->get_csrf_token_name();?>" value="<?php echo $this->security->get_csrf_hash();?>">
                           <input type="hidden" id="base_url" value="<?php echo $base_url;; ?>">
                           <div class="box-body">
                              <!-- Store Code -->
                               <?php 
                                echo "<input type='hidden' name='store_id' id='store_id' value='".get_current_store_id()."'>";
                               ?>
                              <!-- Store Code end -->
                              <div class="form-group">
                                 <label for="payment_date" class="col-sm-2 control-label"><?= $this->lang->line('date'); ?><label class="text-danger">*</label></label>
                                 <div class="col-sm-4">
                                    <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="payment_date" name="payment_date" readonly onkeyup="shift_cursor(event,'sales_status')" value="<?= $payment_date;?>">
                                    </div>
                                    <span id="payment_date_msg" style="display:none" class="text-danger"></span>
                                 </div>
                              </div>
                              <div class="form-group">
                                 <label for="customer_id" class="col-sm-2 control-label"><?= $this->lang->line('customer_name'); ?><label class="text-danger">*</label></label>
                                 <div class="col-sm-4">
                                    <div class="input-group">
                                       <select class="form-control select2" id="customer_id" name="customer_id"  style="width: 100%;">
                                       </select>
                                       <span class="input-group-addon pointer" data-toggle="modal" data-target="#customer-modal" title="New Customer?"><i class="fa fa-user-plus text-primary fa-lg"></i></span>
                                    </div>
                                    <span id="customer_id_msg" style="display:none" class="text-danger"></span>
                                    
                                 </div>
                              </div>
                              <div class="form-group">
                                 <label for="amount" class="col-sm-2 control-label"><?= $this->lang->line('amount'); ?><label class="text-danger">*</label></label>
                                 <div class="col-sm-4">
                                    <div class="input-group">
                                       <input type="text" class="form-control input-sm" id="amount" name="amount" placeholder="" value="<?php print $amount; ?>" autofocus >
                                       <span class="input-group-addon" id="amount_currency_symbol"><?= get_base_currency()->symbol ?></span>
                                    </div>
                                    <span id="amount_msg" style="display:none" class="text-danger"></span>
                                    <!-- Currency conversion display -->
                                    <div id="currency_conversion_display" class="text-info" style="margin-top: 5px; font-size: 12px; display: none;">
                                       <span id="conversion_text"></span>
                                    </div>
                                 </div>
                              </div>
                              <div class="form-group">
                                <label for="payment_type" class="col-sm-2 control-label"><?= $this->lang->line('payment_type'); ?><label class="text-danger">*</label></label>
                                <div class="col-sm-4">
                                  <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){
                                            $selected = (!empty($payment_type) && ($res1->payment_type==$payment_type)) ? 'selected' : '';
                                           echo "<option $selected 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="form-group">
                                 <label for="note" class="col-sm-2 control-label"><?= $this->lang->line('note'); ?></label>
                                 <div class="col-sm-4">
                                    <textarea type="text" class="form-control" id="note" name="note" placeholder=""><?php print $note; ?></textarea>
                                    <span id="note_msg" style="display:none" class="text-danger"></span>
                                 </div>
                              </div>
                           </div>
                           <!-- /.box-footer -->
                           <div class="box-footer">
                              <div class="col-sm-8 col-sm-offset-2 text-center">
                                 <!-- <div class="col-sm-4"></div> -->
                                 <?php
                                    if(isset($q_id)){
                                         $btn_name="Update";
                                         $btn_id="update";
                                        ?>
                                 <input type="hidden" name="q_id" id="q_id" value="<?php echo $q_id;?>"/>
                                 <?php
                                    }
                                              else{
                                                  $btn_name="Save";
                                                  $btn_id="save";
                                              }
                                    
                                              ?>
                                 <div class="col-md-3 col-md-offset-3">
                                    <button type="button" id="<?php echo $btn_id;?>" class=" btn btn-block btn-success" title="Save Data"><?php echo $btn_name;?></button>
                                 </div>
                                 <div class="col-sm-3">
                                    <a href="<?=base_url('dashboard');?>">
                                    <button type="button" class="col-sm-3 btn btn-block btn-warning close_btn" title="Go Dashboard">Close</button>
                                    </a>
                                 </div>
                              </div>
                           </div>
                           <!-- /.box-footer -->
                        </form>
                     </div>
                     <!-- /.box -->
                  </div>
                  <!--/.col (right) -->
               </div>
               <!-- /.row -->
            </section>
            <!-- /.content -->
         </div>
         <!-- /.content-wrapper -->
         <?php $this->load->view('footer');?>
         <!-- Add the sidebar's background. This div must be placed
            immediately after the control sidebar -->
         <div class="control-sidebar-bg"></div>
      </div>
      <!-- ./wrapper -->
      <!-- SOUND CODE -->
      <?php $this->load->view('comman/code_js_sound.php');?>
      <!-- TABLES CODE -->
      <?php $this->load->view('comman/code_js.php');?>
      
      <script src="<?php echo $theme_link; ?>js/customers_advance/advance.js"></script>
      <script src="<?php echo $theme_link; ?>js/modals.js"></script>
      <script type="text/javascript">
        <?php if(isset($q_id)){ ?>
          $("#store_id").attr('readonly',true);
        <?php }?>
      </script>
      <script src="<?php echo $theme_link; ?>js/ajaxselect/customer_select_ajax.js"></script>  
      <script>

         //Customer Selection Box Search
         function getCustomerSelectionId() {
           return '#customer_id';
         }

         $(document).ready(function () {

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

            autoLoadFirstCustomer(customer_id);
            
            // Trigger currency conversion if customer is already selected
            setTimeout(function() {
                if ($('#customer_id').val()) {
                    updateCurrencyConversion();
                }
            }, 1000);

         });
         //Customer Selection Box Search - END

         // Currency conversion functionality
         function updateCurrencyConversion() {
             var amount = parseFloat($('#amount').val()) || 0;
             var customerId = $('#customer_id').val();
             var baseUrl = $('#base_url').val();
             
             if (amount > 0 && customerId) {
                 // Get customer currency and convert
                 $.ajax({
                     url: baseUrl + 'customers/get_customer_currency',
                     type: 'POST',
                     data: { customer_id: customerId },
                     dataType: 'json',
                     success: function(response) {
                         if (response.status) {
                             var customerCurrency = response.currency_name + ' (' + response.currency_code + ')';
                             var baseCurrency = response.base_currency_name + ' (' + response.base_currency_code + ')';
                             
                             // Update the currency symbol in the input field
                             $('#amount_currency_symbol').text(response.currency_symbol);
                             
                             if (response.customer_currency_id && response.customer_currency_id != response.base_currency_id) {
                                 // Get exchange rate
                                 $.ajax({
                                     url: baseUrl + 'customers/get_exchange_rate',
                                     type: 'POST',
                                     data: { 
                                         from_currency: response.customer_currency_id,
                                         to_currency: response.base_currency_id
                                     },
                                     dataType: 'json',
                                     success: function(rateResponse) {
                                         console.log('Exchange rate response:', rateResponse);
                                         
                                         if (rateResponse.status && rateResponse.exchange_rate && rateResponse.exchange_rate !== null) {
                                             var convertedAmount = amount * rateResponse.exchange_rate;
                                             var conversionText = 'Base currency equivalent: ' + 
                                                 formatCurrency(convertedAmount, rateResponse.base_symbol) + 
                                                 ' (Rate: 1 ' + rateResponse.from_code + ' = ' + rateResponse.exchange_rate + ' ' + rateResponse.base_code + ')';
                                             
                                             $('#conversion_text').html(conversionText);
                                             $('#currency_conversion_display').show();
                                         } else {
                                             var debugInfo = rateResponse.debug ? ' (Debug: ' + JSON.stringify(rateResponse.debug) + ')' : '';
                                             $('#conversion_text').html('⚠ No exchange rate found for ' + customerCurrency + debugInfo);
                                             $('#currency_conversion_display').show();
                                         }
                                     },
                                     error: function() {
                                         $('#conversion_text').html('Error calculating exchange rate');
                                         $('#currency_conversion_display').show();
                                     }
                                 });
                             } else {
                                 // Same currency as base
                                 $('#conversion_text').html('Base currency amount: ' + formatCurrency(amount, response.base_currency_symbol));
                                 $('#currency_conversion_display').show();
                             }
                         } else {
                             $('#currency_conversion_display').hide();
                         }
                     },
                     error: function() {
                         $('#currency_conversion_display').hide();
                     }
                 });
             } else {
                 $('#currency_conversion_display').hide();
             }
         }

         function formatCurrency(amount, symbol) {
             return symbol + ' ' + parseFloat(amount).toFixed(2);
         }

         // Event handlers
         $('#amount').on('input', function() {
             updateCurrencyConversion();
         });

         $('#customer_id').on('change', function() {
             // Update currency symbol immediately when customer changes
             updateCurrencySymbol();
             // Also update conversion if amount is entered
             updateCurrencyConversion();
         });

         // Function to update currency symbol only
         function updateCurrencySymbol() {
             var customerId = $('#customer_id').val();
             var baseUrl = $('#base_url').val();
             
             console.log('Updating currency symbol for customer:', customerId);
             
             if (customerId) {
                 $.ajax({
                     url: baseUrl + 'customers/get_customer_currency',
                     type: 'POST',
                     data: { customer_id: customerId },
                     dataType: 'json',
                     success: function(response) {
                         console.log('Customer currency response:', response);
                         if (response.status) {
                             // Update the currency symbol in the input field
                             $('#amount_currency_symbol').text(response.currency_symbol);
                             console.log('Updated currency symbol to:', response.currency_symbol);
                         }
                     },
                     error: function(xhr, status, error) {
                         console.log('Error getting customer currency:', error);
                         console.log('Response:', xhr.responseText);
                         // Reset to base currency on error
                         $('#amount_currency_symbol').text('<?= get_base_currency()->symbol ?>');
                     }
                 });
             } else {
                 // Reset to base currency when no customer selected
                 $('#amount_currency_symbol').text('<?= get_base_currency()->symbol ?>');
             }
         }
      </script>
      <!-- Make sidebar menu hughlighter/selector -->
      <script>$(".<?php echo basename(__FILE__,'.php');?>-active-li").addClass("active");</script>
   </body>
</html>
