<?php
header('Access-Control-Allow-Origin: *');
header(
    'Access-Control-Allow-Methods: HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS'
);
header(
    'Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method,Access-Control-Request-Headers, Authorization'
);
header('Content-Type: application/json');
// Connect to the WordPress database
include '../../../../config/db.php';

// Sanitize input
$status = mysqli_real_escape_string( $con, $_GET['status'] );


// Get all users with a specific status
if($status == 'active'){  
  $statusQry = 'WHERE status = 1';
}else if($status == 'banned'){
  $statusQry = 'WHERE status = 2';
}else if($status == 'all'){
  $statusQry = '';
}
$query = "SELECT * FROM Users  $statusQry";
$result = mysqli_query( $con, $query );
if ( $result ) {
  $users = array();
  while ( $row = mysqli_fetch_assoc( $result ) ) {
    $userId = $row['userId'];
    $pendingServiceCountQuery = "SELECT * FROM `Orders` WHERE userId=$userId AND `status`= 1 OR `status`= 2";
    $pendingServiceCountResult = mysqli_query( $con, $pendingServiceCountQuery );
    $pendingServiceCount = mysqli_num_rows($pendingServiceCountResult);
    $serviceCountQuery = "SELECT * FROM `Orders` WHERE userId=$userId";
    $serviceCountResult = mysqli_query( $con, $serviceCountQuery );
    $serviceCount = mysqli_num_rows($serviceCountResult);
    $row['pendingServiceCount'] = $pendingServiceCount;
    $row['serviceCount'] = $serviceCount;
    $users[] = $row;
  }
  $response = array(
    'status' => 'success',
    'users' => $users
  );
} else {
  $response = array(
    'status' => 'error',
    'message' => mysqli_error( $con )
  );
}

// Return response as JSON
header( 'Content-Type: application/json' );
echo json_encode( $response );

?>