@extends('layouts.app')

@section('title', 'Login Page')

<style>
  .custom-flex-column {
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .custom-flex-normal {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .custom-radius {
    border-radius: 40px;
  }

  .custom-shadow {
    box-shadow: 0px 6px 6px #46291B !important;
  }


  .toast {
    visibility: hidden;
    min-width: 250px;
    margin-left: -125px;
    background-color: #333;
    color: #fff;
    text-align: center;
    border-radius: 2px;
    padding: 16px;
    position: fixed;
    z-index: 100;
    right: 30px;
    top: 30px;
    font-size: 17px;
  }

  .toast.show {
    visibility: visible;
    animation: fadeInOut 3s;
  }

  @keyframes fadeInOut {
    0% {
      opacity: 0;
    }
    10% {
      opacity: 1;
    }
    90% {
      opacity: 1;
    }
    100% {
      opacity: 0;
    }
  }

  /* Success (green) */
  .toast.success {
    background-color: #28a745;
  }

  /* Error (red) */
  .toast.error {
    background-color: #dc3545;
  }


</style>

@section('content')
  <div class="h-full w-full max-w-[1400px]">
    <div class="w-full h-[10%] mb-14 custom-flex-normal">
      <a href="/">
        <img class="h-[3.5vw] min-h-[60px]" src="Images/logo.png" alt="mainLogo">
      </a>
    </div>

    <div class="w-full h-[80%] bg-[#D8D2C2]/40 custom-radius backdrop-blur-md flex flex-col items-center">
      <div class="w-full sm:max-w-[500px] pt-8 px-3 sm:p-8 rounded-lg text-center">
        <h1 class="font-regular text-3xl mb-1 text-[#4B3A29]">create account</h1>
        <p class="text-sm text-[#857F72] mb-14">make sure to fill your details correctly</p>

        <form id="loginForm" class="space-y-2">
  <input
    type="text"
    name="username"
    placeholder="username"
    class="w-full px-4 py-3 mb-1 text-black bg-transparent border-2 border-[#5D432A] rounded-full focus:outline-none focus:ring-2 focus:ring-[#D7C7B7]"
    required
  />
  <input
    type="text"
    name="phone_number"
    placeholder="phone number"
    class="w-full px-4 py-3 text-black bg-transparent border-2 border-[#5D432A] rounded-full focus:outline-none focus:ring-2 focus:ring-[#D7C7B7]"
    required
  />
  <button
    type="submit"
    class="py-2 px-12 active:scale-95 transform transition-all font-semibold border-2 border-[#5D432A] rounded-[40px] whitespace-nowrap mt-8 bg-[#AF8F6F] uppercase custom-shadow"
  >
    Continue
  </button>
</form>


      </div>
    </div>
  </div>

  <div id="otpPopup" class="hidden fixed inset-0 bg-black bg-opacity-50 backdrop-blur-sm flex items-center justify-center z-50">
  <form id="otpForm" class="bg-[#AF8F6F] p-6 rounded-lg w-[90%] max-w-[400px] text-center">
    <h2 class="font-regular text-lg mb-1 text-white">VERIFY YOUR PHONE NUMBER</h2>
    <p class="text-xs text-white mb-4 opacity-60">
      We emailed you a six-digit code to your phone number. Enter the code below to confirm your email address.
    </p>
    <div class="flex justify-center space-x-2 mb-4">
      <input type="text" maxlength="1" class="otp-input w-10 h-16 text-center border border-[#4B3A29] rounded-md bg-secondary backdrop-blur-lg focus:outline-none focus:ring-2 focus:ring-[#D7C7B7]" />
      <input type="text" maxlength="1" class="otp-input w-10 h-16 text-center border border-[#4B3A29] rounded-md bg-secondary backdrop-blur-lg focus:outline-none focus:ring-2 focus:ring-[#D7C7B7]" />
      <input type="text" maxlength="1" class="otp-input w-10 h-16 text-center border border-[#4B3A29] rounded-md bg-secondary backdrop-blur-lg focus:outline-none focus:ring-2 focus:ring-[#D7C7B7]" />
      <input type="text" maxlength="1" class="otp-input w-10 h-16 text-center border border-[#4B3A29] rounded-md bg-secondary backdrop-blur-lg focus:outline-none focus:ring-2 focus:ring-[#D7C7B7]" />
      <input type="text" maxlength="1" class="otp-input w-10 h-16 text-center border border-[#4B3A29] rounded-md bg-secondary backdrop-blur-lg focus:outline-none focus:ring-2 focus:ring-[#D7C7B7]" />
      <input type="text" maxlength="1" class="otp-input w-10 h-16 text-center border border-[#4B3A29] rounded-md bg-secondary backdrop-blur-lg focus:outline-none focus:ring-2 focus:ring-[#D7C7B7]" />
    </div>
    <button type="submit" class="py-2 px-6 active:scale-95 transform transition-all font-semibold border-2 border-[#5D432A] rounded-[40px] whitespace-nowrap bg-headingFont uppercase custom-shadow">
      Continue
    </button>
  </form>
</div>


<script>
document.addEventListener("DOMContentLoaded", () => {
  const loginForm = document.getElementById("loginForm");
  const otpPopup = document.getElementById("otpPopup");
  const otpInputs = document.querySelectorAll("#otpPopup input[type='text']");
  const otpForm = document.getElementById("otpForm");

  // Handle login form submission
  loginForm.addEventListener("submit", (e) => {
    e.preventDefault();

    const username = document.querySelector('input[name="username"]').value;
    const phoneNumber = document.querySelector('input[name="phone_number"]').value;

    fetch("{{ route('login.submit') }}", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json',
        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
      },
      body: JSON.stringify({ username, phone_number: phoneNumber }),
    })
      .then((response) => response.json())
      .then((data) => {
        if (data.status === "otp_sent") {
          otpPopup.classList.remove("hidden");
        } else {
          console.error("Error sending OTP");
        }
      })
      .catch((error) => console.error(error));
  });

  // Close OTP popup when clicking outside
  otpPopup.addEventListener("click", (e) => {
    if (e.target === otpPopup) {
      otpPopup.classList.add("hidden");
    }
  });

  // Add event listeners to OTP inputs
  otpInputs.forEach((input, index) => {
    input.addEventListener("input", (e) => {
      if (e.target.value.length > 1) {
        e.target.value = e.target.value.slice(0, 1); // Ensure only one digit
      }
      if (e.target.value && index < otpInputs.length - 1) {
        otpInputs[index + 1].focus(); // Move to next input
      }
    });

    input.addEventListener("keydown", (e) => {
      if (e.key === "Backspace") {
        if (!e.target.value && index > 0) {
          otpInputs[index - 1].focus(); // Move to previous input
        }
      }
    });
  });

  // Handle OTP form submission
  otpForm.addEventListener("submit", (e) => {
    e.preventDefault();

    const otp = Array.from(otpInputs).map((input) => input.value).join("");
    const phoneNumber = document.querySelector('input[name="phone_number"]').value;

    fetch("{{ route('verify.otp') }}", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json',
        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
      },
      body: JSON.stringify({ otp, phone_number: phoneNumber }),
    })
      .then((response) => response.json())
      .then((data) => {
        if (data.status === "success") {
          // Store the token in localStorage or sessionStorage
          localStorage.setItem('auth_token', data.token);

          console.log(localStorage.getItem('auth_token')); // Check if the token exists

          // Redirect to home after successful OTP verification
          window.location.href = "{{ route('home') }}";

          // Fetch data from the home route with Authorization header
          const token = localStorage.getItem('auth_token');  // Get the token from localStorage
          
          fetch("{{ route('home') }}", {
            method: "GET",
            headers: {
              'Authorization': `Bearer ${token}`,  // Include token in Authorization header
            }
          })
            .then(response => response.json())
            .then(data => {
              console.log(data);  // Handle the response data from the home route
            })
            .catch(error => console.error("Error fetching home data:", error));
        } else {
          showToast("Invalid OTP. Please try again.", 'error');
        }
      })
      .catch((error) => console.error(error));
  });

  // Handle paste in OTP inputs
  otpInputs[0].addEventListener("paste", (e) => {
    const pasteData = e.clipboardData.getData("text").slice(0, otpInputs.length);
    pasteData.split("").forEach((char, i) => {
      otpInputs[i].value = char;
    });
    if (pasteData.length === otpInputs.length) {
      otpInputs[otpInputs.length - 1].focus();
    }
  });
});


function showToast(message, type = 'success') {
  const toast = document.createElement('div');
  toast.classList.add('toast', type);  // Add the type (success or error)
  toast.textContent = message;

  document.body.appendChild(toast);

  // Show the toast and remove it after a short delay
  setTimeout(() => {
    toast.classList.add('show');
  }, 100);

  setTimeout(() => {
    toast.classList.remove('show');
    setTimeout(() => {
      document.body.removeChild(toast);
    }, 500);
  }, 3000);
}

</script>




@endsection
