<?php
include("../db.php");
$requestData = $_REQUEST;
$columns = array(
    0 => 'name_emp',
    1 => 'name_service',
);
$start = $_POST['dataTableSend'][0] ?? "";
$end = $_POST['dataTableSend'][1] ?? "";
$service = $_POST['dataTableSend'][3] ?? 0;
$emp = $_POST['dataTableSend'][2] ?? 0;
if ($service != 0) {
    $addService = " and `sales_footer`.`id_pro` = '$service' ";
} else {
    $addService = " ";
}
if ($emp != 0) {
    $addEmp = " and `emp`.`id_emp` = '$emp' ";
} else {
    $addEmp = " ";
}

$sql = "SELECT * FROM  `sales_footer` 
left join `service` on `service`.`id_service` = `sales_footer`.`id_pro`  
left join `sales_header` on `sales_header`.`id_sales_header` = `sales_footer`.`id_sales_header` 
left join `emp` on `emp`.`id_emp` = `sales_header`.`id_emp` 
left join `cus` on `cus`.`id_cus` = `sales_header`.`id_cus`
where  `sales_footer`.`id_user` = '$idPublicUser' and `sales_header`.`date_add` BETWEEN '$start' and '$end' " . $addService . $addEmp;

$query = mysqli_query($db, $sql);
$totalData = mysqli_num_rows($query);
$totalFiltered = $totalData;
$sql = "SELECT * FROM  `sales_footer` 
left join `service` on `service`.`id_service` = `sales_footer`.`id_pro`  
left join `sales_header` on `sales_header`.`id_sales_header` = `sales_footer`.`id_sales_header` 
left join `emp` on `emp`.`id_emp` = `sales_header`.`id_emp` 
left join `cus` on `cus`.`id_cus` = `sales_header`.`id_cus`
where  `sales_footer`.`id_user` = '$idPublicUser' and `sales_header`.`date_add` BETWEEN '$start' and '$end' " . $addService . $addEmp;
if (!empty($requestData['search']['value'])) {
    $sql .= " AND ( name_emp LIKE '" . $requestData['search']['value'] . "%'  ";
    $sql .= " OR  name_service 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_service"];
    $nestedData[] = $row["name_cus"];
    $nestedData[] = $row["phone_cus"];
    $nestedData[] = $row["count_pro"];
    $nestedData[] = $row["price_pro"];
    $nestedData[] = $row["name_emp"];
    $nestedData[] = $row["time_add"];

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


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

echo json_encode($json_data);

?>