<!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)){
               $debit_account_id =$credit_account_id =$note=$q_id=$store_id=$reference_no='';
               $transfer_code = get_init_code("money_transfer");
               $amount=0;
               $transfer_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 Accounts</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; ?>accounts"><?= $this->lang->line('accounts_list'); ?></a></li>
                  <li class="active"><?= $this->lang->line('accounts'); ?></li>
               </ol>
            </section>
            <!-- Main content -->
            <section class="content">
               <div class="row">
                  <!-- ********** ALERT MESSAGE START******* -->
                  <?php $this->load->view('comman/code_flashdata');?>
                  <!-- ********** ALERT MESSAGE END******* -->
                  <!-- 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="money_transfer-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;; ?>">
                           <input type="hidden" id="store_id" name="store_id" value="<?php echo get_current_store_id(); ?>">
                           <input type="hidden" id="account_balance" value="0">

                           <div class="box-body">
                              <div class="form-group">
                                 <label for="transfer_date" class="col-sm-2 control-label"><?= $this->lang->line('transfer_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="transfer_date" name="transfer_date" readonly onkeyup="shift_cursor(event,'sales_status')" value="<?= $transfer_date;?>">
                                       </div>
                                       <span id="transfer_date_msg" style="display:none" class="text-danger"></span>
                                    </div>
                                    <label for="transfer_code" class="col-sm-2 control-label"><?= $this->lang->line('transfer_code'); ?> <label class="text-danger">*</label></label>
                                       <div class="col-sm-3">
                                          <input type="text" class="form-control" id="transfer_code" name="transfer_code" placeholder=""  value="<?php print $transfer_code; ?>" >
                                          <span id="transfer_code_msg" style="display:none" class="text-danger"></span>
                                       </div>
                              </div>

                              <div class="form-group">
                                     <label for="debit_account_id" class="col-sm-2 control-label">From Account <label class="text-danger">*</label></label>
                                       <div class="col-sm-3">
                                          <select class="form-control select2" id="debit_account_id" name="debit_account_id"  style="width: 100%;" onchange="updateCurrencyFromAccount()">
                                          <?php
                                             echo '<option value="">Select From Account</option>'; 
                                             echo get_accounts_select_list($debit_account_id);
                                             ?>
                                          </select>
                                          <span id="debit_account_id_msg" style="display:none" class="text-danger"></span>
                                          <div id="account_currency_info" style="margin-top: 5px;">
                                            <!-- Account currency info will be shown here -->
                                          </div>
                                       </div>  

                                       <label for="credit_account_id" class="col-sm-2 control-label">To Account <label class="text-danger">*</label></label>
                                       <div class="col-sm-3">
                                          <select class="form-control select2" id="credit_account_id" name="credit_account_id"  style="width: 100%;" onchange="validateAccountSelection(); updateToAccountInfo();">
                                          <?php
                                             echo '<option value="">Select To Account</option>'; 
                                             echo get_accounts_select_list($credit_account_id);
                                             ?>
                                          </select>
                                          <span id="credit_account_id_msg" style="display:none" class="text-danger"></span>
                                          <div id="to_account_info"></div>
                                       </div>
                              </div>

                              <div class="form-group">
                                       <label for="transfer_currency_id" class="col-sm-2 control-label">Currency <label class="text-danger">*</label></label>
                                       <div class="col-sm-3">
                                          <select class="form-control select2" id="transfer_currency_id" name="transfer_currency_id" style="width: 100%;" onchange="updateTransferCurrencyInfo()">
                                            <?php
                                              $base_currency = get_base_currency();
                                              $currencies = get_currency_list();
                                              foreach ($currencies as $currency) {
                                                $selected = ($currency->id == $base_currency->id) ? 'selected' : '';
                                                $base_indicator = ($currency->id == $base_currency->id) ? ' - Base Currency' : '';
                                                echo '<option value="'.$currency->id.'" '.$selected.'>'.$currency->currency_name.' ('.$currency->currency_code.')'.$base_indicator.'</option>';
                                              }
                                            ?>
                                          </select>
                                          <span id="transfer_currency_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-3">
                                          <div class="input-group">
                                            <span class="input-group-addon" id="transfer_currency_symbol"><?= $base_currency->symbol; ?></span>
                                            <input type="text" class="form-control only_currency" id="amount" name="amount" placeholder="" value="<?php print store_number_format($amount,0); ?>" onkeyup="updateTransferCurrencyConversion()">
                                          </div>
                                          <span id="amount_msg" style="display:none" class="text-danger"></span>
                                          <div id="transfer_base_currency_display" class="text-muted" style="margin-top: 5px; font-size: 12px;">
                                            <!-- Base currency conversion will be shown here -->
                                          </div>
                                       </div>
                                       <label for="reference_no" class="col-sm-2 control-label"><?= $this->lang->line('reference_no'); ?></label>
                                       <div class="col-sm-3">
                                          <input type="text" class="form-control" id="reference_no" name="reference_no" placeholder=""  value="<?php print $reference_no; ?>" >
                                          <span id="reference_no_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-3">
                                          <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>
                              
                              <!-- Transfer Summary -->
                              <div class="form-group" id="transfer_summary_container" style="display: none;">
                                 <div class="col-sm-12">
                                    <div class="box box-info">
                                       <div class="box-header">
                                          <h3 class="box-title"><i class="fa fa-exchange"></i> Transfer Summary</h3>
                                       </div>
                                       <div class="box-body" id="transfer_summary">
                                          <!-- Transfer summary will be displayed here -->
                                       </div>
                                    </div>
                                 </div>
                              </div>

                              
                           </div>
                           <!-- /.box-body -->
                           <div class="box-footer">
                              <div class="col-sm-8 col-sm-offset-2 text-center">
                                 <!-- <div class="col-sm-4"></div> -->
                                 <?php
                                    if($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 -->
                           <!-- /.box-footer -->
                        </form>
                     </div>
                     <!-- /.box -->
                  </div>
                  <!--/.col (right) -->
               </div>
               <!-- /.row -->
            </section>
            <!-- /.content -->
         </div>
         <!-- /.content-wrapper -->
         <?php $this->load->view('footer.php');?>
         <!-- 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/accounts/money_transfer.js"></script>
      <script type="text/javascript">
         <?php if(isset($q_id)){ ?>
           $("#store_id").attr('readonly',true);
         <?php }?>
         
         function updateTransferCurrencyInfo() {
           var selectedCurrencyId = $('#transfer_currency_id').val();
           var baseUrl = $('#base_url').val();
           
           // Update currency symbol
           $.post(baseUrl + 'currency/get_currency_info', {currency_id: selectedCurrencyId}, function(result) {
             if (result.success) {
               $('#transfer_currency_symbol').text(result.symbol);
               updateTransferCurrencyConversion();
             }
           }, 'json');
         }
         
         function updateCurrencyFromAccount() {
           var accountId = $('#debit_account_id').val();
           var baseUrl = $('#base_url').val();
           
           if (accountId) {
             // Get account currency information and balance
             $.post(baseUrl + 'accounts/get_account_currency', {account_id: accountId}, function(result) {
               if (result.success) {
                 // Update currency dropdown
                 $('#transfer_currency_id').val(result.currency_id).trigger('change');
                 
                 // Update currency symbol
                 $('#transfer_currency_symbol').text(result.currency_symbol);
                 
                 // Update conversion display
                 updateTransferCurrencyConversion();
                 
                 // Store account balance for validation
                 $('#account_balance').val(result.balance);
                 
                 // Show account currency info and balance
                 var balanceDisplay = parseFloat(result.balance).toLocaleString('en-US', {
                   minimumFractionDigits: 2,
                   maximumFractionDigits: 2
                 });
                 
                 $('#account_currency_info').html(
                   '<div class="row">' +
                     '<div class="col-sm-6">' +
                       '<small class="text-info"><i class="fa fa-info-circle"></i> ' +
                       'Currency: ' + result.currency_name + ' (' + result.currency_code + ')</small>' +
                     '</div>' +
                     '<div class="col-sm-6">' +
                       '<small class="text-success"><i class="fa fa-wallet"></i> ' +
                       'Available Balance: ' + result.currency_symbol + ' ' + balanceDisplay + '</small>' +
                     '</div>' +
                   '</div>'
                 );
               }
             }, 'json').fail(function() {
               // If no currency info, use base currency
               var baseCurrencyId = '<?= get_base_currency()->id; ?>';
               $('#transfer_currency_id').val(baseCurrencyId).trigger('change');
               $('#account_currency_info').html('');
             });
           } else {
             $('#account_currency_info').html('');
           }
         }
         
         function updateTransferCurrencyConversion() {
           var amount = parseFloat($('#amount').val()) || 0;
           var selectedCurrencyId = $('#transfer_currency_id').val();
           var baseUrl = $('#base_url').val();
           
           if (amount > 0 && selectedCurrencyId) {
             $.post(baseUrl + 'currency/get_exchange_rate', {
               from_currency: selectedCurrencyId,
               to_currency: '<?= get_base_currency()->id; ?>',
               amount: amount
             }, function(result) {
               if (result.success) {
                 var baseCurrency = '<?= get_base_currency()->symbol; ?>';
                 $('#transfer_base_currency_display').html(
                   '<i class="fa fa-exchange"></i> Base Currency: ' + 
                   baseCurrency + ' ' + parseFloat(result.base_amount).toFixed(2) + 
                   ' (Rate: ' + parseFloat(result.exchange_rate).toFixed(4) + ')'
                 );
                 
                 // Update transfer summary
                 updateTransferSummary();
               } else {
                 // Show error if rate not available
                 $('#transfer_base_currency_display').html(
                   '<div class="alert alert-warning" style="margin-top: 5px; padding: 5px;">' +
                   '<i class="fa fa-exclamation-triangle"></i> ' +
                   'Exchange rate not available. ' +
                   '<a href="' + baseUrl + 'currency" target="_blank" class="alert-link">Add Exchange Rate</a>' +
                   '</div>'
                 );
                 
                 // Show toast alert
                 if (typeof toastr !== 'undefined') {
                   toastr["warning"]("Exchange rate not available. Please add exchange rate first.", "Rate Required", {
                     "timeOut": 5000,
                     "extendedTimeOut": 2000,
                     "progressBar": true,
                     "closeButton": true
                   });
                 } else {
                   alert("Exchange rate not available. Please add exchange rate first.");
                 }
                 
                 // Clear transfer summary
                 $('#transfer_summary').html('');
               }
             }, 'json').fail(function() {
               // Show error if AJAX fails
               $('#transfer_base_currency_display').html(
                 '<div class="alert alert-danger" style="margin-top: 5px; padding: 5px;">' +
                 '<i class="fa fa-exclamation-circle"></i> ' +
                 'Failed to get exchange rate. ' +
                 '<a href="' + baseUrl + 'currency" target="_blank" class="alert-link">Add Exchange Rate</a>' +
                 '</div>'
               );
               
               if (typeof toastr !== 'undefined') {
                 toastr["error"]("Failed to get exchange rate. Please add exchange rate first.", "Rate Error");
               } else {
                 alert("Failed to get exchange rate. Please add exchange rate first.");
               }
               $('#transfer_summary').html('');
             });
           } else {
             $('#transfer_base_currency_display').html('');
             $('#transfer_summary').html('');
           }
         }
         
         function updateTransferSummary() {
           var fromAccountId = $('#debit_account_id').val();
           var toAccountId = $('#credit_account_id').val();
           var amount = parseFloat($('#amount').val()) || 0;
           var selectedCurrencyId = $('#transfer_currency_id').val();
           var baseUrl = $('#base_url').val();
           
           if (fromAccountId && toAccountId && amount > 0 && selectedCurrencyId) {
             // Show transfer summary container
             $('#transfer_summary_container').show();
             
             // Get both account details
             $.post(baseUrl + 'accounts/get_transfer_summary', {
               from_account_id: fromAccountId,
               to_account_id: toAccountId,
               amount: amount,
               currency_id: selectedCurrencyId
             }, function(result) {
               if (result.success) {
                 $('#transfer_summary').html(result.summary_html);
               }
             }, 'json');
           } else {
             $('#transfer_summary').html('');
             $('#transfer_summary_container').hide();
           }
         }
         
         // Update To Account info when selected
         function updateToAccountInfo() {
           var toAccountId = $('#credit_account_id').val();
           var baseUrl = $('#base_url').val();
           
           if (toAccountId) {
             $.post(baseUrl + 'accounts/get_account_currency', {account_id: toAccountId}, function(result) {
               if (result.success) {
                 var balanceDisplay = parseFloat(result.balance).toLocaleString('en-US', {
                   minimumFractionDigits: 2,
                   maximumFractionDigits: 2
                 });
                 
                 $('#to_account_info').html(
                   '<div class="alert alert-info" style="margin-top: 10px;">' +
                     '<h5><i class="fa fa-info-circle"></i> To Account Information</h5>' +
                     '<p><strong>Account:</strong> ' + result.currency_name + ' (' + result.currency_code + ')</p>' +
                     '<p><strong>Current Balance:</strong> ' + result.currency_symbol + ' ' + balanceDisplay + '</p>' +
                     '<p><strong>Will Receive:</strong> <span id="will_receive_amount">-</span></p>' +
                     '<p><strong>New Balance:</strong> <span id="new_balance_amount">-</span></p>' +
                   '</div>'
                 );
                 
                 // Update will receive and new balance when amount changes
                 updateToAccountCalculations();
               }
             }, 'json');
           } else {
             $('#to_account_info').html('');
           }
         }
         
         function updateToAccountCalculations() {
           var amount = parseFloat($('#amount').val()) || 0;
           var selectedCurrencyId = $('#transfer_currency_id').val();
           var toAccountId = $('#credit_account_id').val();
           var baseUrl = $('#base_url').val();
           
           if (amount > 0 && selectedCurrencyId && toAccountId) {
             $.post(baseUrl + 'accounts/get_to_account_calculation', {
               to_account_id: toAccountId,
               amount: amount,
               currency_id: selectedCurrencyId
             }, function(result) {
               if (result.success) {
                 $('#will_receive_amount').html(result.will_receive_display);
                 $('#new_balance_amount').html(result.new_balance_display);
               }
             }, 'json');
           } else {
             $('#will_receive_amount').html('-');
             $('#new_balance_amount').html('-');
           }
         }
         
         // Validate that From Account and To Account are different
         function validateAccountSelection() {
           var fromAccount = $('#debit_account_id').val();
           var toAccount = $('#credit_account_id').val();
           
           if (fromAccount && toAccount && fromAccount === toAccount) {
             if (typeof toastr !== 'undefined') {
               toastr["error"]("From Account and To Account cannot be the same!");
             } else {
               alert("From Account and To Account cannot be the same!");
             }
             $('#credit_account_id').val('').trigger('change');
             return false;
           }
           return true;
         }
         
         // Validate transfer amount against available balance
         function validateTransferAmount() {
           var transferAmount = parseFloat($('#amount').val()) || 0;
           var availableBalance = parseFloat($('#account_balance').val()) || 0;
           
           if (transferAmount > availableBalance) {
             if (typeof toastr !== 'undefined') {
               toastr["error"]("Transfer amount cannot exceed available balance!");
             } else {
               alert("Transfer amount cannot exceed available balance!");
             }
             $('#amount').focus();
             return false;
           }
           return true;
         }
         
         // Add change event listeners for account validation
         $(document).ready(function() {
           updateTransferCurrencyInfo();
           
           // Validate account selection when either account changes
           $('#debit_account_id, #credit_account_id').on('change', function() {
             validateAccountSelection();
           });
           
           // Validate transfer amount when amount changes
           $('#amount').on('keyup blur', function() {
             validateTransferAmount();
             updateToAccountCalculations();
           });
           
           // Update currency conversion when currency changes
           $('#transfer_currency_id').on('change', function() {
             updateTransferCurrencyConversion();
             updateToAccountCalculations();
           });
           
           // Add form submission validation
           $('#money_transfer-form').on('submit', function(e) {
             if (!validateAccountSelection() || !validateTransferAmount()) {
               e.preventDefault();
               return false;
             }
           });
         });
      </script>
      <!-- Make sidebar menu hughlighter/selector -->
      <script>$(".<?php echo basename(__FILE__,'.php');?>-active-li").addClass("active");</script>
   </body>
</html>
