import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
import { NgIf, NgFor, DatePipe, NgClass } from '@angular/common';
import { HeaderComponent } from '../header/header.component';

@Component({
  selector: 'app-notifications',
  standalone: true,
  imports: [NgIf, NgFor, DatePipe, NgClass, HeaderComponent],
  templateUrl: './notifications.component.html',
})
export class NotificationsComponent implements OnInit {
  notifications: any[] = [];
  userId = 2; // Replace with real user ID

  constructor(private http: HttpClient, private router: Router) {}

  ngOnInit(): void {
    this.fetchNotifications();
  }

  fetchNotifications() {
    this.http
      .get<any[]>(`https://infoways.in/funtelapi/notifications.php?action=get&user_id=${this.userId}`)
      .subscribe((res) => {
        this.notifications = res;
      });
  }

  openNotification(noti: any) {
    if (noti.is_read == 0) {
      this.http
        .post(`https://infoways.in/funtelapi/notifications.php?action=mark_read`, {
          notification_id: noti.id,
        })
        .subscribe(() => {
          noti.is_read = 1;
        });
    }

    this.router.navigate(['/read', noti.story_id]);
  }

  deleteNotification(noti: any) {
    this.http
      .post(`https://infoways.in/funtelapi/notifications.php?action=delete`, {
        notification_id: noti.id,
      })
      .subscribe(() => {
        this.notifications = this.notifications.filter((n) => n.id !== noti.id);
      });
  }
}
