<!DOCTYPE html>
<html>
<head>
<!-- FORM CSS CODE -->
<?php include"comman/code_css.php"; ?>

<!-- Clean CSS to fix layout issues -->
<style>
  .chart-container {
    position: relative;
    width: 100%;
    height: 300px;
    margin: 10px 0;
  }
  
  .chart-container canvas {
    width: 100% !important;
    height: 100% !important;
  }
  
  .subscription_chart {
    width: 100%;
    height: 300px;
  }
  
  .small-box {
    position: relative;
    display: block;
    margin-bottom: 20px;
    box-shadow: 0 1px 1px rgba(0,0,0,0.1);
  }
  
  .small-box > .inner {
    padding: 10px;
  }
  
  .info-box {
    display: block;
    min-height: 90px;
    background: #fff;
    width: 100%;
    box-shadow: 0 1px 1px rgba(0,0,0,0.1);
    border-radius: 2px;
    margin-bottom: 15px;
  }
  
  .box {
    position: relative;
    border-radius: 3px;
    background: #ffffff;
    border-top: 3px solid #d2d6de;
    margin-bottom: 20px;
    width: 100%;
    box-shadow: 0 1px 1px rgba(0,0,0,0.1);
  }
  
  .box-body {
    border-top-left-radius: 0;
    border-top-right-radius: 0;
    border-bottom-right-radius: 3px;
    border-bottom-left-radius: 3px;
    padding: 10px;
  }
  
  .row {
    margin-left: -15px;
    margin-right: -15px;
  }
  
  .row:before,
  .row:after {
    content: " ";
    display: table;
  }
  
  .row:after {
    clear: both;
  }
  
  /* Fix for collapsed design */
  .content-wrapper {
    min-height: calc(100vh - 50px);
  }
  
  .content {
    min-height: 250px;
    padding: 15px;
  }
</style>
<!-- </copy> -->  

</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>
        <?=$page_title;?>
      </h1>     
    </section>
    <div class="row">
    <div class="col-md-12">
      <!-- ********** ALERT MESSAGE START******* -->
       <?php include"comman/code_flashdata.php"; ?>
       <!-- ********** ALERT MESSAGE END******* -->
     </div>
     </div>
      
    <!-- Main content -->
    <section class="content">

      <div class="row">
        <div class="col-md-12">
           <div class="col-md-3 pull-right">
            <?= form_open('dashboard', array('class' => '', 'id' => 'dashboard_form', 'method' => 'post')); ?>
              <!-- Store Code -->
              <?php 
                 echo "<input type='hidden' name='store_id' id='store_id' value='".get_current_store_id()."'>";
                ?>
              <!-- Store Code end -->
              <?= form_close();?>
           </div>
        </div>
      </div>

      <?php if(!is_user() && $CI->permissions('dashboard_info_box_1')){ ?> 
        <div class="row">
          <div class="box-header">
              <div class="btn-group pull-right">
                <button type="button" title="Today" class="btn btn-default btn-info get_tab_records active">Today</button>
                <button type="button" title="Current Week" class="btn btn-default btn-info get_tab_records">Weekly</button>
                <button type="button" title="Current Month" class="btn btn-default btn-info get_tab_records ">Monthly</button>
                <button type="button" title="Current Year" class="btn btn-default btn-info get_tab_records">Yearly</button>
                <button type="button" title="All Years" class="btn btn-default btn-info get_tab_records ">All</button>
              </div>
          </div><br>

             <div class="col-md-3 col-sm-6 col-xs-12">
              <div class="small-box bg-1">
                <div class="inner">
                  <h3 class="purchase_due"><?= $CI->currency(0); ?></h3>
                  <p><?= $this->lang->line('purchase_due'); ?></p>
                </div>
                <div class="icon"><i class="fa fa-cube"></i></div>
              </div>
            </div>

            <div class="col-md-3 col-sm-6 col-xs-12">
              <div class="small-box bg-2">
                <div class="inner">
                  <h3 class="sales_due"><?= $CI->currency(0); ?></h3>
                  <p><?= $this->lang->line('sales_due'); ?></p>
                </div>
                <div class="icon"><i class="fa fa-calendar-minus-o"></i></div>
              </div>
            </div>

            <div class="col-md-3 col-sm-6 col-xs-12">
              <div class="small-box bg-3">
                <div class="inner">
                  <h3 class="tot_sal_grand_total"><?= $CI->currency(0); ?></h3>
                  <p><?= $this->lang->line('sales'); ?></p>
                </div>
                <div class="icon"><i class="fa fa-file-o"></i></div>
              </div>
            </div>

            <div class="col-md-3 col-sm-6 col-xs-12">
              <div class="small-box bg-4">
                <div class="inner">
                  <h3 class="tot_exp"><?= $CI->currency(0); ?></h3>
                  <p><?= $this->lang->line('expense'); ?></p>
                </div>
                <div class="icon"><i class="fa fa-minus-square-o"></i></div>
              </div>
            </div> 

        </div>
     
      
      <?php } ?>
      

      <!-- Info boxes -->
      <?php if(!is_user() && $CI->permissions('dashboard_info_box_2')){ ?> 
         <div class="row">
       
        <div class="col-md-3 col-sm-6 col-xs-12">
          <div class="info-box " >
            <span class="info-box-icon bg-5"><i class="fa fa-users"></i></span>
            <div class="info-box-content">
              <span class="info-box-text tot_cust" style="font-size: 25px;"><?= $CI->currency(0); ?></span>
              <span class="info-box-number"><?= $this->lang->line('customers'); ?></span>
            </div>
            
            <!-- /.info-box-content -->
          </div>
          <!-- /.info-box -->
        </div>
        <!-- /.col -->
        <div class="col-md-3 col-sm-6 col-xs-12">
          <div class="info-box " >
            <span class="info-box-icon bg-5"><i class="fa fa-truck"></i></span>

            <div class="info-box-content">
              <span class="info-box-text tot_sup" style="font-size: 25px;"><?= $CI->currency(0); ?></span>
              <span class="info-box-number"><?= $this->lang->line('suppliers'); ?></span>
            </div>
            <!-- /.info-box-content -->
          </div>
          <!-- /.info-box -->
        </div>
        <!-- /.col -->

        <!-- fix for small devices only -->
        <div class="clearfix visible-sm-block"></div>

        <div class="col-md-3 col-sm-6 col-xs-12">
          <div class="info-box " >
            <span class="info-box-icon bg-5"><i class="fa fa-suitcase"></i></span>

            <div class="info-box-content">
              <span class="info-box-text tot_pur" style="font-size: 25px;"><?= $CI->currency(0); ?></span>
              <span class="info-box-number"><?= $this->lang->line('purchases'); ?></span>
            </div>
            <!-- /.info-box-content -->
          </div>
          <!-- /.info-box -->
        </div>
        <!-- /.col -->
        <div class="col-md-3 col-sm-6 col-xs-12">
          <div class="info-box " >
            <span class="info-box-icon bg-5"><i class="fa fa-shopping-cart"></i></span>

            <div class="info-box-content">
              <span class="info-box-text tot_sal" style="font-size: 25px;"><?= $CI->currency(0); ?></span>
              <span class="info-box-number"><?= $this->lang->line('invoices'); ?></span>
            </div>
            <!-- /.info-box-content -->
          </div>
          <!-- /.info-box -->
        </div>
        <!-- /.col -->
      </div>
      <?php } ?>
       
      <!-- ############################# GRAPHS ############################## -->
      <?php if(is_admin() && store_module()){ ?>
      <div class="row">
        <div class="col-md-6 animated">
          <div class="box box-primary" >

            <div class="box-header ">
              <h3 class="box-title"><?= $this->lang->line('stores_details'); ?></h3>
              <div class="btn-group pull-right hide">
                <button type="button" title="Today" class="btn btn-default btn-info get_storewise_details ">Today</button>
                <button type="button" title="Current Week" class="btn btn-default btn-info get_storewise_details">Weekly</button>
                <button type="button" title="Current Month" class="btn btn-default btn-info get_storewise_details ">Monthly</button>
                <button type="button" title="Current Year" class="btn btn-default btn-info get_storewise_details">Yearly</button>
                <button type="button" title="All Years" class="btn btn-default btn-info get_storewise_details active">All</button>
              </div>
            </div>

            <!-- /.box-header -->
            <div class="box-body table-responsive">
              <table id="stores_details" class="table">
                <thead>
                <tr class=''>
                  <th>#</th>
                  <th><?= $this->lang->line('store_name'); ?></th>
                  <th><?= $this->lang->line('total_sales'); ?></th>
                  <th><?= $this->lang->line('total_expense'); ?></th>
                  <th><?= $this->lang->line('sales_due'); ?></th>
                </tr>
                </thead>
                <tbody>
                  <?= $CI->get_storewise_details(); ?>
                </tbody>
                
              </table>
            </div>
            <!-- /.box-body -->
          </div>
          <!-- /.box -->

        </div>
        <!-- /.col (RIGHT) -->

        <div class="col-md-6 animated">
             <!-- PRODUCT LIST -->
             <div class="box box-primary">
                <div class="box-header with-border">
                  <h3 class="box-title"><?= $this->lang->line('subcriptions'); ?></h3>

                  <div class="box-tools pull-right">
                    <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
                    </button>
                    <button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>
                  </div>
                </div>
                <!-- /.box-header -->
                <div class="box-body ">
                   <div class="subscription_chart" ></div>
                </div>
                <!-- /.box-body -->
             </div>
             <!-- /.box -->
        </div>

        </div>

        <?php } ?>
        
      
      <div class="row">
      <?php if(!is_user() && $CI->permissions('dashboard_pur_sal_chart')){ ?> 
     <div class="col-md-8 animated">
      <!-- BAR CHART -->
          <div class="box box-primary">
            <div class="box-header with-border">
              <h3 class="box-title"><?= $this->lang->line('purchase_sales_and_expense_bar_chart'); ?></h3>

              
            </div>
            <div class="box-body">
              <div class="chart">
                <canvas class="bar-chartcanvas"></canvas>
              </div>
            </div>
            <!-- /.box-body -->
          </div>
          <!-- /.box -->
        </div>
        <div class="col-md-4">
          <!-- PRODUCT LIST -->
          <div class="box box-primary">
            <div class="box-header with-border">
              <h3 class="box-title text-uppercase"><?= $this->lang->line('recently_added_items'); ?></h3>
            </div>
            <!-- /.box-header -->
            <div class="box-body table-responsive ">
                      <table class="table ">
                        <tr class=''>
                          <td>Sl.No</td>
                          <td><?= $this->lang->line('item_name'); ?></td>
                          <td><?= $this->lang->line('item_sales_price'); ?></td>
                        </tr>
                        <tbody>
                <?php
                    $i=1;
                    
                    $this->db->select("item_name,sales_price")
                                      ->where("store_id",get_current_store_id())
                                      ->where("status",1)
                                      ->from("db_items")
                                      ->order_by('id','desc')
                                      ->limit(10);
                                      
                    $q5 = $this->db->get();
                    if($q5->num_rows() >0){
                      
                      foreach($q5->result() as $res5){
                        ?>
                        <tr>
                          <td><?php echo $i++; ?></td>
                          <td><?php echo $res5->item_name; ?></td>
                          <td><?php echo $CI->currency($res5->sales_price,$with_comma=true); ?></td>
                        </tr>
                        
                        <?php
                      }
                    }
                    ?>
                    </tbody>
                    <?php if($CI->session->userdata('inv_userid')==1){ ?> 
                      <tfoot>
                      <tr>
                        <td colspan="3" class="text-center"><a href="<?php echo $base_url; ?>items" class="uppercase"><?= $this->lang->line('view_all'); ?></a></td>
                      </tr>
                    </tfoot>
                    <?php } ?>
                  </table>
            </div>
            <!-- /.box-body -->
          </div>
          <!-- /.box -->
        </div>
        <?php } ?>
        <!-- /.col -->
        
        <!-- /.col -->
     </div>
      <div class="row">
        <?php if($CI->permissions('dashboard_stock_alert') && !is_user()) { ?> 
        <div class="col-md-12">
          <div class="box box-primary">
            <div class="box-header">
              <h3 class="box-title text-uppercase"><?= $this->lang->line('stock_alert'); ?></h3>
            </div>
            <!-- /.box-header -->
            <div class="box-body table-responsive">
              <table id="example2" class="table table-bordered table-hover">
                <thead>
                <tr class='bg-warning'>
                  <th>#</th>
                  <th><?= $this->lang->line('item_name'); ?></th>
                  <th><?= $this->lang->line('category_name'); ?></th>
                  <th><?= $this->lang->line('brand_name'); ?></th>
                  <th><?= $this->lang->line('stock'); ?></th>
                </tr>
                </thead>
                <tbody>
                </tbody>
                
              </table>
            </div>
            <!-- /.box-body -->
          </div>
          <!-- /.box -->

        </div>
        <!-- /.col (RIGHT) -->
      <?php } ?>
      </div>
     <?php if(!is_user()){ ?>
        <div class="row">

          <?php if($CI->permissions('dashboard_trending_items_chart')){ ?> 
        <div class="col-md-6 ">
          
             <!-- PRODUCT LIST -->
             <div class="box box-primary">
                <div class="box-header with-border">
              <h3 class="box-title text-uppercase"><?= $this->lang->line('top_10_trending_items'); ?></h3>
            </div>
            <div class="box-body">
                <!-- /.box-header -->
                <canvas id="doughnut-chart" width="100%"></canvas>
                <!-- /.box-body -->
              </div>
             </div>
             <!-- /.box -->
             
        </div>
        <?php } ?>
        <?php if($CI->permissions('recent_sales_invoice_list')){ ?> 
         <div class="col-md-6">
          <!-- PRODUCT LIST -->
          <div class="box box-primary">
            <div class="box-header with-border">
              <h3 class="box-title text-uppercase"><?= $this->lang->line('recentl_sales_invoices'); ?></h3>
            </div>
            <!-- /.box-header -->
            <div class="box-body table-responsive">
                      <table class="table">
                        <tr class=''>
                          <td>Sl.No</td>
                          <td><?= $this->lang->line('date'); ?></td>
                          <td><?= $this->lang->line('invoice_id'); ?></td>
                          <td><?= $this->lang->line('customer'); ?></td>
                          <td><?= $this->lang->line('total'); ?></td>
                          <td><?= $this->lang->line('status'); ?></td>
                          <td><?= $this->lang->line('created_by'); ?></td>
                        </tr>
                        <tbody>
                <?php
                    $i=1;

                    if(!is_admin() && !is_store_admin()){
                      $this->db->where("created_by",$this->session->userdata('inv_username'));  
                    }
                    $this->db->select("*")
                                      ->where("store_id",get_current_store_id())
                                      ->from("db_sales")
                                      ->order_by('id','desc')
                                      ->limit(10);

                    $q5=$this->db->get();
                    if($q5->num_rows() >0){
                      
                      foreach($q5->result() as $res5){
                        ?>
                        <tr>
                          <td><?php echo $i++; ?></td>
                          <td><?php echo show_date($res5->sales_date); ?></td>
                          <td><?php echo $res5->sales_code; ?></td>
                          <td><?php echo get_customer_details($res5->customer_id)->customer_name; ?></td>
                          <td><?php echo $CI->currency($res5->grand_total,$with_comma=true); ?></td>
                          <td><?php echo $res5->payment_status; ?></td>
                          <td><?php echo ucfirst($res5->created_by); ?></td>
                        </tr>
                        
                        <?php
                      }
                    }
                    ?>
                    </tbody>
                    <?php if($CI->session->userdata('inv_userid')==1){ ?> 
                      <tfoot>
                      <tr>
                        <td colspan="3" class="text-center"><a href="<?php echo $base_url; ?>sales" class="uppercase"><?= $this->lang->line('view_all'); ?></a></td>
                      </tr>
                    </tfoot>
                    <?php } ?>
                  </table>
            </div>
            <!-- /.box-body -->
          </div>
          <!-- /.box -->
        </div>
          <?php } ?>
      </div>
      <?php } ?>

      
      <!-- ############################# GRAPHS END############################## -->
    </section>
    <!-- /.content -->
  </div>
  <!-- /.content-wrapper -->

  <?php $this->load->view('footer'); ?>
  <!-- Add the sidebar's background. This div must be placed
       immediately after the control sidebar -->
  <div class="control-sidebar-bg"></div>

</div>
<!-- ./wrapper -->

<!-- SOUND CODE -->
<?php include"comman/code_js_sound.php"; ?>
<!-- TABLES CODE -->
<?php include"comman/code_js.php"; ?>
<!-- bootstrap datepicker -->

<!-- ChartJS 1.0.1 -->
<script src="<?php echo $theme_link; ?>plugins/chartjs/Chart.min.js"></script>
<script>

  'use strict';

// Modern chart colors with gradients
window.chartColors = {
  primary: 'rgb(102, 126, 234)',
  primaryGradient: 'linear-gradient(135deg, rgb(102, 126, 234), rgb(118, 75, 162))',
  secondary: 'rgb(240, 147, 251)',
  success: 'rgb(74, 222, 128)',
  warning: 'rgb(251, 191, 36)',
  danger: 'rgb(239, 68, 68)',
  info: 'rgb(59, 130, 246)',
  purple: 'rgb(153, 102, 255)',
  orange: 'rgb(251, 146, 60)',
  teal: 'rgb(20, 184, 166)',
  pink: 'rgb(236, 72, 153)',
  indigo: 'rgb(99, 102, 241)',
  // Legacy support
  red: 'rgb(239, 68, 68)',
  blue: 'rgb(59, 130, 246)',
  green: 'rgb(74, 222, 128)',
  yellow: 'rgb(251, 191, 36)',
  grey: 'rgb(156, 163, 175)'
};

// Modern gradient colors for charts
window.chartGradients = {
  primary: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
  secondary: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
  success: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
  warning: 'linear-gradient(135deg, #fa709a 0%, #fee140 100%)',
  danger: 'linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%)',
  info: 'linear-gradient(135deg, #74b9ff 0%, #0984e3 100%)'
};

// Helper function for transparency with modern alpha values
function transparentize(color, opacity) {
  var alpha = opacity === undefined ? 0.8 : 1 - opacity;
  return color.replace('rgb', 'rgba').replace(')', ', ' + alpha + ')');
}

// Create gradient for canvas
function createGradient(ctx, color1, color2) {
  const gradient = ctx.createLinearGradient(0, 0, 0, 400);
  gradient.addColorStop(0, color1);
  gradient.addColorStop(1, color2);
  return gradient;
}

  

<?php if(is_user()){ ?>
  function createConfig(position) {
      return {
        type: 'line',
        data: {
          labels: [
                "<?=$sub_month[6].'-'.$sub_year[6]?>", 
                "<?=$sub_month[5].'-'.$sub_year[5]?>", 
                "<?=$sub_month[4].'-'.$sub_year[4]?>", 
                "<?=$sub_month[3].'-'.$sub_year[3]?>", 
                "<?=$sub_month[2].'-'.$sub_year[2]?>", 
                "<?=$sub_month[1].'-'.$sub_year[1]?>", 
                "<?=$sub_month[0].'-'.$sub_year[0]?>", 
            ],
          datasets: [{
            label: 'Total Subscriptions',
            borderColor: window.chartColors.red,
            backgroundColor: window.chartColors.red,
            data: [   
                  "<?=$tot_subscribes[6]?>", 
                  "<?=$tot_subscribes[5]?>", 
                  "<?=$tot_subscribes[4]?>", 
                  "<?=$tot_subscribes[3]?>", 
                  "<?=$tot_subscribes[2]?>", 
                  "<?=$tot_subscribes[1]?>", 
                  "<?=$tot_subscribes[0]?>", 
              ],
            fill: false,
          }, /*{
            label: 'My Second dataset',
            borderColor: window.chartColors.blue,
            backgroundColor: window.chartColors.blue,
            data: [7, 49, 46, 13, 25, 30, 22],
            fill: false,
          },*/
          ]
        },
        options: {
          responsive: true,
          title: {
            display: true,
            text: 'Tooltip Position: ' + position
          },
          tooltips: {
            position: position,
            mode: 'index',
            intersect: false,
          },
        }
      };
    }
    
    window.onload = function() {
      var container = document.querySelector('.subscription_chart');
      
      if (!container) {
        console.warn('Subscription chart container not found');
        return;
      }

      try {
        ['average'].forEach(function(position) {
          var div = document.createElement('div');
          div.classList.add('chart-container');

          var canvas = document.createElement('canvas');
          div.appendChild(canvas);
          container.appendChild(div);

          var ctx = canvas.getContext('2d');
          var config = createConfig(position);
          
          // Add error handling for chart creation
          try {
            new Chart(ctx, config);
          } catch (e) {
            console.error('Error creating chart:', e);
            div.innerHTML = '<p style="text-align: center; padding: 20px; color: #666;">Chart loading error</p>';
          }
        });
      } catch (e) {
        console.error('Error in chart initialization:', e);
        container.innerHTML = '<p style="text-align: center; padding: 20px; color: #666;">Charts temporarily unavailable</p>';
      }
    };
<?php } ?>

    //MODERN BAR CHART
<?php if(!is_user()){ ?>
    $(function(){

  try {
    //get the bar chart canvas
    var ctx = $(".bar-chartcanvas");
    
    if (ctx.length === 0) {
      console.warn('Bar chart canvas not found');
      return;
    }

    var canvasElement = ctx[0];
    var canvasCtx = canvasElement.getContext('2d');

    //modern bar chart data with gradients
    var data = {
      labels: [
                  "<?=$month[6]?>", 
                  "<?=$month[5]?>", 
                  "<?=$month[4]?>", 
                  "<?=$month[3]?>", 
                  "<?=$month[2]?>", 
                  "<?=$month[1]?>", 
                  "<?=$month[0]?>", 
              ],
      datasets: [
        {
          label: "<?= $this->lang->line('purchase'); ?>",
          data: [   
                    "<?=$purchase[6]?>", 
                    "<?=$purchase[5]?>", 
                    "<?=$purchase[4]?>", 
                    "<?=$purchase[3]?>", 
                    "<?=$purchase[2]?>", 
                    "<?=$purchase[1]?>", 
                    "<?=$purchase[0]?>", 
                ],
          backgroundColor: createGradient(canvasCtx, window.chartColors.primary, transparentize(window.chartColors.primary, 0.3)),
          borderColor: window.chartColors.primary,
          borderWidth: 2,
          borderRadius: 8,
          borderSkipped: false,
        },
        {
         label: "<?= $this->lang->line('sales'); ?>",
          data: [   
                    "<?=$sales[6]?>", 
                    "<?=$sales[5]?>", 
                    "<?=$sales[4]?>", 
                    "<?=$sales[3]?>", 
                    "<?=$sales[2]?>", 
                    "<?=$sales[1]?>", 
                    "<?=$sales[0]?>", 
                ],
          backgroundColor: createGradient(canvasCtx, window.chartColors.success, transparentize(window.chartColors.success, 0.3)),
          borderColor: window.chartColors.success,
          borderWidth: 2,
          borderRadius: 8,
          borderSkipped: false,
        },
        {
          label: "<?= $this->lang->line('expense'); ?>",
          data: [   
                    "<?=$expense[6]?>", 
                    "<?=$expense[5]?>", 
                    "<?=$expense[4]?>", 
                    "<?=$expense[3]?>", 
                    "<?=$expense[2]?>", 
                    "<?=$expense[1]?>", 
                    "<?=$expense[0]?>", 
                ],
          backgroundColor: createGradient(canvasCtx, window.chartColors.warning, transparentize(window.chartColors.warning, 0.3)),
          borderColor: window.chartColors.warning,
          borderWidth: 2,
          borderRadius: 8,
          borderSkipped: false,
        }
      ]
    };

    //modern chart options
    var options = {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          display: true,
          position: "top",
          labels: {
            usePointStyle: true,
            pointStyle: 'circle',
            font: {
              family: 'Inter',
              size: 14,
              weight: '500'
            },
            color: '#374151',
            padding: 20
          }
        },
        tooltip: {
          backgroundColor: 'rgba(0, 0, 0, 0.8)',
          titleColor: '#fff',
          bodyColor: '#fff',
          borderColor: 'rgba(255, 255, 255, 0.1)',
          borderWidth: 1,
          cornerRadius: 8,
          displayColors: true,
          font: {
            family: 'Inter'
          }
        }
      },
      scales: {
        x: {
          grid: {
            display: false
          },
          ticks: {
            font: {
              family: 'Inter',
              size: 12
            },
            color: '#6b7280'
          }
        },
        y: {
          beginAtZero: true,
          grid: {
            color: 'rgba(107, 114, 128, 0.1)',
            borderDash: [5, 5]
          },
          ticks: {
            font: {
              family: 'Inter',
              size: 12
            },
            color: '#6b7280'
          }
        }
      },
      elements: {
        bar: {
          borderRadius: 8,
          borderSkipped: false,
        }
      },
      animation: {
        duration: 1000,
        easing: 'easeOutQuart'
      }
    };
    
    //create modern Chart
    var chart = new Chart(canvasCtx, {
      type: "bar",
      data: data,
      options: options
    });
    
  } catch (e) {
    console.error('Error creating bar chart:', e);
    $('.bar-chartcanvas').parent().html('<div class="chart-error"><i class="fa fa-exclamation-triangle"></i><p>Chart temporarily unavailable</p></div>');
  }
});


  //MODERN DOUGHNUT CHART
  try {
    var doughnutCanvas = document.getElementById("doughnut-chart");
    if (doughnutCanvas) {
      var doughnutCtx = doughnutCanvas.getContext('2d');
      
      new Chart(doughnutCtx, {
        type: 'doughnut',
        data: {
          labels: 
                  [
                    <?php if($tranding_item['tot_rec'] > 0){?>
                        <?php for($i=$tranding_item['tot_rec']; $i>0; $i--){ ?>
                            '<?= $tranding_item[$i]['name'] ?>',
                        <?php } ?>
                    <?php } ?>
                  ],
          datasets: [
            {
              label: "Top Items",
              backgroundColor: [
                window.chartColors.primary,
                window.chartColors.secondary,
                window.chartColors.success,
                window.chartColors.warning,
                window.chartColors.danger,
                window.chartColors.info,
                window.chartColors.purple,
                window.chartColors.orange,
                window.chartColors.teal,
                window.chartColors.pink
              ],
              borderColor: '#ffffff',
              borderWidth: 3,
              hoverBorderWidth: 5,
              data: [
                    <?php if($tranding_item['tot_rec'] > 0){?>
                        <?php for($i=$tranding_item['tot_rec']; $i>0; $i--){ ?>
                            '<?= $tranding_item[$i]['sales_qty'] ?>',
                        <?php } ?>
                    <?php } ?>
                  ],
            }
          ]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          cutout: '65%',
          plugins: {
            legend: {
              display: true,
              position: 'bottom',
              labels: {
                usePointStyle: true,
                pointStyle: 'circle',
                font: {
                  family: 'Inter',
                  size: 12,
                  weight: '500'
                },
                color: '#374151',
                padding: 15,
                generateLabels: function(chart) {
                  const data = chart.data;
                  if (data.labels.length && data.datasets.length) {
                    return data.labels.map((label, i) => ({
                      text: label,
                      fillStyle: data.datasets[0].backgroundColor[i],
                      strokeStyle: '#ffffff',
                      lineWidth: 2,
                      hidden: false,
                      index: i
                    }));
                  }
                  return [];
                }
              }
            },
            tooltip: {
              backgroundColor: 'rgba(0, 0, 0, 0.8)',
              titleColor: '#fff',
              bodyColor: '#fff',
              borderColor: 'rgba(255, 255, 255, 0.1)',
              borderWidth: 1,
              cornerRadius: 8,
              font: {
                family: 'Inter'
              },
              callbacks: {
                label: function(context) {
                  const label = context.label || '';
                  const value = context.parsed || 0;
                  const total = context.dataset.data.reduce((a, b) => a + b, 0);
                  const percentage = ((value / total) * 100).toFixed(1);
                  return `${label}: ${value} (${percentage}%)`;
                }
              }
            }
          },
          animation: {
            animateRotate: true,
            animateScale: true,
            duration: 1000,
            easing: 'easeOutQuart'
          },
          elements: {
            arc: {
              borderWidth: 3,
              hoverBorderWidth: 5
            }
          }
        }
      });
    } else {
      console.warn('Doughnut chart canvas not found');
    }
  } catch (e) {
    console.error('Error creating doughnut chart:', e);
    var chartContainer = document.getElementById("doughnut-chart");
    if (chartContainer && chartContainer.parentElement) {
      chartContainer.parentElement.innerHTML = '<div class="chart-error"><i class="fa fa-exclamation-triangle"></i><p>Chart temporarily unavailable</p></div>';
    }
  }
<?php } ?>

  </script>




<!-- Make sidebar menu hughlighter/selector -->
<script>$(".<?php echo basename(__FILE__,'.php');?>-active-li").addClass("active");</script>
<script type="text/javascript">
    var base_url='<?= base_url(); ?>';
    function get_dashboard_values(dates=''){
      var store_id =<?= (isset($store_id)) ? $store_id : get_current_store_id();?>;
      $.post(base_url+"dashboard/dashboard_values",{store_id:store_id,dates:dates},function(result){
          var data = jQuery.parseJSON(result);
          $.each(data, function(index, element) {
                  $("."+index).html(element);
          });
      });
    }

    $("#store_id").on("change",function(){
      //get_dashboard_values();
      $("#dashboard_form").submit();
    });
    jQuery(document).ready(function($) {
      get_dashboard_values('Today');
    });

      $(".get_tab_records").on("click",function(event) {
        $(".get_tab_records").removeClass('active');
        $(this).addClass('active');
        get_dashboard_values($(this).html());
      });


    <?php if(is_admin() && store_module()){ ?>
      $("#stores_details").DataTable();
    <?php } ?>
</script>
<script>
 /* $(function () {
    $('#example3').DataTable({
      "pageLength" : 5,
      "paging": true,
      "lengthChange": false,
      "searching": false,
      "ordering": true,
      "info": true,
      "autoWidth": false
    });
  });*/


 $(document).ready(function() {
    //datatables
   var table = $('#example2').DataTable({ 

      /* FOR EXPORT BUTTONS START*/
  dom:'<"row margin-bottom-12"<"col-sm-12"<"pull-left"l><"pull-right"fr><"pull-right margin-left-10 "B>>>tip',
 /* dom:'<"row"<"col-sm-12"<"pull-left"B><"pull-right">>> <"row margin-bottom-12"<"col-sm-12"<"pull-left"l><"pull-right"fr>>>tip',*/
      buttons: {
        buttons: [
            {
                className: 'btn bg-red color-palette btn-flat hidden delete_btn pull-left',
                text: 'Delete',
                action: function ( e, dt, node, config ) {
                    multi_delete();
                }
            },
            { extend: 'copy', className: 'btn bg-teal color-palette btn-flat',exportOptions: { columns: [0,1,2,3,4]} },
            { extend: 'excel', className: 'btn bg-teal color-palette btn-flat',exportOptions: { columns: [0,1,2,3,4]} },
            { extend: 'pdf', className: 'btn bg-teal color-palette btn-flat',exportOptions: { columns: [0,1,2,3,4]} },
            { extend: 'print', className: 'btn bg-teal color-palette btn-flat',exportOptions: { columns: [0,1,2,3,4]} },
            { extend: 'csv', className: 'btn bg-teal color-palette btn-flat',exportOptions: { columns: [0,1,2,3,4]} },
            { extend: 'colvis', className: 'btn bg-teal color-palette btn-flat',text:'Columns' },  

            ]
        },
        /* FOR EXPORT BUTTONS END */

        "processing": true, //Feature control the processing indicator.
        "serverSide": true, //Feature control DataTables' server-side processing mode.
        "order": [], //Initial no order.
        "responsive": true,
        language: {
            processing: '<div class="text-primary bg-primary" style="position: relative;z-index:100;overflow: visible;">Processing...</div>'
        },
        // Load data for the table's content from an Ajax source
        "ajax": {
            "url": "<?php echo site_url('dashboard/ajax_list')?>",
            "type": "POST",
            
            complete: function (data) {
             },

        },

        //Set column definition initialisation properties.
        "columnDefs": [
        { 
            //"targets": [ 0,4 ], //first column / numbering column
            "orderable": false, //set not orderable
        },
        {
            //"targets" :[0],
            //"className": "text-center",
        },
        
        ],
    });
    new $.fn.dataTable.FixedHeader( table );
});

<!-- Modern JavaScript Enhancements -->
<script>
// Modern Dashboard Enhancements
$(document).ready(function() {
  
  // Add modern animation delays to elements
  $('.small-box').each(function(index) {
    $(this).css('animation-delay', (index * 0.1) + 's');
    $(this).addClass('animated');
  });
  
  $('.info-box').each(function(index) {
    $(this).css('animation-delay', (index * 0.1) + 's');
    $(this).addClass('animated');
  });
  
  $('.box').each(function(index) {
    $(this).css('animation-delay', (index * 0.1) + 's');
    $(this).addClass('animated');
  });

  // Enhanced hover effects for cards
  $('.small-box, .info-box, .box').hover(
    function() {
      $(this).css('transform', 'translateY(-5px)');
    },
    function() {
      $(this).css('transform', 'translateY(0)');
    }
  );

  // Modern button click effects
  $('.btn').on('click', function(e) {
    let ripple = $('<span class="ripple"></span>');
    let size = Math.max($(this).outerWidth(), $(this).outerHeight());
    let x = e.pageX - $(this).offset().left - size / 2;
    let y = e.pageY - $(this).offset().top - size / 2;
    
    ripple.css({
      'width': size,
      'height': size,
      'left': x,
      'top': y
    });
    
    $(this).append(ripple);
    
    setTimeout(function() {
      ripple.remove();
    }, 600);
  });

  // Smooth scrolling for anchor links
  $('a[href^="#"]').on('click', function(event) {
    var target = $(this.getAttribute('href'));
    if( target.length ) {
      event.preventDefault();
      $('html, body').stop().animate({
        scrollTop: target.offset().top - 100
      }, 1000);
    }
  });

  // Modern tooltip initialization
  $('[data-toggle="tooltip"]').tooltip({
    container: 'body',
    animation: true,
    delay: { show: 300, hide: 100 }
  });

  // Counter animation for dashboard numbers
  function animateCounters() {
    $('.small-box h3, .info-box-text').each(function() {
      var $this = $(this);
      var text = $this.text();
      var number = parseFloat(text.replace(/[^0-9.-]+/g, ''));
      
      if (!isNaN(number) && number > 0) {
        $({ countNum: 0 }).animate({
          countNum: number
        }, {
          duration: 2000,
          easing: 'swing',
          step: function() {
            var formattedNumber = Math.floor(this.countNum);
            if (text.includes('$') || text.includes('₹')) {
              $this.text('₹' + formattedNumber.toLocaleString());
            } else {
              $this.text(formattedNumber.toLocaleString());
            }
          },
          complete: function() {
            $this.text(text); // Reset to original format
          }
        });
      }
    });
  }

  // Trigger counter animation after a delay
  setTimeout(animateCounters, 500);

  // Modern loading states
  function showLoading(element) {
    element.html('<div class="loading-placeholder"></div>');
  }

  function hideLoading(element, content) {
    element.html(content);
  }

  // Enhanced chart responsiveness
  function resizeCharts() {
    if (window.Chart) {
      Object.values(Chart.instances).forEach(chart => {
        chart.resize();
      });
    }
  }

  $(window).resize(resizeCharts);

  // Modern notification system
  function showNotification(message, type = 'info', duration = 5000) {
    const notification = $(`
      <div class="modern-notification notification-${type}">
        <div class="notification-content">
          <i class="fa fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'info-circle'}"></i>
          <span>${message}</span>
        </div>
        <button class="notification-close">×</button>
      </div>
    `);

    $('body').append(notification);
    
    setTimeout(() => {
      notification.addClass('show');
    }, 100);

    setTimeout(() => {
      notification.removeClass('show');
      setTimeout(() => notification.remove(), 300);
    }, duration);

    notification.find('.notification-close').on('click', function() {
      notification.removeClass('show');
      setTimeout(() => notification.remove(), 300);
    });
  }

  // Add notification styles
  $('<style>')
    .prop('type', 'text/css')
    .html(`
      .modern-notification {
        position: fixed;
        top: 20px;
        right: 20px;
        background: rgba(255, 255, 255, 0.95);
        backdrop-filter: blur(10px);
        border-radius: 12px;
        padding: 15px 20px;
        box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
        z-index: 10000;
        transform: translateX(400px);
        opacity: 0;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        max-width: 350px;
        border-left: 4px solid #667eea;
      }
      .modern-notification.show {
        transform: translateX(0);
        opacity: 1;
      }
      .notification-content {
        display: flex;
        align-items: center;
        gap: 10px;
      }
      .notification-content i {
        font-size: 1.2rem;
        color: #667eea;
      }
      .notification-close {
        position: absolute;
        top: 5px;
        right: 10px;
        background: none;
        border: none;
        font-size: 1.2rem;
        color: #9ca3af;
        cursor: pointer;
        padding: 5px;
      }
      .notification-success { border-left-color: #4ade80; }
      .notification-success i { color: #4ade80; }
      .notification-error { border-left-color: #ef4444; }
      .notification-error i { color: #ef4444; }
      .notification-warning { border-left-color: #fbbf24; }
      .notification-warning i { color: #fbbf24; }
    `)
    .appendTo('head');

  // Example: Show welcome notification
  setTimeout(() => {
    showNotification('Welcome to your modern dashboard!', 'success');
  }, 1000);
});

// Add ripple effect styles
$('<style>')
  .prop('type', 'text/css')
  .html(`
    .btn {
      position: relative;
      overflow: hidden;
    }
    .ripple {
      position: absolute;
      border-radius: 50%;
      background: rgba(255, 255, 255, 0.3);
      transform: scale(0);
      animation: ripple-animation 0.6s linear;
      pointer-events: none;
    }
    @keyframes ripple-animation {
      to {
        transform: scale(4);
        opacity: 0;
      }
    }
  `)
  .appendTo('head');
</script>
