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

require_once 'dbcon.php';

$nm_mask = isset($_GET["nm_mask"]) ? $_GET['nm_mask'] : "";

$where = "WHERE 1=1 AND 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%')";
}

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

$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 = $limit * ($page - 1);
if ($start < 0) $start = 0;

$SQL = "SELECT * FROM cycle_lst $where ORDER BY $sidx $sord LIMIT $start, $limit";
$result = mysqli_query($conn, $SQL);

$responce = new stdClass();
$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;

$i = 0;

while($row = mysqli_fetch_assoc($result)) {

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

    $responce->rows[$i]['id'] = $row['chn_id'];

    $responce->rows[$i]['cell'] = array(
        "<a href='gend_cycle_select.php?chn=".$row['pat_mrn']."'>".$row['pat_mrn']."</a>",
        $date,
        $row['cycle_type'],
        $row['pat_name'],
        $row['part_name']
    );

    $i++;
}

echo json_encode($responce);
?>