<?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
$id = mysqli_real_escape_string( $con, $_GET['id'] );

// Get all users with a specific status
$query = "SELECT * FROM Users WHERE userId=$id LIMIT 1";
$result = mysqli_query( $con, $query );
if ( $result ) {
    // echo '123';
    $users = array();
    while ( $row = mysqli_fetch_assoc( $result ) ) {
    $pendingServiceCountQuery = "SELECT * FROM Orders WHERE userId=$id AND `status`= 1 OR `status`= 2";
    $pendingServiceCountResult = mysqli_query( $con, $pendingServiceCountQuery );
    $pendingServiceCount = mysqli_num_rows($pendingServiceCountResult);
    $serviceCountQuery = "SELECT * FROM `Orders` WHERE userId=$id";
    $serviceCountResult = mysqli_query( $con, $serviceCountQuery );

    $serviceCount = mysqli_num_rows($serviceCountResult);
    $row['pendingServiceCount'] = $pendingServiceCount;
    $row['serviceCount'] = $serviceCount;
    $users['username'] = $row['username'];
    $users['email'] = $row['email'];
    $users['fname'] = $row['fname'];
    $users['lname'] = $row['lname'];
    $users['pendingServiceCount'] = $row['pendingServiceCount'];
    $users['phoneData'] = $row['phoneData'];
    $users['phone'] = $row['phone'];
    $users['role'] = $row['role'];
    $users['serviceCount'] = $row['serviceCount'];
    $users['status'] = $row['status'];
    $users['dateModified'] = $row['dateModified'];
    $users['userId'] = $row['userId'];

    $billing_query = "SELECT * FROM UserBilling ub INNER JOIN country_iso c ON ub.country=c.COUNTRY_ISO WHERE ub.userId=$id LIMIT 1";
    $result = mysqli_query( $con, $billing_query );
    if ( $result ) {
        while ( $row = mysqli_fetch_assoc( $result ) ) {
            $users['billing']['NAME'] = $row['NAME'];
            $users['billing']['address1'] = $row['address1'];
            $users['billing']['address2'] = $row['address2'];
            $users['billing']['postalCode'] = $row['postalCode'];
            $users['billing']['country'] = $row['country'];
        }
    }
    // $users[] = $row;
  }
  $response = array(
    'status' => 'success',
    'user' => $users
  );
} else {
  $response = array(
    'status' => 'error',
    'message' => mysqli_error( $con )
  );
}

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

?>