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

@Component({
  selector: 'app-add-page',
  standalone: true,
  imports: [],
  templateUrl: './add-page.component.html',
  styleUrl: './add-page.component.less'
})
export class AddPageComponent {
  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 === 'false'){
          router.navigate(['/login']);
        }
      }
    });
  }
  insertNews = (e: MouseEvent) => {
    e.preventDefault();
    if (!this.validate()){
      alert("Please fill all fields!");
      return;
    }
    const title = $("#titleField").val();
    const content = $("#contentField").val();
    const date = $("#dateField").val();
    const producer = $("#producerField").val();
    const category = $("#categoryField").val();
    $.ajax({
      url: "https://localhost/web/Lab 8/BackEnd/Repositories/Repository.php",
      type: "POST",
      xhrFields: {
        withCredentials: true
      },
      data: {
        title: title,
        news_text: content,
        date: date,
        producer: producer,
        category: category,
        action: "insertNews",
      },
      success: function (response) {
        alert("Log added successfully!");
      },
      error: function (response) {
        alert("Error adding log!");
      },
    });
  };
  returnToAdmin = () => {
    this.router.navigate(['/admin']);
  }
  validate = () => {
    const title = $("#titleField").val();
    const content = $("#contentField").val();
    const date = $("#dateField").val();
    const producer = $("#producerField").val();
    const category = $("#categoryField").val();
    if (title === "" || content === "" || date === "" || producer === "" || category === ""){
      return false;
    }
    return true;
  }
}
