<!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='';
$amount=0;
$deposit_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>
            <?= $this->lang->line('deposit'); ?>
            <small>Add/Update Deposits
            </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; ?>money_deposit">
                <?= $this->lang->line('deposit_list'); ?>
              </a>
            </li>
            <li class="active">
              <?= $this->lang->line('new_deposit'); ?>
            </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">
                    <i class="fa fa-plus-circle"></i> Deposit Transaction
                  </h3>
                  <div class="box-tools pull-right">
                    <small class="text-muted">Add money to an account</small>
                  </div>
                </div>
                
                <!-- Simple Help Section -->
                <div class="box-body" style="background: #f8f9fa; border-bottom: 1px solid #ddd; margin-bottom: 0; padding: 15px;">
                  <div class="alert alert-info" style="margin: 0; padding: 10px 15px;">
                    <strong><i class="fa fa-info-circle"></i> Deposit:</strong> Money coming INTO your business. 
                    Select the account where money will be deposited. Currency will be set automatically based on the selected account.
                  </div>
                </div>
                <!-- /.box-header -->
                <!-- form start -->
                <form class="form-horizontal" id="money_deposit-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(); ?>">
                  <div class="box-body">
                    <div class="form-group">
                      <label for="deposit_date" class="col-sm-2 control-label">
                        <?= $this->lang->line('deposit_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="deposit_date" name="deposit_date" readonly value="<?= $deposit_date;?>">
                        </div>
                        <span id="deposit_date_msg" style="display:none" class="text-danger"></span>
                      </div>
                      <label for="reference_no" class="col-sm-2 control-label">
                        <?= $this->lang->line('reference_no'); ?>
                      </label>
                      <div class="col-sm-4">
                        <div class="input-group">
                          <input type="text" class="form-control" id="reference_no" name="reference_no" placeholder="Reference number" value="<?php print $reference_no; ?>">
                          <span class="input-group-btn">
                            <button type="button" class="btn btn-default" id="generate_ref_btn" title="Generate Reference Number">
                              <i class="fa fa-refresh"></i>
                            </button>
                          </span>
                        </div>
                        <small class="text-muted">Leave empty for auto-generation</small>
                        <span id="reference_no_msg" style="display:none" class="text-danger"></span>
                      </div>
                    </div>

                    <div class="form-group">
                      <label for="credit_account_id" class="col-sm-2 control-label">
                        Deposit To Account <label class="text-danger">*</label>
                      </label>
                      <div class="col-sm-4">
                        <select class="form-control select2" id="credit_account_id" name="credit_account_id" style="width: 100%;">
                          <?php
echo '<option value="">Select Account</option>'; 
echo get_accounts_select_list($credit_account_id);
?>
                        </select>
                        <div id="account_currency_info" class="alert alert-info" style="margin-top: 8px; padding: 8px 12px; font-size: 13px; display: none; border-radius: 4px;">
                          <!-- Account currency info will be shown here -->
                        </div>
                        <span id="credit_account_id_msg" style="display:none" class="text-danger"></span>
                      </div>
                      <label for="debit_account_id" class="col-sm-2 control-label">
                        Source Account
                      </label>
                      <div class="col-sm-4">
                        <select class="form-control select2" id="debit_account_id" name="debit_account_id" style="width: 100%;">
                          <?php
echo '<option value="">Select Source Account (Optional)</option>'; 
echo get_accounts_select_list($debit_account_id);
?>
                        </select>
                        <span id="debit_account_id_msg" style="display:none" class="text-danger"></span>
                      </div>
                    </div>

                    <div class="form-group">
                      <label for="deposit_currency_id" class="col-sm-2 control-label">
                        Currency <label class="text-danger">*</label>
                      </label>
                      <div class="col-sm-4">
                        <select class="form-control select2" id="deposit_currency_id" name="deposit_currency_id" style="width: 100%;" onchange="updateDepositCurrencyInfo()" disabled>
                          <option value="">Select Account First</option>
                        </select>
                        <span id="deposit_currency_id_msg" style="display:none" class="text-danger"></span>
                        <small class="text-muted">Currency will be set automatically based on selected account</small>
                      </div>
                      <label for="amount" class="col-sm-2 control-label">
                        Amount <label class="text-danger">*</label>
                      </label>
                      <div class="col-sm-4">
                        <div class="input-group">
                          <span class="input-group-addon" id="deposit_currency_symbol">$</span>
                          <input type="text" class="form-control only_currency" id="amount" name="amount" placeholder="0.00" value="<?php print store_number_format($amount,0); ?>" onkeyup="updateDepositCurrencyConversion()">
                        </div>
                        <span id="amount_msg" style="display:none" class="text-danger"></span>
                        <div id="deposit_base_currency_display" class="text-muted" style="margin-top: 5px; font-size: 12px;">
                          <!-- Base currency conversion will be shown here -->
                        </div>
                      </div>
                    </div>

                    <div class="form-group">
                      <label for="note" class="col-sm-2 control-label">
                        <?= $this->lang->line('note'); ?> 
                        <label class="text-danger">*</label>
                      </label>
                      <div class="col-sm-10">
                        <textarea type="text" class="form-control" id="note" name="note" placeholder="Enter deposit description or notes" rows="3"><?php print $note; ?></textarea>
                        <span id="note_msg" style="display:none" class="text-danger"></span>
                      </div>
                    </div>
                  </div>
                  <!-- /.box-body -->
                  <div class="box-footer">
                    <div class="col-sm-8 col-sm-offset-2 text-center">
                      <?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_deposit.js">
    </script>
    
    <style>
      /* Simple styles for deposit form */
      .form-control:focus {
        border-color: #3c8dbc;
        box-shadow: 0 0 0 0.2rem rgba(60, 141, 188, 0.25);
      }
      
      .text-danger {
        font-weight: bold;
      }
    </style>
    
    <script type="text/javascript">
      <?php if(isset($q_id)){
        ?>
          $("#store_id").attr('readonly',true);
        <?php }
      ?>
      
      function updateDepositCurrencyInfo() {
        var selectedCurrencyId = $('#deposit_currency_id').val();
        var baseUrl = $('#base_url').val();
        
        if (selectedCurrencyId) {
          // Simple fallback - extract symbol from option text
          var selectedText = $('#deposit_currency_id option:selected').text();
          var symbol = selectedText.match(/\(([^)]+)\)/);
          if (symbol && symbol[1]) {
            $('#deposit_currency_symbol').text(symbol[1]);
          }
          updateDepositCurrencyConversion();
        }
      }
      
      function updateDepositCurrencyConversion() {
        var amount = parseFloat($('#amount').val()) || 0;
        var selectedCurrencyId = $('#deposit_currency_id').val();
        
        if (amount > 0 && selectedCurrencyId) {
          // Simple display without AJAX calls to prevent hanging
          $('#deposit_base_currency_display').html(
            '<small class="text-muted">Amount: ' + amount + ' (Currency conversion not available)</small>'
          );
        } else {
          $('#deposit_base_currency_display').html('');
        }
      }
      
      // Initialize currency info on page load
      $(document).ready(function() {
        updateDepositCurrencyInfo();
        
        // Handle account selection to set currency
        $('#credit_account_id').on('change', function() {
          var accountId = $(this).val();
          console.log('Account selected:', accountId);
          
          if (accountId) {
            // Get account currency via AJAX
            $.post('<?php echo base_url(); ?>accounts/get_account_currency', {
              account_id: accountId
            }, function(result) {
              console.log('AJAX response:', result);
              
              if (result.success) {
                // Set the currency dropdown
                $('#deposit_currency_id').html('<option value="' + result.currency_id + '">' + result.currency_name + ' (' + result.currency_code + ')</option>');
                $('#deposit_currency_id').val(result.currency_id);
                $('#deposit_currency_id').prop('disabled', false);
                
                // Update currency symbol
                $('#deposit_currency_symbol').text(result.currency_symbol);
                
                // Show account currency info
                $('#account_currency_info').html(
                  '<i class="fa fa-info-circle"></i> <strong>Account Currency:</strong> ' + 
                  result.currency_name + ' (' + result.currency_code + ')'
                ).show();
                
                console.log('Currency info displayed');
                
                // Trigger currency update
                updateDepositCurrencyInfo();
              } else {
                console.log('AJAX failed:', result.message);
                // Fallback: enable currency selection with all currencies
                loadAllCurrencies();
              }
            }, 'json').fail(function(xhr, status, error) {
              console.log('AJAX error:', status, error);
              // Fallback: enable currency selection with all currencies
              loadAllCurrencies();
            });
          } else {
            // Reset currency dropdown
            $('#deposit_currency_id').html('<option value="">Select Account First</option>');
            $('#deposit_currency_id').prop('disabled', true);
            $('#deposit_currency_symbol').text('$');
            $('#account_currency_info').hide();
            console.log('Account deselected, currency reset');
          }
        });
        
        // If editing and an account is already selected, load its currency info
        var preselectedAccountId = $('#credit_account_id').val();
        if (preselectedAccountId) {
          $('#credit_account_id').trigger('change');
        }
        
        // Load all currencies as fallback
        function loadAllCurrencies() {
          var baseUrl = $('#base_url').val();
          $.post(baseUrl + 'currency/get_currency_list', {}, function(result) {
            if (result.success) {
              var options = '<option value="">Select Currency</option>';
              $.each(result.currencies, function(index, currency) {
                var selected = (currency.id == '<?= get_base_currency()->id; ?>') ? 'selected' : '';
                var baseIndicator = (currency.id == '<?= get_base_currency()->id; ?>') ? ' - Base Currency' : '';
                options += '<option value="' + currency.id + '" ' + selected + '>' + currency.currency_name + ' (' + currency.currency_code + ')' + baseIndicator + '</option>';
              });
              $('#deposit_currency_id').html(options);
              $('#deposit_currency_id').prop('disabled', false);
            }
          }, 'json');
        }
        
        // Generate reference number
        function generateReferenceNumber() {
          var today = new Date();
          var dateStr = today.getFullYear().toString() + 
                       (today.getMonth() + 1).toString().padStart(2, '0') + 
                       today.getDate().toString().padStart(2, '0');
          var timeStr = today.getHours().toString().padStart(2, '0') + 
                       today.getMinutes().toString().padStart(2, '0') + 
                       today.getSeconds().toString().padStart(2, '0');
          var refNumber = 'DEP' + dateStr + timeStr;
          $('#reference_no').val(refNumber);
        }
        
        // Handle reference number generation
        $('#generate_ref_btn').on('click', function() {
          generateReferenceNumber();
        });
        
        // Auto-generate reference if empty before form submission
        $('#save, #update').on('click', function() {
          if (!$('#reference_no').val().trim()) {
            generateReferenceNumber();
          }
        });
      });
    </script>
    <!-- Make sidebar menu hughlighter/selector -->
    <script>$(".<?php echo basename(__FILE__,'.php');?>-active-li").addClass("active");
    </script>
  </body>
</html>
