<?php 
$CI =& get_instance();
$css= ($CI->session->userdata('language')=='Arabic' || $CI->session->userdata('language')=='Urdu') ? 'right' : 'left';
?>
<!DOCTYPE html>
<html>
<head>
<!-- TABLES CSS CODE -->
<?php include"comman/code_css.php"; ?>
<style>
  .ledger-summary-card {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 10px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
  }
  
  .ledger-summary-card h4 {
    margin-top: 0;
    font-weight: 600;
  }
  
  .summary-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    padding: 8px 0;
    border-bottom: 1px solid rgba(255,255,255,0.2);
  }
  
  .summary-item:last-child {
    border-bottom: none;
    margin-bottom: 0;
  }
  
  .summary-value {
    font-weight: bold;
    font-size: 16px;
  }
  
  .balance-positive {
    color: #e74c3c;
  }
  
  .balance-negative {
    color: #27ae60;
  }
  
  .transaction-row-debit {
    background-color: #ffebee !important;
  }
  
  .transaction-row-credit {
    background-color: #e8f5e8 !important;
  }
  
  .customer-summary-modal .modal-dialog {
    width: 800px;
  }
  
  .customer-info-card {
    background: #f8f9fa;
    padding: 15px;
    border-radius: 8px;
    margin-bottom: 15px;
  }
  
  .stat-card {
    text-align: center;
    padding: 15px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  }
  
  .stat-number {
    font-size: 24px;
    font-weight: bold;
    color: #2c3e50;
  }
  
  .stat-label {
    font-size: 12px;
    color: #7f8c8d;
    text-transform: uppercase;
  }
</style>
</head>

<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">

  <?php include"sidebar.php"; ?>

  <!-- Content Wrapper. Contains page content -->
  <div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <section class="content-header">
      <h1>
        <?= $this->lang->line('transaction_ledger_report'); ?>
        <small><?= $this->lang->line('control_panel'); ?></small>
      </h1>
      <ol class="breadcrumb">
        <li><a href="<?php echo $base_url; ?>dashboard"><i class="fa fa-dashboard"></i> <?= $this->lang->line('home'); ?></a></li>
        <li><a href="<?php echo $base_url; ?>reports"><?= $this->lang->line('reports'); ?></a></li>
        <li class="active"><?= $this->lang->line('transaction_ledger_report'); ?></li>
      </ol>
    </section>

    <!-- Main content -->
    <section class="content">
      <div class="row">
        <div class="col-md-12">
          <!-- Filter Section -->
          <div class="box box-primary">
            <div class="box-header with-border">
              <h3 class="box-title"><i class="fa fa-filter"></i> <?= $this->lang->line('filters'); ?></h3>
            </div>
            <div class="box-body">
              <div class="row">
                
                <!-- Store Selection -->
                <?php if(store_module() && is_admin()): ?>
                <div class="col-md-3">
                  <div class="form-group">
                    <label><?= $this->lang->line('store_name'); ?></label>
                    <select class="form-control select2" id="store_id" name="store_id" style="width: 100%;">
                      <?= get_stores_select_list(); ?>
                    </select>
                  </div>
                </div>
                <?php else: ?>
                  <input type="hidden" id="store_id" value="<?= get_current_store_id(); ?>">
                <?php endif; ?>
                
                <!-- Customer Selection -->
                <div class="col-md-3">
                  <div class="form-group">
                    <label><?= $this->lang->line('customer_name'); ?></label>
                    <select class="form-control select2" id="customer_id" name="customer_id" style="width: 100%;">
                      <option value="">-All Customers-</option>
                    </select>
                  </div>
                </div>
                
                <!-- From Date -->
                <div class="col-md-2">
                  <div class="form-group">
                    <label><?= $this->lang->line('from_date'); ?></label>
                    <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="from_date" name="from_date" readonly value="<?= date('01-m-Y'); ?>">
                    </div>
                  </div>
                </div>
                
                <!-- To Date -->
                <div class="col-md-2">
                  <div class="form-group">
                    <label><?= $this->lang->line('to_date'); ?></label>
                    <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="to_date" name="to_date" readonly value="<?= date('d-m-Y'); ?>">
                    </div>
                  </div>
                </div>
                
                <!-- Action Buttons -->
                <div class="col-md-2">
                  <div class="form-group">
                    <label>&nbsp;</label>
                    <div>
                      <button type="button" class="btn btn-primary btn-block" id="btn_show">
                        <i class="fa fa-search"></i> <?= $this->lang->line('show'); ?>
                      </button>
                    </div>
                  </div>
                </div>
                
              </div>
              
              <!-- Additional Action Buttons -->
              <div class="row">
                <div class="col-md-12">
                  <div class="btn-group pull-right" style="margin-top: 10px;">
                    <button type="button" class="btn btn-success" id="btn_export" disabled>
                      <i class="fa fa-download"></i> <?= $this->lang->line('export'); ?>
                    </button>
                    <button type="button" class="btn btn-info" id="btn_customer_summary" disabled>
                      <i class="fa fa-user"></i> Customer Summary
                    </button>
                    <button type="button" class="btn btn-warning" id="btn_print" disabled>
                      <i class="fa fa-print"></i> <?= $this->lang->line('print'); ?>
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- Summary Cards -->
          <div id="summary_section" style="display: none;">
            <div class="row">
              <div class="col-md-12">
                <div class="ledger-summary-card">
                  <h4><i class="fa fa-chart-line"></i> Transaction Summary</h4>
                  <div class="row">
                    <div class="col-md-3">
                      <div class="summary-item">
                        <span>Opening Balance:</span>
                        <span class="summary-value" id="summary_opening_balance">0.00</span>
                      </div>
                    </div>
                    <div class="col-md-3">
                      <div class="summary-item">
                        <span>Total Debits:</span>
                        <span class="summary-value text-danger" id="summary_total_debits">0.00</span>
                      </div>
                    </div>
                    <div class="col-md-3">
                      <div class="summary-item">
                        <span>Total Credits:</span>
                        <span class="summary-value text-success" id="summary_total_credits">0.00</span>
                      </div>
                    </div>
                    <div class="col-md-3">
                      <div class="summary-item">
                        <span>Closing Balance:</span>
                        <span class="summary-value" id="summary_closing_balance">0.00</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- Transaction Table -->
          <div class="box box-success">
            <div class="box-header with-border">
              <h3 class="box-title"><i class="fa fa-list"></i> Transaction Ledger</h3>
              <div class="box-tools pull-right">
                <span class="label label-success" id="record_count">0 transactions</span>
              </div>
            </div>
            <div class="box-body">
              <div class="table-responsive">
                <table class="table table-bordered table-striped table-hover" id="ledger_table">
                  <thead class="bg-gray">
                    <tr>
                      <th width="10%"><?= $this->lang->line('date'); ?></th>
                      <th width="15%">Customer</th>
                      <th width="12%">Type</th>
                      <th width="15%">Reference</th>
                      <th width="25%">Description</th>
                      <th width="10%" class="text-right">Debit</th>
                      <th width="10%" class="text-right">Credit</th>
                      <th width="13%" class="text-right">Balance</th>
                    </tr>
                  </thead>
                  <tbody id="ledger_tbody">
                    <tr>
                      <td colspan="8" class="text-center">
                        <i class="fa fa-info-circle"></i> Please select filters and click "Show" to load transactions
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  </div>

  <?php include"footer.php"; ?>
</div>

<!-- Customer Summary Modal -->
<div class="modal fade customer-summary-modal" id="customer_summary_modal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title"><i class="fa fa-user"></i> Customer Summary</h4>
      </div>
      <div class="modal-body">
        <div id="customer_summary_content">
          <div class="text-center">
            <i class="fa fa-spinner fa-spin"></i> Loading customer summary...
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<!-- SOUND CODE -->
<?php include"comman/code_js_sound.php"; ?>

<!-- TABLES CODE -->
<?php include"comman/code_js.php"; ?>

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

<script type="text/javascript">
$(document).ready(function() {
  
  // Initialize date pickers
  $('.datepicker').datepicker({
    format: 'dd-mm-yyyy',
    autoclose: true,
    todayHighlight: true
  });

  // Load customers on page load
  setTimeout(function() {
    autoLoadFirstCustomer();
  }, 500);

  // Pre-select customer if provided from URL parameter
  <?php if(!empty($pre_selected_customer_id)): ?>
  setTimeout(function() {
    $('#customer_id').val('<?php echo $pre_selected_customer_id; ?>').trigger('change');
    // Auto-load transaction data after customer is selected
    setTimeout(function() {
      showTransactionLedger();
    }, 1500);
  }, 1000);
  <?php endif; ?>

  // Show report button click
  $('#btn_show').click(function() {
    showTransactionLedger();
  });

  // Export button click
  $('#btn_export').click(function() {
    exportLedger();
  });

  // Customer summary button click
  $('#btn_customer_summary').click(function() {
    showCustomerSummary();
  });

  // Print button click
  $('#btn_print').click(function() {
    printLedger();
  });

  // Store change event
  $('#store_id').change(function() {
    autoLoadFirstCustomer();
  });

});

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

// Dummy function for customer AJAX compatibility
function set_the_previous_due(previous_due, tot_advance) {
  // This function is called by customer_select_ajax.js
  // For transaction ledger, we don't need to set previous due in the UI
  // but we need this function to exist to prevent errors
}

function showTransactionLedger() {
  var from_date = $('#from_date').val();
  var to_date = $('#to_date').val();
  var customer_id = $('#customer_id').val();
  var store_id = $('#store_id').val();

  if(from_date == '' || to_date == '') {
    toastr.warning('Please select both from and to dates');
    return;
  }

  // Show loading
  $('#ledger_tbody').html('<tr><td colspan="8" class="text-center"><i class="fa fa-spinner fa-spin"></i> Loading transactions...</td></tr>');
  
  // Disable buttons
  $('#btn_export, #btn_customer_summary, #btn_print').prop('disabled', true);

  $.ajax({
    url: base_url + 'transaction_ledger/show_transaction_ledger',
    type: 'POST',
    dataType: 'json',
    data: {
      from_date: from_date,
      to_date: to_date,
      customer_id: customer_id,
      store_id: store_id,
      '<?php echo $this->security->get_csrf_token_name(); ?>': '<?php echo $this->security->get_csrf_hash(); ?>'
    },
    success: function(response) {
      displayLedgerData(response);
    },
    error: function() {
      toastr.error('Error loading transaction data');
      $('#ledger_tbody').html('<tr><td colspan="8" class="text-center text-danger"><i class="fa fa-exclamation-triangle"></i> Error loading data</td></tr>');
    }
  });
}

function displayLedgerData(data) {
  var tbody = '';
  
  if(data.transactions && data.transactions.length > 0) {
    
    // Show opening balance row if customer is selected
    var customer_id = $('#customer_id').val();
    if(customer_id != '') {
      tbody += '<tr class="bg-info">';
      tbody += '<td>' + $('#from_date').val() + '</td>';
      tbody += '<td>' + $('#customer_id option:selected').text() + '</td>';
      tbody += '<td><strong>OPENING BALANCE</strong></td>';
      tbody += '<td>-</td>';
      tbody += '<td><strong>Balance brought forward</strong></td>';
      tbody += '<td class="text-right">-</td>';
      tbody += '<td class="text-right">-</td>';
      tbody += '<td class="text-right"><strong>' + store_number_format(data.opening_balance) + '</strong></td>';
      tbody += '</tr>';
    }
    
    // Add transaction rows
    $.each(data.transactions, function(index, transaction) {
      var rowClass = '';
      if(transaction.debit_raw > 0) {
        rowClass = 'transaction-row-debit';
      } else if(transaction.credit_raw > 0) {
        rowClass = 'transaction-row-credit';
      }
      
      tbody += '<tr class="' + rowClass + '">';
      tbody += '<td>' + transaction.date + '</td>';
      tbody += '<td>' + transaction.customer_name + '</td>';
      tbody += '<td><span class="label label-' + getTransactionTypeColor(transaction.transaction_type) + '">' + transaction.transaction_type + '</span></td>';
      tbody += '<td>' + transaction.reference + '</td>';
      tbody += '<td>' + transaction.description + '</td>';
      tbody += '<td class="text-right text-danger">' + transaction.debit + '</td>';
      tbody += '<td class="text-right text-success">' + transaction.credit + '</td>';
      tbody += '<td class="text-right"><strong>' + transaction.running_balance + '</strong></td>';
      tbody += '</tr>';
    });
    
    // Show closing balance row
    tbody += '<tr class="bg-warning">';
    tbody += '<td>' + $('#to_date').val() + '</td>';
    tbody += '<td>' + (customer_id != '' ? $('#customer_id option:selected').text() : 'All Customers') + '</td>';
    tbody += '<td><strong>CLOSING BALANCE</strong></td>';
    tbody += '<td>-</td>';
    tbody += '<td><strong>Balance carried forward</strong></td>';
    tbody += '<td class="text-right">-</td>';
    tbody += '<td class="text-right">-</td>';
    tbody += '<td class="text-right"><strong>' + store_number_format(data.closing_balance) + '</strong></td>';
    tbody += '</tr>';
    
    // Update summary
    $('#summary_opening_balance').text(store_number_format(data.opening_balance));
    $('#summary_total_debits').text(store_number_format(data.total_debit));
    $('#summary_total_credits').text(store_number_format(data.total_credit));
    $('#summary_closing_balance').text(store_number_format(data.closing_balance));
    
    // Apply balance color
    var closing_balance_elem = $('#summary_closing_balance');
    closing_balance_elem.removeClass('balance-positive balance-negative');
    if(data.closing_balance > 0) {
      closing_balance_elem.addClass('balance-positive');
    } else if(data.closing_balance < 0) {
      closing_balance_elem.addClass('balance-negative');
    }
    
    $('#summary_section').show();
    $('#record_count').text(data.transaction_count + ' transactions');
    
    // Enable buttons
    $('#btn_export, #btn_print').prop('disabled', false);
    
    if(customer_id != '') {
      $('#btn_customer_summary').prop('disabled', false);
    }
    
  } else {
    tbody = '<tr><td colspan="8" class="text-center text-muted"><i class="fa fa-info-circle"></i> No transactions found for the selected criteria</td></tr>';
    $('#summary_section').hide();
    $('#record_count').text('0 transactions');
  }
  
  $('#ledger_tbody').html(tbody);
}

function getTransactionTypeColor(type) {
  switch(type) {
    case 'SALE': return 'danger';
    case 'PAYMENT': return 'success';
    case 'RETURN': return 'warning';
    default: return 'primary';
  }
}

function exportLedger() {
  var from_date = $('#from_date').val();
  var to_date = $('#to_date').val();
  var customer_id = $('#customer_id').val();
  var store_id = $('#store_id').val();
  
  var url = base_url + 'transaction_ledger/export_transaction_ledger?';
  url += 'from_date=' + encodeURIComponent(from_date);
  url += '&to_date=' + encodeURIComponent(to_date);
  url += '&customer_id=' + encodeURIComponent(customer_id);
  url += '&store_id=' + encodeURIComponent(store_id);
  
  window.open(url, '_blank');
}

function showCustomerSummary() {
  var customer_id = $('#customer_id').val();
  var store_id = $('#store_id').val();
  
  if(customer_id == '') {
    toastr.warning('Please select a customer first');
    return;
  }
  
  $('#customer_summary_content').html('<div class="text-center"><i class="fa fa-spinner fa-spin"></i> Loading customer summary...</div>');
  $('#customer_summary_modal').modal('show');
  
  $.ajax({
    url: base_url + 'transaction_ledger/customer_transaction_summary',
    type: 'POST',
    dataType: 'json',
    data: {
      customer_id: customer_id,
      store_id: store_id,
      '<?php echo $this->security->get_csrf_token_name(); ?>': '<?php echo $this->security->get_csrf_hash(); ?>'
    },
    success: function(response) {
      if(response.error) {
        $('#customer_summary_content').html('<div class="alert alert-danger">' + response.error + '</div>');
        return;
      }
      
      var content = '';
      
      // Customer Info
      content += '<div class="customer-info-card">';
      content += '<h4><i class="fa fa-user"></i> ' + response.customer.name + '</h4>';
      content += '<div class="row">';
      content += '<div class="col-md-6"><strong>Mobile:</strong> ' + (response.customer.mobile || 'Not provided') + '</div>';
      content += '<div class="col-md-6"><strong>Last Transaction:</strong> ' + response.customer.last_transaction_date + '</div>';
      content += '</div>';
      content += '</div>';
      
      // Stats Cards
      content += '<div class="row">';
      content += '<div class="col-md-3"><div class="stat-card"><div class="stat-number">' + response.summary.total_sales.count + '</div><div class="stat-label">Total Sales</div></div></div>';
      content += '<div class="col-md-3"><div class="stat-card"><div class="stat-number">' + response.summary.total_payments.count + '</div><div class="stat-label">Total Payments</div></div></div>';
      content += '<div class="col-md-3"><div class="stat-card"><div class="stat-number">' + response.summary.total_returns.count + '</div><div class="stat-label">Total Returns</div></div></div>';
      content += '<div class="col-md-3"><div class="stat-card"><div class="stat-number">' + response.customer.current_balance + '</div><div class="stat-label">Current Balance</div></div></div>';
      content += '</div>';
      
      // Balance Details
      content += '<div class="row" style="margin-top: 15px;">';
      content += '<div class="col-md-6">';
      content += '<h5>Account Balance Details</h5>';
      content += '<table class="table table-bordered table-sm">';
      content += '<tr><td>Opening Balance:</td><td class="text-right">' + response.customer.opening_balance + '</td></tr>';
      content += '<tr><td>Current Balance:</td><td class="text-right">' + response.customer.current_balance + '</td></tr>';
      content += '<tr><td>Advance Balance:</td><td class="text-right">' + response.customer.advance_balance + '</td></tr>';
      content += '<tr><td>Credit Limit:</td><td class="text-right">' + response.customer.credit_limit + '</td></tr>';
      content += '</table>';
      content += '</div>';
      content += '<div class="col-md-6">';
      content += '<h5>Transaction Totals</h5>';
      content += '<table class="table table-bordered table-sm">';
      content += '<tr><td>Total Sales Amount:</td><td class="text-right">' + response.summary.total_sales.amount + '</td></tr>';
      content += '<tr><td>Total Payments Amount:</td><td class="text-right">' + response.summary.total_payments.amount + '</td></tr>';
      content += '<tr><td>Total Returns Amount:</td><td class="text-right">' + response.summary.total_returns.amount + '</td></tr>';
      content += '</table>';
      content += '</div>';
      content += '</div>';
      
      // Recent Transactions
      if(response.recent_transactions && response.recent_transactions.length > 0) {
        content += '<h5 style="margin-top: 20px;">Recent Transactions</h5>';
        content += '<table class="table table-bordered table-striped table-sm">';
        content += '<thead><tr><th>Date</th><th>Type</th><th>Reference</th><th>Amount</th></tr></thead>';
        content += '<tbody>';
        $.each(response.recent_transactions, function(index, transaction) {
          content += '<tr>';
          content += '<td>' + transaction.date + '</td>';
          content += '<td><span class="label label-' + getTransactionTypeColor(transaction.transaction_type) + '">' + transaction.transaction_type + '</span></td>';
          content += '<td>' + transaction.reference + '</td>';
          content += '<td class="text-right">' + (transaction.debit || transaction.credit) + '</td>';
          content += '</tr>';
        });
        content += '</tbody></table>';
      }
      
      $('#customer_summary_content').html(content);
    },
    error: function() {
      $('#customer_summary_content').html('<div class="alert alert-danger">Error loading customer summary</div>');
    }
  });
}

function printLedger() {
  window.print();
}

// Number formatting function
function store_number_format(number) {
  if(typeof number === 'string') {
    number = parseFloat(number);
  }
  return number.toLocaleString('en-IN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  });
}

var base_url = $('#base_url').val() || '<?php echo base_url(); ?>';
</script>

<!-- Make sidebar menu highlighter/selector -->
<script>$(".transaction-ledger-report-active-li").addClass("active");</script>

</body>
</html>
