<?php //itemSummary_functions.php
if(file_exists('../../../'.$_REQUEST['tenant'].'/config.php')){require_once('../../../'.$_REQUEST['tenant'].'/config.php');}
if(file_exists('/config.php')){require_once('/config.php');}

if(!empty($_REQUEST['locnumber'])){$filter="AND `locnumber`='".$_REQUEST['locnumber']."'";}

 function getFreq($code){
            $iucSql  = mysqli_query($GLOBALS['con'],"SELECT `units`,`frequency` FROM `dd_plant` WHERE `code` = '". $code."'")or die(mysqli_error($GLOBALS['con']));          
            $iuc     = mysqli_fetch_array($iucSql);
            return $iuc['frequency'];
        }

        function getUnit($code){
            $iucSql  = mysqli_query($GLOBALS['con'],"SELECT `units`,`frequency` FROM `dd_plant` WHERE `code` = '". $code."'")or die(mysqli_error($GLOBALS['con']));          
            $iuc     = mysqli_fetch_array($iucSql);
            return $iuc['units'];
        }
switch($_REQUEST['FCN']){
    default:break;

case "load":$client    = mysqli_real_escape_string($con, $_REQUEST['clientnumber']);
$locfilter = "";
if (!empty($_REQUEST['locnumber'])) {
    $loc = mysqli_real_escape_string($con, $_REQUEST['locnumber']);
    $locfilter = " AND `locnumber` = '{$loc}'";
}

    // 1) Convert the incoming dd-mm-yyyy into UNIX timestamps:
    $startDt = DateTime::createFromFormat('d-m-Y', $_REQUEST['start']);
    $endDt   = DateTime::createFromFormat('d-m-Y', $_REQUEST['end']);
    $start   = $startDt->getTimestamp();
    $end     = $endDt->getTimestamp();

    // 2) Fetch your distinct items exactly as before:
    $sql = "
      SELECT `desc`,`code`
        FROM `itemdetails`
       WHERE `clientnumber` = '{$client}'
         {$locfilter}
         AND `statuslive` = 1
         AND `currdate` BETWEEN {$start} AND {$end}
       GROUP BY `desc`,`code`
    ";
    $res = mysqli_query($GLOBALS['con'], $sql) or die(mysqli_error($GLOBALS['con']));
    if (mysqli_num_rows($res) === 0) {
        echo '<p class="text-center mt-4 alert alert-warning text-center w-100 m-0" style="width:100% !important">No Results for the date period <b>'.$_REQUEST['start'].'</b> to <b>'.$_REQUEST['end'].'</b></p>';
      
        exit;
    }

    // 3) Build your table header…
    $html  = '<div class="table-responsive w-100">';
    $html .= '<table id="tableData" class="table table-striped table-sm mt-4" style="width:100% !important; table-layout: fixed;">';
    $html .= '<thead class="table-dark"><tr>
                <th>Item</th><th>Code</th><th>Count</th><th>Frequency</th>
              </tr></thead><tbody>';

    $totalCount = 0;
    while ($row = mysqli_fetch_assoc($res)) {
        $descRaw  = $row['desc'];
        $descSql  = mysqli_real_escape_string($GLOBALS['con'], $descRaw);
        $descHtml = htmlspecialchars($descRaw, ENT_QUOTES, 'UTF-8');

        // 4) Now count using integer BETWEEN
        $cntSql = "
          SELECT COUNT(*) AS cnt
            FROM `itemdetails`
           WHERE `clientnumber` = '{$client}'
             {$locfilter}
             AND `statuslive` = 1
             AND `desc` = '{$descSql}'
             AND `currdate` BETWEEN {$start} AND {$end}
        ";
        $cntRes = mysqli_query($GLOBALS['con'], $cntSql) or die(mysqli_error($GLOBALS['con']));
        $count  = (int)mysqli_fetch_assoc($cntRes)['cnt'];

        if ($count > 0) {
            $freq = htmlspecialchars(getFreq($row['code']), ENT_QUOTES, 'UTF-8');
            $html .= "<tr>
                        <td>{$descHtml}</td>
                        <td>{$row['code']}</td>
                        <td>{$count}</td>
                        <td>{$freq}</td>
                      </tr>";
            $totalCount += $count;
        }
    }

    // 5) Close out tbody, add tfoot, and wrap-up
    $html .= "</tbody>
              <tfoot class=\"bg-info text-white\">
                <tr>
                  <th colspan=\"2\"></th>
                  <td>{$totalCount}</td>
                  <th></th>
                </tr>
              </tfoot>
             </table></div>";

    echo $html;
    break;



}


?>