<?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');
$method = $_SERVER['REQUEST_METHOD'];
if ($method == "OPTIONS") {
  header('Access-Control-Allow-Origin: *');
  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("HTTP/1.1 200 OK");
  die();
}


include '../../../../config/db.php';
include '../../../../config/mail.php';

include_once '../../../../vendor/firebase/php-jwt/src/BeforeValidException.php';
include_once '../../../../vendor/firebase/php-jwt/src/ExpiredException.php';
include_once '../../../../vendor/firebase/php-jwt/src/SignatureInvalidException.php';
include_once '../../../../vendor/firebase/php-jwt/src/JWT.php';

require '../../../../mail/libs/Exception.php';
require '../../../../mail/libs/PHPMailer.php';
require '../../../../mail/libs/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use \Firebase\JWT\JWT;

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

  //Validate data
  if (
    trim($request->username) === '' ||
    trim($request->fname) === '' ||
    trim($request->lname) === '' ||
    trim($request->email) === '' ||
    trim($request->phone) === '' ||
    trim($request->password) === '' ||
    trim($request->role) === ''
  ) {
    $responseArray = [
      'message' => 'Required fields are missing.',
      'status' => -2,
    ];
    echo json_encode($responseArray);
    return http_response_code(406);
  }
  // Sanitize input
  $username = mysqli_real_escape_string($con, trim($request->username));
  $fname = mysqli_real_escape_string($con, trim($request->fname));
  $lname = mysqli_real_escape_string($con, trim($request->lname));
  $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));
  $role = mysqli_real_escape_string($con, trim($request->role));
  $behaviour = 0;
  $comments = '';
  $dateTime = date("Y-m-d H:i:s");
  $token = bin2hex(random_bytes(20)); // token generator

  $isExistsQuery = "SELECT * FROM Users WHERE `email` = '$email' LIMIT 1";
  $isExistsResult = mysqli_query($con, $isExistsQuery);
  if (mysqli_num_rows($isExistsResult) == 0) {
    // Create user
    $password_hash = password_hash($password, PASSWORD_DEFAULT);

    $query = "INSERT INTO `Users`(`userId`, `username`, `fname`, `lname`, `email`, `phoneData`, `phone`, `password`, `role`, `behaviour`, `comments`, `isDeleted`, `token`, `status`, `dateCreated`, `dateModified`)
              VALUES (null,'$username','$fname','$lname','$email','$phoneData','$phone','$password_hash','$role','$behaviour','$comments',0,'$token',1,'$dateTime','$dateTime')";

    $result = mysqli_query($con, $query);

    if ($result) {

      $latest_id = $con->insert_id;

      //mail send
      $myAwardSpaceEmail = "technical@ayushnames.com";
      $myAwardSpaceEmailPassword = 'Ayush@2022';
      $myPersonalEmail = $request->email;

      $reply_email = 'info@ayushnames.com';

      $mail = new PHPMailer(true);
      $mail->SMTPDebug = 0;
      $mail->Host = 'ftp.ayushnames.com';
      $mail->SMTPAuth = true;
      $mail->Username = $myAwardSpaceEmail;
      $mail->Password = $myAwardSpaceEmailPassword;
      $mail->SMTPSecure = 'tls';
      $mail->Port = 587;

      $mail->setFrom($myAwardSpaceEmail, 'Ayush Names - Verify My Account');
      $mail->addAddress($myPersonalEmail);
      $mail->addReplyTo($reply_email, 'Ayush Names');
      $mail->isHTML(true);
      $mail->Subject = 'Ayush Names - Verify My Account';

      $txt = '<div style="margin-left: auto;margin-right: auto;width: 55%;">
            <div style="border: 0.5px solid #d7d7d7;border-radius: 10px;padding: 20px;width: fit-content;font-family: system-ui;">
            <div style="width: 50%;">
            <img style="height: auto; width: 100%;" src="https://ayushnames.com/wp-content/uploads/2022/03/Artboard-2@4x-3-373x147.png">
            </div>
            <p>Dear ' . $fname . ' ' . $lname . ', </p>
            <p> Please click on this link to verify your account on Ayush names.</p>
            <a style="width: 200px;display: block;background: orange;color: #ffffff;padding: 10px;margin: auto;text-align: center;text-decoration: none;border-radius: 10px;" href="https://ayushnames.com/verify-user/?token=' . $token . '&email=' . $email . '">Verify Me</a>
            <p> Thank you,</p>
            <p>Ayush team</p>
            </div>
            </div>';

      $mail->Body = $txt;

      try {

        $mail->send();

        http_response_code(200);
        $response = array(
          'status' => 'success'
        );
      } catch (Exception $e) {

        deleteUser($con, $latest_id);

        http_response_code(200);
        $response = array(
          'status' => 'error'
        );
      }
    } else {
      $response = array(
        'status' => 'error'
      );
    }
  } else {
    $response = array(
      'status' => 'error',
      'code' => -1,
      'message' => 'Data already exists.'
    );
  }


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


function deleteUser($con, $id)
{
  $delete_query = "DELETE FROM Users WHERE userId= $id";
  mysqli_query($con, $delete_query);
}
