<?php
session_start();
require 'connect.php';
mysqli_query($dbC, "set @tid=0;");
date_default_timezone_set("Europe/Athens");
$filterCols = ["id", "etairia", "elegkths", "monada_paxunshs", "eidos"];
$filters = "";
// if (isset($_POST['today']) && $_POST['today'] == 'true') {
//     $filters .= " AND hm_elegxou='" . date('Y-m-d') . "'";
// }
if (isset($_POST['from']) && $_POST['from'] != "") {
    $from = date('Y-m-d', strtotime($_POST['from']));
    $filters .= " AND hm_elegxou>=\"${from}\"";
}
if (isset($_POST['to']) && $_POST['to'] != "") {
    $to = date('Y-m-d', strtotime($_POST['to']));
    $filters .= " AND hm_elegxou<=\"${to}\"";
}
if ($_SESSION['susername'] == 'sel' || $_SESSION['susername'] == 'maroudas') {
    $filters .= " AND etairia='ΣΕΛΟΝΤΑ'";
}
if ($_POST['filter'] != "") {
    $filters .= " AND (";
    foreach ($filterCols as $index => $col) {
        $filters .= ($index != 0 ? " OR " : "") . "${col} LIKE '%{$_POST['filter']}%'";
    }
    $filters .= ")";
}
$control = "control_form2";



$baseQuery = "select *, @tid:=@tid+1 as tid from ${control} WHERE isactive=1 ${filters} order by id desc";
$qry = "select * from (
            ${baseQuery}
        ) cf
        " . ($_POST['page'] > 1 ? " WHERE cf.tid>" . (($_POST['page'] - 1) * $_POST['limit']) : "") . " order by cf.tid asc limit {$_POST['limit']}";

$res = mysqli_query($dbC, $qry);
$table = "";
while ($row = mysqli_fetch_array($res)) {
    if ($row['flag'] == 1) {
        $table .= "<tr class=\"blue\">";
    } elseif (isset($row['apodekth']) && $row['apodekth'] == "0") {
        $table .= "<tr class=\"red\">";
    } else {
        $table .= "<tr>";
    }
    $table.= "
      <td>" . $row['id'] . "</td>
      <td>" . $row['etairia'] . "</td>
      <td>" . $row['elegkths'] . "</td>
      <td>" . $row['eidos'] . $row['megethos'] . "</td>
      <td>" . $row['monada_paxunshs'] . "</td>
      <td>" . date('d-m-Y', strtotime($row['hm_elegxou'])) . "</td>
      <td>" . (empty($row['picture']) ? '' : '<img src="img/img.png" height="25px" />') . "</td>
      <td>
      <div class='btn-group'>
      <button class='btn btn-default' onclick=\"document.location = 'control2.php?type=view&id=" . $row['id'] . "';\">View</button> ";
    $table.= "</div></td></tr>";

}
$numPages = ceil(mysqli_num_rows(mysqli_query($dbC, $baseQuery)) / $_POST['limit']);
echo json_encode(["table" => $table, "numPages" => $numPages, "qry"=>$qry]);
?>