<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once 'dbcon.php';

$nm_mask = $_GET['nm_mask'] ?? "";

// WHERE condition
$where = "WHERE cycle_activt <> '2'";

if($nm_mask!='') {
    $where .= " AND (pat_mrn LIKE '%$nm_mask%' 
                OR pat_name LIKE '%$nm_mask%' 
                OR part_name LIKE '%$nm_mask%')";
}

// Paging
$page  = $_GET['page'] ?? 1;
$limit = $_GET['rows'] ?? 15;
$sidx  = $_GET['sidx'] ?? 'chn_id';
$sord  = $_GET['sord'] ?? 'DESC';

// Count
$result = mysqli_query($conn, "SELECT COUNT(*) AS count FROM cycle_lst $where");
$row = mysqli_fetch_assoc($result);
$count = $row['count'];

$total_pages = ($count > 0) ? ceil($count/$limit) : 0;
if ($page > $total_pages) $page = $total_pages;

$start = ($page - 1) * $limit;
if ($start < 0) $start = 0;

// Main query
$SQL = "SELECT * FROM cycle_lst $where ORDER BY chn_id DESC LIMIT $start, $limit";
$result = mysqli_query($conn, $SQL);

// Response
$response = new stdClass();
$response->page = $page;
$response->total = $total_pages;
$response->records = $count;

$i = 0;
while($row = mysqli_fetch_assoc($result)) {

    // icons
// VERIFIED
$verfied = "";
if($row['x1stopd'] == "0") {
    $verfied = "-"; // or show default icon
} elseif(in_array($row['x1stopd'], ['1','2','3','4','5'])) {
    $verfied = "<img src='images/ews-verified-logo-list.jpg' width='20'>";
} elseif(in_array($row['x1stopd'], ['6','7','8'])) {
    $verfied = "<img src='images/ews-verified-logo-list-noncompl.jpg' width='20'>";
} elseif($row['x1stopd']=="9") {
    $verfied = "<img src='images/ews-verified-logo-list-noyags.jpg' width='20'>";
} elseif($row['x1stopd']=="10") {
    $verfied = "<img src='images/ews-cyccancelled.jpg' width='20'>";
}

// CYCLE CLOSE
$cycleclose = ($row['cycle_activt'] == "1") 
    ? "<img src='images/ews-cycleclose-logo.jpg' width='20'>" 
    : "-";

// CONSUME/DISCARD
$consumediscrd = ($row['x1allfz'] == "1") 
    ? "<img src='images/ews-cycleclose-logo.jpg' width='20'>" 
    : "-";

    $cycle_date = !empty($row['cycle_strtd']) ? date('d/m/Y', strtotime($row['cycle_strtd'])) : '';

    $response->rows[$i]['id'] = $row['cnh']; // FIXED

    $response->rows[$i]['cell'] = [
        $cycleclose,
        $verfied,
        $consumediscrd,
        "<a href='gend_cycle_select.php?chn=".$row['pat_mrn']."'>".$row['pat_mrn']."</a>",
        $cycle_date,
        $row['cycle_type'],
        $row['pat_name'],
        $row['part_name']
    ];

    $i++;
}

echo json_encode($response);
?>