<link rel="stylesheet" href="css/new_mxerp.css">
<?php
$PageSecurity = 2;
$title = _('View/Search Items');
include('includes/SQL_CommonFunctions.inc');
$_SESSION['modid'] = $_REQUEST['modid'];
$_SESSION['frmid'] = $_REQUEST['frmid'];
$frmpermission = $px->GetFileAccess($_SESSION['modid'], $_SESSION['frmid'], $_SESSION['ACGRoleId']);
$_SESSION['frmAdd'] = $frmpermission[0];
$_SESSION['frmEdit'] = $frmpermission[1];
$_SESSION['frmDelete'] = $frmpermission[2];
$_SESSION['frmView'] = $frmpermission[3];
$recordsPerPage = 100;
$currentPage = isset($_REQUEST['item_page']) ? max(1, (int) $_REQUEST['item_page']) : 1;
$offset = ($currentPage - 1) * $recordsPerPage;

?>
<script language="javascript" type="text/javascript">
  function get_itemsubgroup(str) {
    if (str == "") {
      document.getElementById("sub_id").innerHTML = "";
      return;
    }
    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp = new XMLHttpRequest();
    } else { // code for IE6, IE5
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        document.getElementById("sub_id").innerHTML = xmlhttp.responseText;
      }
    }
    xmlhttp.open("GET", "item_subcategory.php?q=" + str, true);
    xmlhttp.send();
  }
</script>

<?php
if ($_REQUEST['id'] != '' && $_REQUEST['action'] == 'delete') {
  $delete_sql = "delete from item_master where id='" . $_REQUEST['id'] . "'";
  $d_res = DB_query($delete_sql, $db);

  if ($_REQUEST['item_cat'] == 'FG') {
    $delete_color = "Delete from item_color_master where item_master_id ='" . $_REQUEST['id'] . "'";
    $r_res = DB_query($delete_color, $db);
  }
  echo "<script>location.href='index.php?route=item_list&modid=" . $_REQUEST['modid'] . "&frmid=" . $_REQUEST['frmid'] . "'</script>";
}
if ($_REQUEST['search']) {


  $filter = array();

  if ($_REQUEST['main_group'] != '000')
    $filter[] = "CategoryID = '" . $_REQUEST['main_group'] . "'";
  if ($_REQUEST['sub_group'] != '000')
    $filter[] = "SubCategoryID = '" . $_REQUEST['sub_group'] . "'";
  if ($_REQUEST['item_code'] != '')
    $filter[] = "StockID like '%" . $_REQUEST['item_code'] . "%'";
  if ($_REQUEST['item_name'] != '')
    $filter[] = "item_name like '%" . $_REQUEST['item_name'] . "%'";
  if ($_REQUEST['generic_name'] != '')
    $filter[] = "generic_name like '%" . $_REQUEST['generic_name'] . "%'";

  // if ($_REQUEST['salt_name'] != '') {
  //   //     echo "<pre>";
  //   // print_r($_REQUEST); exit();
  //   $filterQue = " itemgenerics.generic_code like '%" . $_REQUEST['salt_name'] . "%' OR itemgenerics.generic_desc like '%" . $_REQUEST['salt_name'] . "%' group by itemforms_id";


  //   $mdb   = mysqli_connect('127.0.0.1', 'root', '123456', 'hmis_amch');
  //   //  echo "<pre>";
  //   //  print_r($_SESSION); die;
  //   $item_code = "";

  //    $getsql = $mdb->query("SELECT itemforms.item_code
  //   FROM itemgenerics
  //   INNER JOIN itemforms ON itemforms.id = itemgenerics.itemforms_id
  //   WHERE $filterQue");

  //   if ($getsql && $getsql->num_rows > 0) {
  //     $codes = [];

  //     while ($row = $getsql->fetch_assoc()) {
  //       $codes[] = "'" . $row['item_code'] . "'";
  //     }

  //     $item_code = implode(',', $codes);
  //     $filter[] = "StockID IN ($item_code)";
  //   }
  // }

  if (!empty($filter)) {
    $filter1 = implode(" and ", $filter);
    $whereClause = "$filter1 and CompanyId='" . $_SESSION['ACGCompanyId'] . "'";
  } else {
    $whereClause = "CompanyId='" . $_SESSION['ACGCompanyId'] . "'";
  }
} else {
  $whereClause = "CompanyId='" . $_SESSION['ACGCompanyId'] . "'";
}
$fullSql = "select * from item_master where " . $whereClause . " order by id desc";
$_SESSION['item_query1'] = $fullSql;
$countSql = "select count(*) as total_records from item_master where " . $whereClause;
$countResult = DB_query($countSql, $db);
$countRow = DB_fetch_array($countResult);
$totalRecords = (int) $countRow['total_records'];
$totalPages = max(1, (int) ceil($totalRecords / $recordsPerPage));
if ($currentPage > $totalPages) {
  $currentPage = $totalPages;
  $offset = ($currentPage - 1) * $recordsPerPage;
}
$sql = $fullSql . " LIMIT " . $offset . "," . $recordsPerPage;

$paginationParams = array(
  'route' => 'item_list',
  'modid' => $_REQUEST['modid'],
  'frmid' => $_REQUEST['frmid']
);
if (!empty($_REQUEST['search'])) {
  $paginationParams['search'] = $_REQUEST['search'];
}
if (isset($_REQUEST['main_group']) && $_REQUEST['main_group'] !== '') {
  $paginationParams['main_group'] = $_REQUEST['main_group'];
}
if (isset($_REQUEST['sub_group']) && $_REQUEST['sub_group'] !== '') {
  $paginationParams['sub_group'] = $_REQUEST['sub_group'];
}
if (isset($_REQUEST['item_code']) && $_REQUEST['item_code'] !== '') {
  $paginationParams['item_code'] = $_REQUEST['item_code'];
}
if (isset($_REQUEST['item_name']) && $_REQUEST['item_name'] !== '') {
  $paginationParams['item_name'] = $_REQUEST['item_name'];
}
if (isset($_REQUEST['generic_name']) && $_REQUEST['generic_name'] !== '') {
  $paginationParams['generic_name'] = $_REQUEST['generic_name'];
}

?>

<div class="body_contain">
  <div class="tab_div">

    <h1>ITEMS</h1>
    <form action="" method="get">
      <input type="hidden" name="route" value="item_list" />
      <input type="hidden" name="modid" value="<?php echo $_REQUEST['modid']; ?>" />
      <input type="hidden" name="frmid" value="<?php echo $_REQUEST['frmid']; ?>" />
      <table width="100%" border="0" cellpadding="3" cellspacing="0" align="center">
        <tr class="row1">
          <td width="13%" align="right">Main Group</td>
          <td width="35%"><select name="main_group" id="main_group" onchange="get_itemsubgroup(this.value)">
              <option value="000">---Select---</option>
              <?php
              $query1 = DB_query("select * from stockmaincategory  where CompanyId='" . $_SESSION['ACGCompanyId'] . "'", $db);
              while ($result1 = DB_fetch_array($query1)) {
              ?>
                <option value="<?php echo $result1['id']; ?>" <?php echo ($_REQUEST['main_group'] == $result1['id'] ? 'selected' : '') ?>><?php echo $result1['stockmaincategoryname']; ?></option>
              <?php } ?>
            </select></td>
          <td width="13%" align="right">Item Code</td>
          <td><input type="text" name="item_code" id="item_code" value="<?php echo $_REQUEST['item_code']; ?>" /></td>
        </tr>
        <tr class="row1">
          <td align="right">Sub Group</td>
          <td>
            <div id="sub_id"><select name="sub_group" id="sub_group">
                <option value="000">---Select---</option>
                <?php
                if ($_REQUEST['main_group']) {
                  $query2 = DB_query("select * from stockcategory where stockmaincategory='" . $_REQUEST['main_group'] . "'", $db);
                } else {
                  $query2 = DB_query("select * from stockcategory", $db);
                }
                while ($result2 = DB_fetch_array($query2)) {
                ?>
                  <option value="<?php echo $result2['id']; ?>" <?php echo ($_REQUEST['sub_group'] == $result2['id'] ? 'selected' : '') ?>><?php echo $result2['categorydescription']; ?></option>
                <?php } ?>
              </select></div>
          </td>
          <td align="right">Item Name</td>
          <td><input type="text" name="item_name" id="item_name" placeholder="Search by Item Name" value="<?php echo $_REQUEST['item_name']; ?>" /></td>
        </tr>
        <tr class="row1">
          <td align="right">Generic Name</td>
          <td><input type="text" name="generic_name" id="generic_name" placeholder="Search by Generic Name" value="<?php echo $_REQUEST['generic_name']; ?>" /></td>
          <td colspan="2">&nbsp;</td>
        </tr>
        <!-- <td align="right">Salt Name</td>
        <td><input type="text" name="salt_name" id="salt_name" placeholder="Search by Salt Name" value="<?php echo $_REQUEST['salt_name']; ?>" /></td> -->

        <tr class="row1">
          <td colspan="4" align="center"><input type="submit" name="search" class="search" value="Search" /></td>
        </tr>
      </table>

    </form>
    <p align="left">
      <?php if ($_SESSION['frmAdd'] == '1') { ?>

        <a href="index.php?route=crm_item_master&modid=<?php echo $_REQUEST['modid']; ?>&frmid=<?php echo $_REQUEST['frmid']; ?>" style="text-decoration:none;"><input type='button' value='Add New' class="search" /></a><?php } ?>

      <a href="itemlistprint.php" style="text-decoration:none;"><input type='button' value='Print' class="search" /></a>
    </p>

    <form action="" method="post">

      <table width="100%" border="0" cellpadding="3" cellspacing="0" class="thborder">
        <tr>
          <th width="10%">Item Code</th>
          <th width="10%">Item Name</th>
          <th width="18%">Generic Name</th>
          <th width="12%">Main Category</th>
          <th width="12%">Sub Category</th>
          <th width="5%" style="text-align:center;">View</th>
          <th width="5%" style="text-align:center;">Edit</th>
          <!-- <th width="5%" style="text-align:center;">Delete</th> -->
        </tr>
        <?php
        $result = DB_query($sql, $db);
        $i = 1;
        if (DB_num_rows($result) > 0) {
          while ($myrow = DB_fetch_array($result)) {
        ?>
            <tr>
              <td><?php echo $myrow['StockID']; ?></td>
              <td><?php echo $myrow['item_name']; ?></td>
              <td><?php echo $myrow['generic_name']; ?></td>
              <td><?php
                  $main_sql = DB_query("select stockmaincategoryname from stockmaincategory where id='" . $myrow['CategoryID'] . "'", $db);
                  $main_res = DB_fetch_array($main_sql);
                  echo $main_res['stockmaincategoryname']; ?></td>
              <td><?php
                  $Sub_sql = DB_query("select categorydescription from stockcategory where id='" . $myrow['SubCategoryID'] . "'", $db);
                  $sub_res = DB_fetch_array($Sub_sql);
                  echo $sub_res['categorydescription']; ?></td>
              <td style="text-align:center;"><?php if ($_SESSION['frmView'] == '1') { ?><a href="index.php?route=crm_item_master&modid=<?php echo $_REQUEST['modid']; ?>&frmid=<?php echo $_REQUEST['frmid']; ?>&id=<?php echo $myrow['id']; ?>&action=view"><img src="images/search.png" width="15" height="15" title="View Document" /></a><?php } else { ?><img src="images/search.png" width="15" height="15" title="No Permission to View Document" style="opacity:0.5;" /><?php } ?></td>
              <td style="text-align:center;"><?php if ($_SESSION['frmEdit'] == '1') { ?><a href="index.php?route=crm_item_master&<?php echo $rurl; ?>&id=<?php echo $myrow['id']; ?>&action=edit"><img src="images/icon-edit.png" width="15" height="15" title="Edit Document" /></a><?php } else { ?><img src="images/icon-edit.png" width="15" height="15" title="No Permission to Edit Document" style="opacity:0.5;" /><?php } ?></td>
              <!-- <td style="text-align:center;"><?php //if($_SESSION['frmDelete']=='1'){
                                                  ?><a href="index.php?route=item_list&<?php  //echo $rurl;
                                                                                        ?>&id=<?php //echo $myrow['id'];
                                                                                              ?>&action=delete" onClick="return confirm('Are you sure you want to delete this Item record?');"><img src="images/Icon_Delete.png"  width="15" height="15" title="Delete Document" /></a><?php //} else{ 
                                                                                                                                                                                                                                                                                        ?><img src="images/Icon_Delete.png"  width="15" height="15" title="No Permission to Delete Document" style="opacity:0.5;" /><?php //}
                                                                                                                                                                                                                                                                                                                                                                                                                                                            ?></td> -->
            </tr>
          <?php $i++;
          }
        } else { ?>
          <tr>
            <td colspan="7" align="center">
              <font color="#FF0000">No Record Found!</font>
            </td>
          </tr>
        <?php
        } ?>
      </table>

      <?php if ($totalRecords > 0) { ?>
        <div style="margin-top:10px; text-align:center;">
          <?php
          $startRecord = $offset + 1;
          $endRecord = min($offset + $recordsPerPage, $totalRecords);
          echo "Showing " . $startRecord . " to " . $endRecord . " of " . $totalRecords . " records";
          ?>
        </div>
      <?php } ?>

      <?php if ($totalPages > 1) { ?>
        <div style="margin-top:10px; text-align:center;">
          <?php
          if ($currentPage > 1) {
            $firstPageParams = $paginationParams;
            $firstPageParams['item_page'] = 1;
            $prevPageParams = $paginationParams;
            $prevPageParams['item_page'] = $currentPage - 1;
            echo '<a class="search" style="padding:4px 8px; text-decoration:none;" href="index.php?' . htmlspecialchars(http_build_query($firstPageParams), ENT_QUOTES) . '">First</a> ';
            echo '<a class="search" style="padding:4px 8px; text-decoration:none;" href="index.php?' . htmlspecialchars(http_build_query($prevPageParams), ENT_QUOTES) . '">Previous</a> ';
          }

          $pageWindowStart = max(1, $currentPage - 2);
          $pageWindowEnd = min($totalPages, $currentPage + 2);

          for ($pageNo = $pageWindowStart; $pageNo <= $pageWindowEnd; $pageNo++) {
            $pageParams = $paginationParams;
            $pageParams['item_page'] = $pageNo;
            if ($pageNo == $currentPage) {
              echo '<strong style="padding:4px 8px;">' . $pageNo . '</strong> ';
            } else {
              echo '<a class="search" style="padding:4px 8px; text-decoration:none;" href="index.php?' . htmlspecialchars(http_build_query($pageParams), ENT_QUOTES) . '">' . $pageNo . '</a> ';
            }
          }

          if ($currentPage < $totalPages) {
            $nextPageParams = $paginationParams;
            $nextPageParams['item_page'] = $currentPage + 1;
            $lastPageParams = $paginationParams;
            $lastPageParams['item_page'] = $totalPages;
            echo '<a class="search" style="padding:4px 8px; text-decoration:none;" href="index.php?' . htmlspecialchars(http_build_query($nextPageParams), ENT_QUOTES) . '">Next</a> ';
            echo '<a class="search" style="padding:4px 8px; text-decoration:none;" href="index.php?' . htmlspecialchars(http_build_query($lastPageParams), ENT_QUOTES) . '">Last</a>';
          }
          ?>
        </div>
      <?php } ?>

    </form>
  </div>
</div>




<?php
//include('includes/footer.inc');
?>
