<?php
include("../db.php");
$requestData = $_REQUEST;
$columns = array(
    0 => 'name_pro',
    1 => 'name_cat',
);
$start = $_POST['dataTableSend'][0] ?? "";
$end = $_POST['dataTableSend'][1] ?? "";
$cat = $_POST['dataTableSend'][2] ?? 0;
$pro = $_POST['dataTableSend'][3] ?? 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  `sales` 
left join `pro` on `pro`.`id_pro` = `sales`.`id_pro`  
left join `cat` on  `cat`.`id_cat` = `pro`.`id_cat` 
left join `emp` on `emp`.`id_emp` = `sales`.`id_emp` 
where  `sales`.`id_user` = '$idPublicUser' and `sales`.`date_add` BETWEEN '$start' and '$end' " . $addYear . $addSubscription;

$query = mysqli_query($db, $sql);
$totalData = mysqli_num_rows($query);
$totalFiltered = $totalData;
$sql = "SELECT * FROM  `sales` 
left join `pro` on `pro`.`id_pro` = `sales`.`id_pro`  
left join `cat` on  `cat`.`id_cat` = `pro`.`id_cat` 
left join `emp` on `emp`.`id_emp` = `sales`.`id_emp` 
where  `sales`.`id_user` = '$idPublicUser' and `sales`.`date_add` BETWEEN '$start' and '$end' " . $addYear . $addSubscription;
if (!empty($requestData['search']['value'])) {
    $sql .= " AND ( name_pro LIKE '" . $requestData['search']['value'] . "%'  ";
    $sql .= " OR  name_emp 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"];
    $nestedData[] = $row["total_before_price"];
    $nestedData[] = $row["discount"];
    $nestedData[] = $row["total_after_price"];
    $nestedData[] = $row["name_emp"];
    $nestedData[] = $row["time_add"];
    $nestedData[] = $row["note"];

    $data[] = $nestedData;
}
$totalPrice = 0;
$queryTotal = mysqli_query($db, query: $sql);
while ($r = mysqli_fetch_assoc($queryTotal)) {
    $totalPrice += $r['total_after_price'];
}


$json_data = array(
    "draw" => intval($requestData['draw']),
    "recordsTotal" => intval($totalData),
    "recordsFiltered" => intval($totalFiltered),
    "data" => $data,
    "totalPrice" => $totalPrice
);

echo json_encode($json_data);

?>