import { Component } from '@angular/core';
import { Router } from '@angular/router';
import $ from 'jquery';



@Component({
  selector: 'app-login-page',
  standalone: true,
  imports: [],
  templateUrl: './login-page.component.html',
  styleUrl: './login-page.component.less'
})

export class LoginPageComponent {
  constructor(private router: Router) { 
    $.ajax({
      url: 'https://localhost/web/Lab%208/BackEnd/Repositories/Repository.php?action=isLogged',
      type: 'GET',
      xhrFields: {
        withCredentials: true
      },
      success: function(data: any){
        if (data === 'true'){
          console.log('User is logged in');
          router.navigate(['/admin']);
        }
      }
    });
  }
  login = () => {
    let username = $('#username').val();
    let password = $('#password').val();
    let router = this.router;

    $.ajax({
      url: 'https://localhost/web/Lab%208/BackEnd/Repositories/Repository.php',
      type: 'POST',
      data: {username: username, password: password, action: 'validateUser'},
      xhrFields: {
        withCredentials: true
      },
      success: function(data: any){
        if (data){
          router.navigate(['/admin']);
        }
        else{
          alert('Invalid username or password');
        }
      },
      error: function(){
        alert('Invalid username or password');
      }
    });
    
  }

  cancel = () => {
    this.router.navigate(['/']);
  }
}
