<?php
include("../db.php");
$requestData = $_REQUEST;
$columns = array(
    0 => 'name_pro',
    1 => 'name_cat',
);
$cat = $_POST['dataTableSend'][0] ?? 0;
$pro = $_POST['dataTableSend'][1] ?? 0;

if ($cat != 0) {
    $addYear = " and `cat`.`id_cat` = '$cat' ";
} else {
    $addYear = " ";
}
if ($pro != 0) {
    $addSubscription = " and `pro`.`id_pro` = '$pro' ";
} else {
    $addSubscription = " ";
}

$sql = "SELECT * FROM  `pro` 
left join `cat` on  `cat`.`id_cat` = `pro`.`id_cat` 
where  `pro`.`id_user` = '$idPublicUser' " . $addYear . $addSubscription;

$query = mysqli_query($db, $sql);
$totalData = mysqli_num_rows($query);
$totalFiltered = $totalData;
$sql = "SELECT * FROM  `pro` 
left join `cat` on  `cat`.`id_cat` = `pro`.`id_cat` 
where  `pro`.`id_user` = '$idPublicUser' " . $addYear . $addSubscription;
if (!empty($requestData['search']['value'])) {
    $sql .= " AND ( name_pro LIKE '" . $requestData['search']['value'] . "%'  ";
    $sql .= " OR  name_cat LIKE '" . $requestData['search']['value'] . "%' ) ";
}
$query = mysqli_query($db, $sql);
$totalFiltered = mysqli_num_rows($query);
$sql .= " ORDER BY " . $columns[$requestData['order'][0]['column']] . "   " . $requestData['order'][0]['dir'] . "  LIMIT " . $requestData['start'] . " ," . $requestData['length'] . "   ";
$query = mysqli_query($db, $sql);
$data = array();
while ($row = mysqli_fetch_array($query)) {
    $nestedData = array();


    $nestedData[] = $row["name_pro"];
    $nestedData[] = $row["name_cat"];
    $nestedData[] = $row["count_pro"];
    $nestedData[] = $row["price_pro"];
    $nestedData[] = $row["count_pro"] * $row["price_pro"] . " EGP";


    $data[] = $nestedData;
}

$totalPrice = 0;

$queryTotal = mysqli_query($db, query: $sql);
while ($r = mysqli_fetch_assoc($queryTotal)) {
    $total = $r["count_pro"] * $r["price_pro"];
    $totalPrice += $total;
}
$json_data = array(
    "draw" => intval($requestData['draw']),
    "recordsTotal" => intval($totalData),
    "recordsFiltered" => intval($totalFiltered),
    "data" => $data,
    "totalPrice" => $totalPrice
);

echo json_encode($json_data);

?>