<?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';

$postData = file_get_contents('php://input');
if (isset($postData) && !empty($postData)) {
  //Extract the data
  $request = json_decode($postData);

  //Validate data
  if (
    trim($request->userId) === '' ||
    trim($request->firstName) === '' ||
    trim($request->lastName) === '' ||
    trim($request->phone) === ''
  ) {
    $responseArray = [
      'message' => 'Required fields are missing.',
      'status' => -2,
    ];
    echo json_encode($responseArray);
    return http_response_code(406);
  }
  // Sanitize input
  $userId = mysqli_real_escape_string($con, trim($request->userId));
  $username = mysqli_real_escape_string($con, trim($request->email));
  $firstName = mysqli_real_escape_string($con, trim($request->firstName));
  $lastName = mysqli_real_escape_string($con, trim($request->lastName));
  $email = mysqli_real_escape_string($con, trim($request->email));
  $phone = mysqli_real_escape_string($con, trim($request->phone));
  $phoneData = $request->phoneData;


  $password = mysqli_real_escape_string($con, trim($request->password));

  if (!empty($request->password)) {
    $new_password_hash = password_hash($request->password, PASSWORD_BCRYPT);
    $user_query = "SELECT * FROM Users WHERE userId = '$request->userId'";

    if ($results = mysqli_query($con, $user_query)) {
      if ($results->num_rows == 1) {
        while ($user_data = $results->fetch_assoc()) {

          $current_password = $user_data['password'];

          if (password_verify($request->password, $current_password)) {
            http_response_code(400);
            echo json_encode([
              'status' => 0,
              'message' => 'The new password cannot be the same as the old password. Please provide a different password.',
            ]);
          } else {
            $update_query = "UPDATE Users SET  fname = '$firstName', lname = '$lastName', phone = '$phone', phoneData = '$phoneData', password = '$new_password_hash', dateModified = NOW() WHERE userId = $userId";


            if (mysqli_query($con, $update_query) === TRUE) {
              http_response_code(200);
              echo json_encode([
                'status' => 1,
                'message' => 'Data updated successfully.',
                'data' => [],
              ]);
            } else {
              http_response_code(400);
              echo json_encode([
                'status' => 0,
                'message' => 'Could not update data.',
              ]);
            }
          }
        }
      } else {
        http_response_code(404);
        echo json_encode([
          'status' => 0,
          'message' => 'User not found.',
        ]);
      }
    }
  } else {
    $update_query = "UPDATE Users SET username = '$username', fname = '$firstName', lname = '$lastName', email = '$email', phone = '$phone', phoneData = '$phoneData', dateModified = NOW() WHERE userId = $userId";


    if (mysqli_query($con, $update_query) === TRUE) {
      http_response_code(200);
      echo json_encode([
        'status' => 1,
        'message' => 'Data updated successfully.',
        'data' => [],
      ]);
    } else {
      http_response_code(400);
      echo json_encode([
        'status' => 0,
        'message' => 'Could not update data.',
      ]);
    }
  }
}
