<!DOCTYPE html>
<html>
<head>
<!-- TABLES CSS CODE -->
<?php include"comman/code_css.php"; ?>
<!-- </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;?>
        <small></small>
      </h1>
      <ol class="breadcrumb">
        <li><a href="<?php echo $base_url; ?>dashboard"><i class="fa fa-dashboard"></i> Home</a></li>
        <li class="active"><?=$page_title;?></li>
      </ol>
    </section>

    <!-- /.content -->
    <section class="content">
      <div class="row">
        <div class="col-md-12">
                     <!-- Horizontal Form -->
                     <div class="box box-primary">
                        <div class="box-header with-border">
                           <h3 class="box-title">Please Enter Valid Information</h3>
                        </div>
                        <!-- /.box-header -->
                        <!-- form start -->
                        <form class="form-horizontal" id="report-form" onkeypress="return event.keyCode != 13;">
                           <input type="hidden" name="<?php echo $this->security->get_csrf_token_name();?>" value="<?php echo $this->security->get_csrf_hash();?>">
                           <input type="hidden" id="base_url" value="<?php echo $base_url; ?>">
                           <div class="box-body">
                              <div class="form-group">
                                 <label for="filter_type" class="col-sm-2 control-label">Filter By</label>
                                 <div class="col-sm-3">
                                    <select class="form-control" id="filter_type" name="filter_type">
                                       <option value="all">All Items</option>
                                       <option value="expiring">Expiring (Next 30 Days)</option>
                                       <option value="expired">Expired Items</option>
                                       <option value="critical">Critical (Next 7 Days)</option>
                                    </select>
                                 </div>
                                 
                                 <label for="from_date" class="col-sm-2 control-label">From Date</label>
                                 <div class="col-sm-3">
                                    <input type="text" class="form-control datepicker" id="from_date" name="from_date" placeholder="From Date" value="">
                                 </div>
                              </div>
                              
                              <div class="form-group">
                                 <label for="to_date" class="col-sm-2 control-label">To Date</label>
                                 <div class="col-sm-3">
                                    <input type="text" class="form-control datepicker" id="to_date" name="to_date" placeholder="To Date" value="">
                                 </div>
                              </div>
                           </div>
                           <!-- /.box-body -->
                           <div class="box-footer">
                              <div class="col-sm-8 col-sm-offset-2 text-center">
                                 <div class="col-md-2 col-md-offset-2">
                                    <button type="button" id="view" class="btn btn-block btn-success" title="Show Report">Show</button>
                                 </div>
                                 <div class="col-sm-2">
                                    <button type="button" class="btn btn-block btn-info" onclick="exportToExcel()" title="Export Excel">
                                       <i class="fa fa-file-excel-o"></i> Excel
                                    </button>
                                 </div>
                                 <div class="col-sm-2">
                                    <button type="button" class="btn btn-block btn-danger" onclick="exportToPDF()" title="Export PDF">
                                       <i class="fa fa-file-pdf-o"></i> PDF
                                    </button>
                                 </div>
                                 <div class="col-sm-2">
                                    <a href="<?=base_url('dashboard');?>">
                                    <button type="button" class="btn btn-block btn-warning close_btn" title="Go Dashboard">Close</button>
                                    </a>
                                 </div>
                              </div>
                           </div>
                           <!-- /.box-footer -->
                        </form>
                     </div>
                     <!-- /.box -->
                  </div>

                  <div class="col-md-12">
                     <!-- Custom Tabs -->
                     <div class="nav-tabs-custom">
                       
                        <ul class="nav nav-tabs">
                           <li class="active"><a href="#tab_1" data-toggle="tab">All Items</a></li>
                           <li><a href="#tab_2" data-toggle="tab">Expiring (Next 30 Days)</a></li>
                           <li><a href="#tab_3" data-toggle="tab">Expired Items</a></li>
                           <li><a href="#tab_4" data-toggle="tab"><i class="fa fa-exclamation-triangle text-danger"></i> Critical (Next 7 Days)</a></li>
                        </ul>
                        <div class="tab-content">
                           <div class="tab-pane active" id="tab_1">
                            <div class="table-responsive">
                              <table id="expiry_report_table" class="table table-bordered table-striped">
                                <thead>
                                  <tr>
                                    <th>Item Name</th>
                                    <th>Item Code</th>
                                    <th>Batch Number</th>
                                    <th>Manufacturing Date</th>
                                    <th>Expiry Date</th>
                                    <th>Days to Expiry</th>
                                    <th>Available Stock</th>
                                    <th>Status</th>
                                    <th>Store</th>
                                  </tr>
                                </thead>
                                <tbody>
                                  <!-- Data will be loaded via AJAX -->
                                </tbody>
                              </table>
                            </div>
                           </div>
                           <div class="tab-pane" id="tab_2">
                            <div class="table-responsive">
                              <table id="expiring_table" class="table table-bordered table-striped">
                                <thead>
                                  <tr>
                                    <th>Item Name</th>
                                    <th>Item Code</th>
                                    <th>Batch Number</th>
                                    <th>Manufacturing Date</th>
                                    <th>Expiry Date</th>
                                    <th>Days to Expiry</th>
                                    <th>Available Stock</th>
                                    <th>Status</th>
                                    <th>Store</th>
                                  </tr>
                                </thead>
                                <tbody>
                                  <!-- Data will be loaded via AJAX -->
                                </tbody>
                              </table>
                            </div>
                           </div>
                           <div class="tab-pane" id="tab_3">
                            <div class="table-responsive">
                              <table id="expired_table" class="table table-bordered table-striped">
                                <thead>
                                  <tr>
                                    <th>Item Name</th>
                                    <th>Item Code</th>
                                    <th>Batch Number</th>
                                    <th>Manufacturing Date</th>
                                    <th>Expiry Date</th>
                                    <th>Days to Expiry</th>
                                    <th>Available Stock</th>
                                    <th>Status</th>
                                    <th>Store</th>
                                  </tr>
                                </thead>
                                <tbody>
                                  <!-- Data will be loaded via AJAX -->
                                </tbody>
                              </table>
                            </div>
                           </div>
                           <div class="tab-pane" id="tab_4">
                            <div class="table-responsive">
                              <table id="critical_table" class="table table-bordered table-striped">
                                <thead>
                                  <tr>
                                    <th>Item Name</th>
                                    <th>Item Code</th>
                                    <th>Batch Number</th>
                                    <th>Manufacturing Date</th>
                                    <th>Expiry Date</th>
                                    <th>Days to Expiry</th>
                                    <th>Available Stock</th>
                                    <th>Status</th>
                                    <th>Store</th>
                                  </tr>
                                </thead>
                                <tbody>
                                  <!-- Data will be loaded via AJAX -->
                                </tbody>
                              </table>
                            </div>
                           </div>
                        </div>
                     </div>
                  </div>
      </div>
    </section>
    <!-- /.content -->
  </div>
  <!-- /.content-wrapper -->
</div>

<?php include"comman/code_js.php"; ?>

<script>
var expiryTable, expiringTable, expiredTable, criticalTable;

$(document).ready(function() {
    // Initialize date pickers
    $('.datepicker').datepicker({
        autoclose: true,
        format: 'dd-mm-yyyy',
        todayHighlight: true
    });
    
    // Initialize DataTables for each tab
    expiryTable = $('#expiry_report_table').DataTable({
        "processing": true,
        "serverSide": false,
        "paging": true,
        "lengthChange": true,
        "searching": true,
        "ordering": true,
        "info": true,
        "autoWidth": false,
        "pageLength": 25,
        "order": [[5, "asc"]]
    });
    
    expiringTable = $('#expiring_table').DataTable({
        "processing": true,
        "serverSide": false,
        "paging": true,
        "lengthChange": true,
        "searching": true,
        "ordering": true,
        "info": true,
        "autoWidth": false,
        "pageLength": 25,
        "order": [[5, "asc"]]
    });
    
    expiredTable = $('#expired_table').DataTable({
        "processing": true,
        "serverSide": false,
        "paging": true,
        "lengthChange": true,
        "searching": true,
        "ordering": true,
        "info": true,
        "autoWidth": false,
        "pageLength": 25,
        "order": [[5, "asc"]]
    });
    
    criticalTable = $('#critical_table').DataTable({
        "processing": true,
        "serverSide": false,
        "paging": true,
        "lengthChange": true,
        "searching": true,
        "ordering": true,
        "info": true,
        "autoWidth": false,
        "pageLength": 25,
        "order": [[5, "asc"]]
    });
    
    // Show button click handler
    $('#view').click(function() {
        loadExpiryReport();
    });
    
    // Load initial data
    loadExpiryReport();
});

function loadExpiryReport() {
    var filterType = $('#filter_type').val();
    var fromDate = $('#from_date').val();
    var toDate = $('#to_date').val();
    
    // Clear all tables
    expiryTable.clear().draw();
    expiringTable.clear().draw();
    expiredTable.clear().draw();
    criticalTable.clear().draw();
    
    $.ajax({
        url: base_url + 'reports/get_expiry_report_data',
        type: 'POST',
        data: {
            filter_type: filterType,
            from_date: fromDate,
            to_date: toDate
        },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                var allData = [];
                var expiringData = [];
                var expiredData = [];
                var criticalData = [];
                
                response.data.forEach(function(item) {
                    var statusClass = '';
                    var statusText = '';
                    var daysClass = '';
                    
                    if (item.days_until_expiry < 0) {
                        statusClass = 'danger';
                        statusText = 'Expired';
                        daysClass = 'text-danger';
                        expiredData.push(formatRowData(item, statusClass, statusText, daysClass));
                    } else if (item.days_until_expiry <= 7) {
                        statusClass = 'danger';
                        statusText = 'Critical';
                        daysClass = 'text-danger';
                        criticalData.push(formatRowData(item, statusClass, statusText, daysClass));
                    } else if (item.days_until_expiry <= 30) {
                        statusClass = 'warning';
                        statusText = 'Soon';
                        daysClass = 'text-warning';
                        expiringData.push(formatRowData(item, statusClass, statusText, daysClass));
                    } else {
                        statusClass = 'success';
                        statusText = 'Good';
                        daysClass = 'text-success';
                    }
                    
                    allData.push(formatRowData(item, statusClass, statusText, daysClass));
                });
                
                // Populate tables
                expiryTable.rows.add(allData).draw();
                expiringTable.rows.add(expiringData).draw();
                expiredTable.rows.add(expiredData).draw();
                criticalTable.rows.add(criticalData).draw();
            } else {
                alert('Error loading expiry report: ' + response.message);
            }
        },
        error: function() {
            alert('Error loading expiry report data');
        }
    });
}

function formatRowData(item, statusClass, statusText, daysClass) {
    return [
        '<strong>' + item.item_name + '</strong>',
        item.item_code || 'N/A',
        item.batch_number || 'N/A',
        item.manufacturing_date ? formatDate(item.manufacturing_date) : 'N/A',
        item.expiry_date ? formatDate(item.expiry_date) : 'N/A',
        '<span class="' + daysClass + '"><strong>' + item.days_until_expiry + '</strong></span>',
        '<span class="text-primary"><strong>' + item.remaining_quantity + '</strong></span>',
        '<span class="label label-' + statusClass + '">' + statusText + '</span>',
        item.store_name || 'N/A'
    ];
}

function formatDate(dateString) {
    if (!dateString || dateString === '0000-00-00') return 'N/A';
    
    var parts = dateString.split('-');
    if (parts.length === 3) {
        return parts[2] + '-' + parts[1] + '-' + parts[0]; // DD-MM-YYYY
    }
    return dateString;
}

function exportToExcel() {
    var filterType = $('#filter_type').val();
    var fromDate = $('#from_date').val();
    var toDate = $('#to_date').val();
    
    var url = base_url + 'reports/export_expiry_excel?filter_type=' + filterType;
    if (fromDate) url += '&from_date=' + fromDate;
    if (toDate) url += '&to_date=' + toDate;
    
    window.open(url, '_blank');
}

function exportToPDF() {
    var filterType = $('#filter_type').val();
    var fromDate = $('#from_date').val();
    var toDate = $('#to_date').val();
    
    var url = base_url + 'reports/export_expiry_pdf?filter_type=' + filterType;
    if (fromDate) url += '&from_date=' + fromDate;
    if (toDate) url += '&to_date=' + toDate;
    
    window.open(url, '_blank');
}
</script>

<!-- Make sidebar menu highlighter/selector -->
<script>$(".<?php echo basename(__FILE__,'.php');?>-active-li").addClass("active");</script>
</body>
</html>