import { Component } from '@angular/core';
import { Router } from '@angular/router';
import News from '../../types/news';

@Component({
  selector: 'app-edit-page',
  standalone: true,
  imports: [],
  templateUrl: './edit-page.component.html',
  styleUrl: './edit-page.component.less'
})
export class EditPageComponent {
  news: News = {
    id: -1,
    title: "",
    news_text: "",
    date: "",
    producer: "",
    category: ""
  };
  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']);
        }
      }
    });
    let id = router.url.split("/")[2];
    $.ajax({
      url: `https://localhost/web/Lab 8/BackEnd/Repositories/Repository.php?action=getNewsById&id=${id}`,
      type: "GET",
      context: this,
      xhrFields: {
        withCredentials: true
      },
      success: (response: any) => {
        const news = JSON.parse(response);
        this.news = news;
      },
      error: function (response) {
        alert("Error getting log!");
        this.router.navigate(['/admin']);
      },
    });
  }
  editNews = (e: MouseEvent) => {
    e.preventDefault();
    if (!this.validate()){
      alert("Please fill all fields!");
      return;
    }
    const id = $("#idField").val();
    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: {
        id: id,
        title: title,
        news_text: content,
        date: date,
        producer: producer,
        category: category,
        action: "updateNews",
      },
      success: function (response) {
        alert("Log edited successfully!");
      },
      error: function (response) {
        alert("Error edited 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;
  }
}
