<!DOCTYPE html>
<html>
<head>
<?php include "comman/code_css.php"; ?>
<link rel="stylesheet" href="<?=$theme_link;?>plugins/datepicker/bootstrap-datepicker.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
:root{
  --bg:#eef2f7;--ink:#0f172a;--muted:#64748b;--panel:#ffffff;--ring:rgba(37,99,235,.16);
  --shadow:0 8px 28px rgba(15,23,42,.08),0 2px 8px rgba(15,23,42,.05);
  --primary:#2563eb;--ok:#16a34a;--warn:#f59e0b;--danger:#ef4444
}
/* page */
html,body{background:var(--bg);color:var(--ink)}
.content-header h1{font-weight:800;letter-spacing:.2px;margin:8px 0 6px}

/* ===== Status row (Period/Currency/Multi/Updated) — equal width ===== */
.status-shell{background:var(--panel);border:1px solid #e6ebf2;border-radius:18px;box-shadow:var(--shadow);padding:12px 14px;margin-bottom:16px}
.status-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px}
.status-pill{width:100%;display:flex;align-items:center;gap:10px;background:#eef4ff;border:1px solid #dbe7ff;color:#1e3a8a;border-radius:999px;padding:10px 14px}
.status-ico{flex:0 0 28px;height:28px;border-radius:50%;background:#fff;border:1px solid #e6edff;display:flex;align-items:center;justify-content:center;font-size:14px;color:#4f6bff}
.status-key{font-weight:700;margin-right:6px}
.status-val{font-weight:800}
@media(max-width:992px){.status-grid{grid-template-columns:repeat(2,1fr)}}
@media(max-width:560px){.status-grid{grid-template-columns:1fr}}

/* ===== KPI gradient cards (like your screenshot) ===== */
.kpi-row{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:14px;margin-bottom:14px}
.kpi{position:relative;border-radius:14px;min-height:88px;padding:14px 16px 14px 16px;color:#fff;box-shadow:var(--shadow);overflow:hidden}
.kpi .value{font-size:28px;font-weight:900;line-height:1}
.kpi .label{margin-top:4px;letter-spacing:.3px;text-transform:uppercase;font-size:12px;font-weight:700;opacity:.9}
.kpi .kico{position:absolute;right:16px;top:50%;transform:translateY(-50%);font-size:48px;opacity:.18}
.kpi.p1{background:linear-gradient(135deg,#a78bfa 0%,#ec4899 100%)}
.kpi.p2{background:linear-gradient(135deg,#f43f5e 0%,#ef4444 50%,#ec4899 100%)}
.kpi.p3{background:linear-gradient(135deg,#10b981 0%,#22c55e 100%)}
.kpi.p4{background:linear-gradient(135deg,#0f172a 0%,#0ea5e9 100%)}
/* light mini cards row (Customers/Suppliers/Purchases/Invoices) */
.mini-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:14px;margin-bottom:16px}
.mini{background:#fff;border:1px solid #e6ebf2;border-radius:12px;box-shadow:var(--shadow);display:flex;align-items:center;gap:12px;padding:12px 14px}
.mini .m-ico{flex:0 0 46px;height:46px;border-radius:12px;display:flex;align-items:center;justify-content:center;color:#fff;font-size:20px}
.mi1{background:linear-gradient(135deg,#22c1c3,#2f80ed)} .mi2{background:linear-gradient(135deg,#2f80ed,#1cb5e0)}
.mi3{background:linear-gradient(135deg,#2f80ed,#0ea5e9)} .mi4{background:linear-gradient(135deg,#2f80ed,#3b82f6)}
.mini .m-val{font-size:22px;font-weight:900;line-height:1}
.mini .m-key{margin-top:2px;text-transform:uppercase;font-weight:800;font-size:12px;color:#0f172a;opacity:.8}

/* Boxes */
.box-modern{background:var(--panel);border-radius:16px;box-shadow:var(--shadow);border:1px solid #e6ebf2}
.box-modern .box-header{border-bottom:1px solid #e6ebf2;border-radius:16px 16px 0 0;padding:12px 16px}
.box-modern .box-title{font-weight:800;margin:0}
.chart canvas{max-height:360px}

/* Recent sales */
.recent-card{background:var(--panel);border-radius:16px;box-shadow:var(--shadow);border:1px solid #e6ebf2}
.recent-sales-container{max-height:520px;overflow-y:auto}
.recent-sale-item{border-bottom:1px solid #eef2f7;padding:14px 16px;transition:all .2s ease}
.recent-sale-item:hover{transform:translateX(2px);background:#fafcff}
.rs-top{display:grid;grid-template-columns:1fr auto;gap:12px;align-items:start}
.sale-code a{color:#1f51ff;font-weight:800;text-decoration:none}
.sale-code a:hover{text-decoration:underline}
.sale-date{color:var(--muted);font-size:12px;margin-top:2px}
.rs-amt{text-align:right}
.amount{font-weight:900;color:#0f172a;display:block}
.amount-secondary{color:#475569;font-weight:800}
.rs-bottom{display:grid;grid-template-columns:1fr auto;align-items:center;margin-top:8px}
.customer-info{color:#334155;font-size:13px;display:flex;align-items:center;gap:6px}
.sale-status .label{font-size:11px;padding:4px 8px;border-radius:999px}
.rs-meta{margin-top:6px;color:#64748b;font-size:11px}
.label-success{background:#16a34a}.label-warning{background:#f59e0b}.label-info{background:#0ea5e9}.label-danger{background:#ef4444}
@media(max-width:1200px){.kpi-row,.mini-grid{grid-template-columns:repeat(2,1fr)}}
@media(max-width:640px){.kpi-row,.mini-grid{grid-template-columns:1fr}.rs-top{grid-template-columns:1fr}.rs-amt{text-align:left}}

/* Stock alert */
#stock_alert_table{width:100%}
#stock_alert_table thead th{background:#f8fafc;color:#0f172a;border-bottom:1px solid #e2e8f0}
.stock-note{display:flex;gap:10px;align-items:center;background:#fff7ed;border:1px solid #fde68a;color:#7c2d12;padding:10px 12px;border-radius:12px;margin-bottom:12px}
.table-bordered>tbody>tr>td,.table-bordered>thead>tr>th{border-color:#e2e8f0!important}
.btn-xs{border-radius:10px}

/* Filters */
.filter-bar{display:flex;flex-wrap:wrap;gap:8px;justify-content:flex-end;margin:6px 0 16px}
.filter-bar .btn{border-radius:999px;border:1px solid #e5e7eb;background:#fff;color:var(--ink);padding:7px 14px}
.filter-bar .btn.active{background:#2563eb;color:#fff;border-color:#2563eb;box-shadow:0 0 0 6px var(--ring)}
.filter-bar .btn-success{background:#22c55e;border-color:#22c55e;color:#06201a}
</style>
</head>
<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">
<?php include "sidebar.php"; ?>

<div class="content-wrapper">
<section class="content-header"><h1><?=$page_title;?></h1></section>
<div class="row"><div class="col-md-12"><?php include "comman/code_flashdata.php"; ?></div></div>

<section class="content">

<!-- ===== Status row (equal columns) ===== -->
<div class="status-shell">
  <div class="status-grid">
    <div class="status-pill">
      <div class="status-ico"><i class="fa fa-calendar"></i></div>
      <div><span class="status-key">Period:</span> <span class="status-val" id="current_period">Today</span></div>
    </div>
    <div class="status-pill">
      <div class="status-ico"><i class="fa fa-money"></i></div>
      <div><span class="status-key">System Currency:</span> <span class="status-val"><?php $bc=get_base_currency(); echo isset($bc->currency_code)?$bc->currency_code:'USD'; ?></span></div>
    </div>
    <div class="status-pill">
      <div class="status-ico"><i class="fa fa-exchange"></i></div>
      <div><span class="status-key">Multi-Currency:</span> <span class="status-val" style="color:#15803d">Enabled</span></div>
    </div>
    <div class="status-pill">
      <div class="status-ico"><i class="fa fa-clock-o"></i></div>
      <div><span class="status-key">Updated:</span> <span class="status-val" id="last_updated">Just now</span></div>
    </div>
  </div>
</div>

<?php if(!is_user() && $CI->permissions('dashboard_info_box_1')){ ?>
<div class="row"><div class="col-md-12">
  <div class="filter-bar">
    <button type="button" class="btn get_tab_records active">Today</button>
    <button type="button" class="btn get_tab_records">Yesterday</button>
    <button type="button" class="btn get_tab_records">This Week</button>
    <button type="button" class="btn get_tab_records">Last Week</button>
    <button type="button" class="btn get_tab_records">This Month</button>
    <button type="button" class="btn get_tab_records">Last Month</button>
    <button type="button" class="btn get_tab_records">This Year</button>
    <button type="button" class="btn get_tab_records">Last Year</button>
    <button type="button" class="btn get_tab_records">All</button>
    <button type="button" class="btn btn-success" id="custom_date_btn">Custom</button>
  </div>
</div></div>

<!-- ===== Gradient KPI cards (equal width) ===== -->
<div class="kpi-row">
  <div class="kpi p1">
    <div class="value purchase_due"><?= $CI->currency(0); ?></div>
    <div class="label"><?= $this->lang->line('purchase_due'); ?></div>
    <i class="fa fa-cube kico"></i>
  </div>
  <div class="kpi p2">
    <div class="value sales_due"><?= $CI->currency(0); ?></div>
    <div class="label"><?= $this->lang->line('sales_due'); ?></div>
    <i class="fa fa-calendar kico"></i>
  </div>
  <div class="kpi p3">
    <div class="value tot_sal_grand_total"><?= $CI->currency(0); ?></div>
    <div class="label"><?= $this->lang->line('sales'); ?></div>
    <i class="fa fa-file-o kico"></i>
  </div>
  <div class="kpi p4">
    <div class="value tot_exp"><?= $CI->currency(0); ?></div>
    <div class="label"><?= $this->lang->line('expense'); ?></div>
    <i class="fa fa-minus-square-o kico"></i>
  </div>
</div>

<?php } ?>

<?php if(!is_user() && $CI->permissions('dashboard_info_box_2')){ ?>
<!-- ===== Small white stat cards row ===== -->
<div class="mini-grid">
  <div class="mini"><div class="m-ico mi1"><i class="fa fa-users"></i></div><div><div class="m-val tot_cust"><?= $CI->currency(0); ?></div><div class="m-key"><?= $this->lang->line('customers'); ?></div></div></div>
  <div class="mini"><div class="m-ico mi2"><i class="fa fa-truck"></i></div><div><div class="m-val tot_sup"><?= $CI->currency(0); ?></div><div class="m-key"><?= $this->lang->line('suppliers'); ?></div></div></div>
  <div class="mini"><div class="m-ico mi3"><i class="fa fa-suitcase"></i></div><div><div class="m-val tot_pur"><?= $CI->currency(0); ?></div><div class="m-key"><?= $this->lang->line('purchases'); ?></div></div></div>
  <div class="mini"><div class="m-ico mi4"><i class="fa fa-shopping-cart"></i></div><div><div class="m-val tot_sal"><?= $CI->currency(0); ?></div><div class="m-key"><?= $this->lang->line('invoices'); ?></div></div></div>
</div>
<?php } ?>

<?php if(is_admin() && store_module()){ ?>
<div class="row" style="margin-top:6px;">
  <div class="col-md-6">
    <div class="box-modern">
      <div class="box-header"><h3 class="box-title"><?= $this->lang->line('stores_details'); ?></h3></div>
      <div class="box-body table-responsive">
        <table id="stores_details" class="table">
          <thead><tr><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>
    </div>
  </div>
  <div class="col-md-6">
    <div class="box-modern">
      <div class="box-header"><h3 class="box-title"><?= $this->lang->line('subcriptions'); ?></h3></div>
      <div class="box-body"><div class="subscription_chart"></div></div>
    </div>
  </div>
</div>
<?php } ?>

<div class="row" style="margin-top:12px;">
<?php if(!is_user() && $CI->permissions('dashboard_pur_sal_chart')){ ?>
  <div class="col-md-8">
    <div class="box-modern">
      <div class="box-header"><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>
    </div>
  </div>
  <div class="col-md-4">
    <div class="box-modern">
      <div class="box-header"><h3 class="box-title text-uppercase"><?= $this->lang->line('recently_added_items'); ?></h3></div>
      <div class="box-body table-responsive">
        <table class="table">
          <tr><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>
    </div>
  </div>
<?php } ?>
</div>

<div class="row" style="margin-top:12px;">
<?php if($CI->permissions('dashboard_stock_alert') && !is_user()) { ?>
  <div class="col-md-12">
    <div class="box-modern">
      <div class="box-header">
        <h3 class="box-title text-uppercase"><i class="fa fa-exclamation-triangle"></i> <?= $this->lang->line('stock_alert'); ?></h3>
        <div class="box-tools pull-right"><button class="btn btn-sm btn-primary" onclick="refreshStockAlert()"><i class="fa fa-refresh"></i> Refresh</button></div>
      </div>
      <div class="box-body">
        <div class="stock-note"><i class="fa fa-bell"></i><div><strong><?= $this->lang->line('stock_alert'); ?></strong> – <?= $this->lang->line('stock_alert_description'); ?></div></div>
        <div class="table-responsive">
          <table id="stock_alert_table" class="table table-bordered table-hover">
            <thead>
              <tr>
                <th>#</th><th><?= $this->lang->line('item_details'); ?></th><th><?= $this->lang->line('category'); ?></th><th><?= $this->lang->line('brand'); ?></th>
                <th class="text-center"><?= $this->lang->line('current_stock'); ?></th><th class="text-center"><?= $this->lang->line('min_stock'); ?></th>
                <th class="text-center"><?= $this->lang->line('status'); ?></th><th class="text-center"><?= $this->lang->line('actions'); ?></th>
              </tr>
            </thead>
            <tbody></tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
<?php } ?>
</div>

<!-- Expiry Notifications Widget -->
<?php if(!is_user()){ ?>
<div class="row" style="margin-top:12px;">
  <div class="col-md-6">
    <div class="box-modern">
      <div class="box-header">
        <h3 class="box-title">
          <i class="fa fa-calendar-times-o text-warning"></i> 
          Expiring Items (Next 30 Days)
        </h3>
        <div class="box-tools pull-right">
          <a href="<?=base_url('reports/expiry_report')?>" class="btn btn-xs btn-primary">
            <i class="fa fa-eye"></i> View All
          </a>
        </div>
      </div>
      <div class="box-body">
        <div id="expiring_items_widget">
          <div class="text-center">
            <i class="fa fa-spinner fa-spin"></i> Loading...
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="col-md-6">
    <div class="box-modern">
      <div class="box-header">
        <h3 class="box-title">
          <i class="fa fa-exclamation-triangle text-danger"></i> 
          Expired Items
        </h3>
        <div class="box-tools pull-right">
          <a href="<?=base_url('reports/expiry_report?filter=expired')?>" class="btn btn-xs btn-danger">
            <i class="fa fa-eye"></i> View All
          </a>
        </div>
      </div>
      <div class="box-body">
        <div id="expired_items_widget">
          <div class="text-center">
            <i class="fa fa-spinner fa-spin"></i> Loading...
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<?php } ?>

<?php if(!is_user()){ ?>
<div class="row" style="margin-top:12px;">
<?php if($CI->permissions('dashboard_trending_items_chart')){ ?>
  <div class="col-md-6">
    <div class="box-modern">
      <div class="box-header"><h3 class="box-title text-uppercase"><?= $this->lang->line('top_10_trending_items'); ?></h3></div>
      <div class="box-body"><canvas id="doughnut-chart" width="100%"></canvas></div>
    </div>
  </div>
<?php } ?>
<?php if($CI->permissions('recent_sales_invoice_list')){ ?>
  <div class="col-md-6">
    <div class="recent-card">
      <div class="box-header" style="border-bottom:1px solid #e6ebf2;padding:12px 16px">
        <h3 class="box-title"><i class="fa fa-file-text-o"></i> <?= $this->lang->line('recentl_sales_invoices'); ?> <small class="text-muted">(Last 10)</small></h3>
        <div class="box-tools pull-right"><a href="<?php echo $base_url; ?>sales" class="btn btn-sm btn-primary"><i class="fa fa-eye"></i> View All</a></div>
      </div>
      <div class="box-body" style="padding:0;">
        <div class="recent-sales-container">
        <?php
          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){
              $customer = get_customer_details($res5->customer_id);
              $customer_name = $customer ? $customer->customer_name : 'Unknown Customer';
              $base_currency = get_base_currency();
              $original_amount = $res5->grand_total;
              $original_currency_code = '';
              $base_amount = $res5->grand_total;
              $base_currency_code = $base_currency->currency_code;
              $show_dual_currency = false; $exchange_rate = 0;
              if (!empty($res5->transaction_currency_id) && $res5->transaction_currency_id != $base_currency->id) {
                $original_currency = get_currency_by_id($res5->transaction_currency_id);
                $original_currency_code = $original_currency->currency_code;
                $base_amount = convert_currency($res5->grand_total, $res5->transaction_currency_id, $base_currency->id);
                $exchange_rate = get_exchange_rate($res5->transaction_currency_id, $base_currency->id);
                $show_dual_currency = true;
              } elseif (empty($res5->transaction_currency_id) && !empty($res5->customer_id)) {
                $customer_currency = get_customer_trading_currency($res5->customer_id);
                if ($customer_currency && $customer_currency->id != $base_currency->id) {
                  $original_currency_code = $customer_currency->currency_code;
                  $base_amount = convert_currency($res5->grand_total, $customer_currency->id, $base_currency->id);
                  $exchange_rate = get_exchange_rate($customer_currency->id, $base_currency->id);
                  $show_dual_currency = true;
                }
              }
              $status_class='danger'; $status_icon='fa-times-circle';
              switch(strtolower($res5->payment_status)){
                case 'paid': $status_class='success'; $status_icon='fa-check-circle'; break;
                case 'pending': $status_class='warning'; $status_icon='fa-clock-o'; break;
                case 'partial': $status_class='info'; $status_icon='fa-hourglass-half'; break;
              } ?>
              <div class="recent-sale-item">
                <div class="rs-top">
                  <div>
                    <h4 class="sale-code"><a href="<?php echo base_url('sales/invoice/'.$res5->id); ?>"><?php echo $res5->sales_code; ?></a></h4>
                    <p class="sale-date"><i class="fa fa-calendar"></i> <?php echo show_date($res5->sales_date); ?></p>
                  </div>
                  <div class="rs-amt">
                    <?php if($show_dual_currency){ ?>
                      <span class="amount"><?php echo number_format($original_amount, 2); ?> <?php echo $original_currency_code; ?></span>
                      <span class="amount amount-secondary"><?php echo number_format($base_amount, 2); ?> <?php echo $base_currency_code; ?></span>
                      <small class="text-muted">(1 <?php echo $original_currency_code; ?> = <?php echo number_format($exchange_rate, 6); ?> <?php echo $base_currency_code; ?>)</small>
                    <?php } else { ?>
                      <span class="amount"><?php echo $CI->currency($base_amount, $with_comma=true); ?></span>
                    <?php } ?>
                  </div>
                </div>
                <div class="rs-bottom">
                  <div class="customer-info"><i class="fa fa-user"></i><?php echo $customer_name; ?></div>
                  <div class="sale-status"><span class="label label-<?php echo $status_class; ?>"><i class="fa <?php echo $status_icon; ?>"></i> <?php echo ucfirst($res5->payment_status); ?></span></div>
                </div>
                <div class="rs-meta"><i class="fa fa-user-circle"></i> Created by <?php echo ucfirst($res5->created_by); ?></div>
              </div>
            <?php } } else { ?>
              <div class="text-center" style="padding:40px 20px;"><i class="fa fa-file-text-o fa-3x text-muted"></i><p class="text-muted" style="margin-top:15px;">No recent sales invoices found</p></div>
            <?php } ?>
        </div>
      </div>
    </div>
  </div>
<?php } ?>
</div>
<?php } ?>

</section>
</div>

<?php $this->load->view('footer'); ?>
<div class="control-sidebar-bg"></div>
</div>

<?php include "comman/code_js_sound.php"; ?>
<?php include "comman/code_js.php"; ?>
<script src="<?=$theme_link;?>plugins/datepicker/bootstrap-datepicker.min.js"></script>
<script src="<?php echo $theme_link; ?>plugins/chartjs/Chart.min.js"></script>

<script>
var base_url='<?= base_url(); ?>';
<?php if(is_admin() && store_module()){ ?>$("#stores_details").DataTable();<?php } ?>

function getPeriodWithDates(period){
  var now=new Date();var f=d=> (d.getMonth()+1)+'/'+d.getDate()+'/'+d.getFullYear();
  if(period==='Today')return 'Today ('+f(now)+')';
  if(period==='Yesterday'){var y=new Date(now);y.setDate(y.getDate()-1);return 'Yesterday ('+f(y)+')'}
  if(period==='This Week'){var s=new Date(now);s.setDate(now.getDate()-now.getDay()+1);var e=new Date(s);e.setDate(s.getDate()+6);return 'This Week ('+f(s)+' - '+f(e)+')'}
  if(period==='Last Week'){var s=new Date(now);s.setDate(now.getDate()-now.getDay()-6);var e=new Date(s);e.setDate(s.getDate()+6);return 'Last Week ('+f(s)+' - '+f(e)+')'}
  if(period==='This Month'){var s=new Date(now.getFullYear(),now.getMonth(),1);var e=new Date(now.getFullYear(),now.getMonth()+1,0);return 'This Month ('+f(s)+' - '+f(e)+')'}
  if(period==='Last Month'){var s=new Date(now.getFullYear(),now.getMonth()-1,1);var e=new Date(now.getFullYear(),now.getMonth(),0);return 'Last Month ('+f(s)+' - '+f(e)+')'}
  if(period==='This Year'){return 'This Year ('+now.getFullYear()+')'}
  if(period==='Last Year'){return 'Last Year ('+(now.getFullYear()-1)+')'}
  if(period==='All')return 'All Time';
  return period;
}
function get_dashboard_values(dates,from_date,to_date){
  var store_id=<?= (isset($store_id)) ? $store_id : get_current_store_id();?>;
  var post_data={store_id:store_id,dates:dates};
  if(from_date&&to_date){post_data.from_date=from_date;post_data.to_date=to_date;}
  $.post(base_url+"dashboard/dashboard_values",post_data,function(result){
    var data=jQuery.parseJSON(result);
    $.each(data,function(k,v){$("."+k).html(v);});
    $("#last_updated").text(new Date().toLocaleTimeString());
  });
}
$(function(){
  $("#current_period").text(getPeriodWithDates('Today'));
  get_dashboard_values('Today');
  $(".get_tab_records").on("click",function(){
    $(".get_tab_records").removeClass('active');$(this).addClass('active');
    $("#current_period").text(getPeriodWithDates($(this).text()));$("#last_updated").text("Updating...");
    get_dashboard_values($(this).text());
  });
  $("#custom_date_btn").on("click",function(){$("#custom_date_modal").modal('show');});
  if($.fn.datepicker){$('.datepicker').datepicker({format:'yyyy-mm-dd',autoclose:true,todayHighlight:true});}
  $("#apply_custom_date").on("click",function(){
    var f=$("#from_date").val(),t=$("#to_date").val(),re=/^\d{4}-\d{2}-\d{2}$/;
    if(!re.test(f)||!re.test(t)){alert("Use date format YYYY-MM-DD.");return;}
    $(".get_tab_records").removeClass('active');$("#custom_date_btn").addClass('active');
    var disp=(f.split('-')[1]+'/'+f.split('-')[2]+'/'+f.split('-')[0])+' to '+(t.split('-')[1]+'/'+t.split('-')[2]+'/'+t.split('-')[0]);
    $("#current_period").text("Custom ("+disp+")");$("#last_updated").text("Updating...");
    get_dashboard_values('Custom',f,t);$("#custom_date_modal").modal('hide');
  });
});
</script>

<!-- Custom Date Modal -->
<div class="modal fade" id="custom_date_modal" tabindex="-1" role="dialog" aria-labelledby="customDateModalLabel">
  <div class="modal-dialog" role="document"><div class="modal-content">
    <div class="modal-header" style="background:#22c55e;color:#06201a">
      <button type="button" class="close" data-dismiss="modal" aria-label="Close" style="color:#06201a"><span aria-hidden="true">&times;</span></button>
      <h4 class="modal-title" id="customDateModalLabel">Select Custom Date Range</h4>
    </div>
    <div class="modal-body">
      <div class="form-group"><label for="from_date">From Date</label><input type="text" class="form-control datepicker" id="from_date" placeholder="YYYY-MM-DD"></div>
      <div class="form-group"><label for="to_date">To Date</label><input type="text" class="form-control datepicker" id="to_date" placeholder="YYYY-MM-DD"></div>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-times"></i> Cancel</button>
      <button type="button" class="btn btn-success" id="apply_custom_date"><i class="fa fa-check"></i> Apply Filter</button>
    </div>
  </div></div>
</div>

<script>
<?php if(!is_user()){ ?>
(function(){
  var ctx=$(".bar-chartcanvas");
  var labels=["<?=$month[6]?>","<?=$month[5]?>","<?=$month[4]?>","<?=$month[3]?>","<?=$month[2]?>","<?=$month[1]?>","<?=$month[0]?>"];
  var purchase=["<?=$purchase[6]?>","<?=$purchase[5]?>","<?=$purchase[4]?>","<?=$purchase[3]?>","<?=$purchase[2]?>","<?=$purchase[1]?>","<?=$purchase[0]?>"];
  var sales   =["<?=$sales[6]?>","<?=$sales[5]?>","<?=$sales[4]?>","<?=$sales[3]?>","<?=$sales[2]?>","<?=$sales[1]?>","<?=$sales[0]?>"];
  var expense =["<?=$expense[6]?>","<?=$expense[5]?>","<?=$expense[4]?>","<?=$expense[3]?>","<?=$expense[2]?>","<?=$expense[1]?>","<?=$expense[0]?>"];

  function spread(arr,len){var o=[];for(var i=0;i<len;i++){o.push(arr[i%arr.length]);}return o}
  var purchaseColors=["#93c5fd","#60a5fa","#38bdf8","#a7f3d0","#fde68a","#fca5a5","#c4b5fd"];
  var salesColors   =["#22c55e","#10b981","#2dd4bf","#60a5fa","#f59e0b","#f97316","#a78bfa"];
  var expenseColors =["#ef4444","#fb7185","#f97316","#f59e0b","#eab308","#a3e635","#34d399"];

  new Chart(ctx,{type:"bar",
    data:{labels:labels,
      datasets:[
        {label:"<?= $this->lang->line('purchase'); ?>",data:purchase,backgroundColor:spread(purchaseColors,labels.length)},
        {label:"<?= $this->lang->line('sales'); ?>",data:sales,backgroundColor:spread(salesColors,labels.length)},
        {label:"<?= $this->lang->line('expense'); ?>",data:expense,backgroundColor:spread(expenseColors,labels.length)}
      ]},
    options:{responsive:true,legend:{display:true,position:"bottom"},
      scales:{yAxes:[{ticks:{beginAtZero:true}}]},tooltips:{mode:'index',intersect:false}}
  });

  new Chart(document.getElementById("doughnut-chart"),{
    type:'doughnut',
    data:{
      labels:[<?php if($tranding_item['tot_rec']>0){ for($i=$tranding_item['tot_rec'];$i>0;$i--){ ?>'<?= $tranding_item[$i]['name'] ?>',<?php } } ?>],
      datasets:[{data:[<?php if($tranding_item['tot_rec']>0){ for($i=$tranding_item['tot_rec'];$i>0;$i--){ ?>'<?= $tranding_item[$i]['sales_qty'] ?>',<?php } } ?>],
        backgroundColor:["#2563eb","#06b6d4","#22c55e","#f59e0b","#ef4444","#a855f7","#10b981","#eab308","#0ea5e9","#f97316"]}]
    },
    options:{legend:{position:'bottom'}}
  });
})();
<?php } ?>
</script>

<script>
var stockTable=null;
function buildStockDataSrc(json){
  if(typeof json==='string'){try{json=JSON.parse(json);}catch(e){return []}}
  var items=(json&&json.stock_alert_items)?json.stock_alert_items:[];
  return items.map(function(item,idx){
    var details="<strong>"+(item.item_name||'')+"</strong><br><small class='text-muted'><?= $this->lang->line('code'); ?>: "+(item.item_code||'')+"</small><br><small style='color:#0ea5e9'><?= $this->lang->line('reorder'); ?>: "+(item.reorder_needed?'<?= $this->lang->line('yes'); ?>':'<?= $this->lang->line('no'); ?>')+"</small>";
    var current="<strong style='color:#ef4444'>"+((item.current_stock!=null)?item.current_stock:'0')+"</strong>";
    var status="<span class='label label-"+(item.status_class||'danger')+"'>"+(item.stock_status||'<?= $this->lang->line('low_stock'); ?>')+"</span>";
    var actions="<div class='btn-group btn-group-xs'>"
      +"<button class='btn btn-primary btn-xs' onclick='adjustStock("+(item.item_id||0)+")' title='<?= $this->lang->line('adjust_stock'); ?>'><i class=\"fa fa-edit\"></i></button>"
      +"<button class='btn btn-success btn-xs' onclick='quickOrder("+(item.item_id||0)+")' title='<?= $this->lang->line('quick_order'); ?>'><i class=\"fa fa-shopping-cart\"></i></button>"
      +"</div>";
    return{index:idx+1,item_details:details,category_name:item.category_name||'',brand_name:item.brand_name||'',current_stock:current,alert_qty:(item.alert_qty!=null)?item.alert_qty:'',status:status,actions:actions,row_class:item.status_class||''};
  });
}
$(document).ready(function(){
  stockTable=$('#stock_alert_table').DataTable({
    paging:true,lengthChange:false,searching:true,ordering:true,info:true,autoWidth:false,pageLength:10,responsive:true,
    columnDefs:[{orderable:false,targets:7}],
    ajax:{url:base_url+"dashboard/get_enhanced_stock_alert",type:"GET",dataType:"json",dataSrc:function(json){return buildStockDataSrc(json);}},
    columns:[
      {data:'index'},{data:'item_details'},{data:'category_name'},{data:'brand_name'},
      {data:'current_stock',className:'text-center'},
      {data:'alert_qty',className:'text-center'},
      {data:'status',className:'text-center'},
      {data:'actions',className:'text-center'}
    ],
    createdRow:function(row,data){if(data.row_class){$(row).addClass(data.row_class);}}
  });
});
function refreshStockAlert(){ if(stockTable){ stockTable.ajax.reload(null,false);} }
function adjustStock(itemId){ window.location.href = base_url + "stock_adjustment?item_id=" + itemId + "&mode=adjust"; }
function quickOrder(itemId){ window.location.href = base_url + "purchase/add?item_id=" + itemId; }

// Load expiry widgets
function loadExpiryWidgets() {
    // Load expiring items
    $.ajax({
        url: base_url + 'dashboard/get_expiring_items',
        type: 'GET',
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                displayExpiringItems(response.data);
            } else {
                $('#expiring_items_widget').html('<div class="text-center text-muted">No expiring items found</div>');
            }
        },
        error: function() {
            $('#expiring_items_widget').html('<div class="text-center text-danger">Error loading expiring items</div>');
        }
    });
    
    // Load expired items
    $.ajax({
        url: base_url + 'dashboard/get_expired_items',
        type: 'GET',
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                displayExpiredItems(response.data);
            } else {
                $('#expired_items_widget').html('<div class="text-center text-muted">No expired items found</div>');
            }
        },
        error: function() {
            $('#expired_items_widget').html('<div class="text-center text-danger">Error loading expired items</div>');
        }
    });
}

function displayExpiringItems(items) {
    if (items.length === 0) {
        $('#expiring_items_widget').html('<div class="text-center text-muted">No items expiring in the next 30 days</div>');
        return;
    }
    
    var html = '<div class="table-responsive"><table class="table table-condensed">';
    html += '<thead><tr><th>Item</th><th>Batch</th><th>Expires</th><th>Qty</th></tr></thead><tbody>';
    
    items.forEach(function(item) {
        var daysClass = item.days_until_expiry <= 7 ? 'danger' : (item.days_until_expiry <= 15 ? 'warning' : 'info');
        var statusText = item.days_until_expiry <= 7 ? 'Critical' : (item.days_until_expiry <= 15 ? 'Soon' : 'Normal');
        
        html += '<tr>';
        html += '<td><strong>' + item.item_name + '</strong><br><small class="text-muted">' + item.item_code + '</small></td>';
        html += '<td>' + (item.batch_number || 'N/A') + '</td>';
        html += '<td><span class="label label-' + daysClass + '">' + item.expiry_date + '</span><br><small>' + statusText + '</small></td>';
        html += '<td class="text-center">' + item.remaining_quantity + '</td>';
        html += '</tr>';
    });
    
    html += '</tbody></table></div>';
    $('#expiring_items_widget').html(html);
}

function displayExpiredItems(items) {
    if (items.length === 0) {
        $('#expired_items_widget').html('<div class="text-center text-muted">No expired items found</div>');
        return;
    }
    
    var html = '<div class="table-responsive"><table class="table table-condensed">';
    html += '<thead><tr><th>Item</th><th>Batch</th><th>Expired</th><th>Qty</th></tr></thead><tbody>';
    
    items.forEach(function(item) {
        var daysExpired = Math.abs(item.days_until_expiry);
        
        html += '<tr class="danger">';
        html += '<td><strong>' + item.item_name + '</strong><br><small class="text-muted">' + item.item_code + '</small></td>';
        html += '<td>' + (item.batch_number || 'N/A') + '</td>';
        html += '<td><span class="label label-danger">' + item.expiry_date + '</span><br><small>Expired ' + daysExpired + ' days ago</small></td>';
        html += '<td class="text-center">' + item.remaining_quantity + '</td>';
        html += '</tr>';
    });
    
    html += '</tbody></table></div>';
    $('#expired_items_widget').html(html);
}

// Load expiry widgets when page loads
$(document).ready(function() {
    loadExpiryWidgets();
});
</script>

<script>$(".<?php echo basename(__FILE__,'.php');?>-active-li").addClass("active");</script>
</body>
</html>
