<!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)){
               $parent_id =$account_name=$note=$q_id=$store_id='';
               $account_code = get_init_code("accounts");
               $opening_balance=0;
            }
            ?>
         <!-- Content Wrapper. Contains page content -->
         <div class="content-wrapper">
            <!-- Content Header (Page header) -->
            <section class="content-header">
               <h1>
                  <?= $this->lang->line('accounts'); ?>
                  <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="accounts-form" enctype="multipart/form-data">
                           <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">
                              <div class="row">
                                 <div class="col-md-5">
                                    <!-- 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="parent_id" class="col-sm-4 control-label"><?= $this->lang->line('parent_account'); ?> <label class="text-danger">*</label></label>
                                       <div class="col-sm-8">
                                          <select class="form-control select2" id="parent_id" name="parent_id"  style="width: 100%;">
                                          <?php
                                             echo '<option value="">-CREATE ACCOUNT HEAD-</option>'; 
                                             echo get_accounts_select_list($parent_id);
                                             ?>
                                          </select>
                                          <span id="parent_id_msg" style="display:none" class="text-danger"></span>
                                       </div>
                                    </div>
                                    <div class="form-group">
                                       <label for="account_code" class="col-sm-4 control-label"><?= $this->lang->line('account_code'); ?> <label class="text-danger">*</label></label>
                                       <div class="col-sm-8">
                                          <input type="text" class="form-control" id="account_code" name="account_code" placeholder=""  value="<?php print $account_code; ?>" >
                                          <span id="account_code_msg" style="display:none" class="text-danger"></span>
                                       </div>
                                    </div>
                                    <div class="form-group">
                                       <label for="account_name" class="col-sm-4 control-label"><?= $this->lang->line('account_name'); ?> <label class="text-danger">*</label></label>
                                       <div class="col-sm-8">
                                          <?php
                                             // Check if this is a Cash Account (restricted account)
                                             $is_cash_account = (!empty($account_name) && strtolower($account_name) == 'cash account');
                                             $is_restricted = (!empty($delete_bit) && $delete_bit == 1);
                                             
                                             if ($is_cash_account || $is_restricted) {
                                                 // For Cash Account, disable editing
                                                 echo '<div class="input-group">';
                                                 echo '<input type="hidden" id="account_name" name="account_name" value="'.$account_name.'">';
                                                 echo '<input type="text" class="form-control" value="'.$account_name.'" readonly style="background-color: #f5f5f5;">';
                                                 echo '<span class="input-group-addon"><i class="fa fa-lock text-warning" title="Restricted Account - Name cannot be changed"></i></span>';
                                                 echo '</div>';
                                                 echo '<small class="text-warning"><i class="fa fa-info-circle"></i> <strong>Restricted Account:</strong> This is a system account and cannot be modified.</small>';
                                             } else {
                                                 // Regular account - allow editing
                                                 echo '<input type="text" class="form-control" id="account_name" name="account_name" placeholder="" value="'.$account_name.'">';
                                             }
                                          ?>
                                          <span id="account_name_msg" style="display:none" class="text-danger"></span>
                                       </div>
                                    </div>
                                    <div class="form-group">
                                       <label for="currency_id" class="col-sm-4 control-label">Currency <label class="text-danger">*</label></label>
                                       <div class="col-sm-8">
                                          <?php
                                             // Check if this is a Cash Account (restricted account)
                                             $is_cash_account = (!empty($account_name) && strtolower($account_name) == 'cash account');
                                             $is_restricted = (!empty($delete_bit) && $delete_bit == 1);
                                             
                                             if ($is_cash_account || $is_restricted) {
                                                 // For Cash Account, use store currency and disable editing
                                                 $store_currency = get_base_currency();
                                                 $store_currency_id = $store_currency ? $store_currency->id : 1;
                                                 $store_currency_name = $store_currency ? $store_currency->currency_name : 'Base Currency';
                                                 $store_currency_code = $store_currency ? $store_currency->currency_code : 'USD';
                                                 
                                                 echo '<div class="input-group">';
                                                 echo '<input type="hidden" id="currency_id" name="currency_id" value="'.$store_currency_id.'">';
                                                 echo '<input type="text" class="form-control" value="'.$store_currency_name.' ('.$store_currency_code.') - Store Currency" readonly style="background-color: #f5f5f5;">';
                                                 echo '<span class="input-group-addon"><i class="fa fa-lock text-warning" title="Restricted Account - Currency cannot be changed"></i></span>';
                                                 echo '</div>';
                                                 echo '<small class="text-warning"><i class="fa fa-info-circle"></i> <strong>Restricted Account:</strong> Currency is automatically set to store currency and cannot be changed.</small>';
                                             } else {
                                                 // Regular account - allow currency selection
                                                 echo '<select class="form-control select2" id="currency_id" name="currency_id" style="width: 100%;" onchange="updateCurrencyInfo()">';
                                                 $base_currency = get_base_currency();
                                                 $selected_currency_id = !empty($currency_id) ? $currency_id : $base_currency->id;
                                                 
                                                 // Get all currencies
                                                 $currencies = get_currency_list();
                                                 foreach ($currencies as $currency) {
                                                     $selected = ($currency->id == $selected_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>';
                                                 }
                                                 echo '</select>';
                                             }
                                          ?>
                                          <span id="currency_id_msg" style="display:none" class="text-danger"></span>
                                          <div class="alert alert-info" style="margin-top: 5px;">
                                             <i class="fa fa-info-circle"></i> <strong>Multi-Currency Account:</strong> 
                                             <ul style="margin: 5px 0 0 0; padding-left: 20px;">
                                                <li>Account will be maintained in the selected currency</li>
                                                <li>Opening balance will be in the selected currency</li>
                                                <li>All transactions will be automatically converted to base currency for reporting</li>
                                                <li>Account balance will be displayed in the account's currency</li>
                                             </ul>
                                          </div>
                                       </div>
                                    </div>
                                    <div class="form-group <?= (!empty($q_id)) ? 'hide' : ''?>">
                                       <label for="opening_balance" class="col-sm-4 control-label"><?= $this->lang->line('opening_balance'); ?> <label class="text-danger">*</label></label>
                                       <div class="col-sm-8">
                                          <div class="input-group">
                                             <span class="input-group-addon" id="currency_symbol"><?= $base_currency->symbol; ?></span>
                                             <input type="text" class="form-control only_currency" id="opening_balance" name="opening_balance" placeholder="" value="<?php print store_number_format($opening_balance,0); ?>" onkeyup="updateCurrencyConversion()">
                                             <span class="input-group-addon" id="currency_loading" style="display: none;">
                                                <i class="fa fa-spinner fa-spin"></i>
                                             </span>
                                          </div>
                                          <span id="opening_balance_msg" style="display:none" class="text-danger"></span>
                                          <div id="base_currency_display" class="text-muted" style="margin-top: 5px; font-size: 12px;">
                                             <!-- Base currency conversion will be shown here -->
                                          </div>
                                          <div id="account_examples" class="text-muted" style="margin-top: 5px; font-size: 11px;">
                                             <!-- Account examples will be shown here -->
                                          </div>
                                          <div id="existing_accounts" class="text-info" style="margin-top: 5px; font-size: 11px;">
                                             <!-- Existing accounts in this currency will be shown here -->
                                          </div>
                                       </div>
                                    </div>
                                    <!-- ########### -->
                                 </div>
                                 <div class="col-md-5">
                                    <div class="form-group">
                                       <label for="note" class="col-sm-4 control-label"><?= $this->lang->line('note'); ?></label>
                                       <div class="col-sm-8">
                                          <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 class="form-group">
                                       <label for="supporting_documents" class="col-sm-4 control-label">Supporting Documents</label>
                                       <div class="col-sm-8">
                                          <input type="file" class="form-control" id="supporting_documents" name="supporting_documents[]" multiple accept=".pdf,.doc,.docx,.jpg,.jpeg,.png,.gif">
                                          <span id="supporting_documents_msg" style="display:none" class="text-danger"></span>
                                          <small class="text-muted">
                                             <i class="fa fa-info-circle"></i> 
                                             Supported formats: PDF, DOC, DOCX, JPG, PNG, GIF (Max 5MB each)
                                          </small>
                                          <div id="file_preview" style="margin-top: 10px;">
                                             <!-- File previews will be shown here -->
                                          </div>
                                       </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/accounts.js"></script>
      <script type="text/javascript">
         <?php if(isset($q_id)){ ?>
           $("#store_id").attr('readonly',true);
         <?php }?>
         
         function updateCurrencyInfo() {
            var selectedCurrencyId = $('#currency_id').val();
            var baseUrl = $('#base_url').val();
            
            if (!selectedCurrencyId) {
                return;
            }
            
            // Show loading indicator
            $('#currency_loading').show();
            
            // Update currency symbol
            $.post(baseUrl + 'currency/get_currency_info', {currency_id: selectedCurrencyId}, function(result) {
                $('#currency_loading').hide();
                
                if (result.success) {
                    $('#currency_symbol').text(result.symbol);
                    updateCurrencyConversion();
                    showAccountExamples(selectedCurrencyId, result.currency_code);
                } else {
                    console.error('Currency info error:', result.message);
                    // Fallback to base currency symbol
                    $('#currency_symbol').text('<?= get_base_currency()->symbol; ?>');
                }
            }, 'json').fail(function(xhr, status, error) {
                $('#currency_loading').hide();
                console.error('AJAX error:', status, error);
                // Fallback to base currency symbol
                $('#currency_symbol').text('<?= get_base_currency()->symbol; ?>');
            });
         }
         
         function showAccountExamples(currencyId, currencyCode) {
            var baseCurrencyId = '<?= get_base_currency()->id; ?>';
            var examples = '';
            
            if (currencyId == baseCurrencyId) {
                examples = '<i class="fa fa-lightbulb-o"></i> <strong>Examples:</strong> Cash Account (USD), Bank Account (USD), Petty Cash (USD)';
            } else {
                examples = '<i class="fa fa-lightbulb-o"></i> <strong>Examples:</strong> Cash Account (' + currencyCode + '), Bank Account (' + currencyCode + '), Petty Cash (' + currencyCode + ')';
            }
            
            $('#account_examples').html(examples);
            loadExistingAccounts(currencyId);
         }
         
         function loadExistingAccounts(currencyId) {
            var baseUrl = $('#base_url').val();
            
            $.post(baseUrl + 'accounts/get_accounts_by_currency', {currency_id: currencyId}, function(result) {
                if (result.success && result.accounts.length > 0) {
                    var accountsList = result.accounts.map(function(account) {
                        return account.account_name + ' (' + account.account_code + ')';
                    }).join(', ');
                    
                    $('#existing_accounts').html(
                        '<i class="fa fa-list"></i> <strong>Existing accounts in this currency:</strong> ' + accountsList
                    );
                } else {
                    $('#existing_accounts').html(
                        '<i class="fa fa-info-circle"></i> <strong>No existing accounts found in this currency.</strong>'
                    );
                }
            }, 'json').fail(function() {
                $('#existing_accounts').html('');
            });
         }
         
         function updateCurrencyConversion() {
            var amount = parseFloat($('#opening_balance').val()) || 0;
            var selectedCurrencyId = $('#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; ?>';
                        $('#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) + ')'
                        );
                    } else {
                        console.error('Exchange rate error:', result.message);
                        $('#base_currency_display').html('<span class="text-warning">Unable to get exchange rate</span>');
                    }
                }, 'json').fail(function(xhr, status, error) {
                    console.error('Exchange rate AJAX error:', status, error);
                    $('#base_currency_display').html('<span class="text-warning">Unable to get exchange rate</span>');
                });
            } else {
                $('#base_currency_display').html('');
            }
         }
         
         // File preview functionality
         function previewFiles() {
            var files = $('#supporting_documents')[0].files;
            var preview = $('#file_preview');
            preview.empty();
            
            if (files.length > 0) {
               preview.append('<h6><i class="fa fa-paperclip"></i> Selected Files:</h6>');
               
               for (var i = 0; i < files.length; i++) {
                  var file = files[i];
                  var fileSize = (file.size / 1024 / 1024).toFixed(2);
                  var fileIcon = getFileIcon(file.type);
                  
                  preview.append(
                     '<div class="file-preview-item" style="margin: 5px 0; padding: 5px; border: 1px solid #ddd; border-radius: 3px; background: #f9f9f9;">' +
                        '<i class="fa ' + fileIcon + '"></i> ' +
                        '<span>' + file.name + '</span> ' +
                        '<span class="text-muted">(' + fileSize + ' MB)</span>' +
                     '</div>'
                  );
               }
            }
         }
         
         function getFileIcon(fileType) {
            if (fileType.includes('pdf')) return 'fa-file-pdf-o text-danger';
            if (fileType.includes('word') || fileType.includes('document')) return 'fa-file-word-o text-primary';
            if (fileType.includes('image')) return 'fa-file-image-o text-success';
            return 'fa-file-o text-muted';
         }
         
         // Initialize currency info on page load
         $(document).ready(function() {
            console.log('Initializing currency info...');
            updateCurrencyInfo();
            
            // Add change event listener to currency dropdown
            $('#currency_id').on('change', function() {
                console.log('Currency changed to:', $(this).val());
                updateCurrencyInfo();
            });
            
            // File preview on change
            $('#supporting_documents').on('change', function() {
               previewFiles();
            });
         });
      </script>
      <!-- Make sidebar menu hughlighter/selector -->
      <script>$(".<?php echo basename(__FILE__,'.php');?>-active-li").addClass("active");</script>
   </body>
</html>
