import 'package:intl/intl.dart';

class OntDataModel {
  final int idData;
  final int id;
  final DateTime waktu; // Use DateTime instead of String
  final String status;
  final String download;
  final String upload;

  OntDataModel({
    required this.idData,
    required this.id,
    required this.waktu,
    required this.status,
    required this.download,
    required this.upload,
  });

  // Factory constructor to create an instance from JSON
  factory OntDataModel.fromJson(Map<String, dynamic> json) {
    DateTime originalTime =
        DateTime.parse(json['waktu'].toString()).toUtc(); // Ensure UTC
    DateTime utcPlus8 =
        originalTime.add(const Duration(hours: 8)); // Convert to UTC+8

    return OntDataModel(
      idData: json['id_data'] is int
          ? json['id_data']
          : int.tryParse(json['id_data'].toString()) ?? 0,
      id: json['id'] is int
          ? json['id']
          : int.tryParse(json['id'].toString()) ?? 0,
      waktu: utcPlus8, // Store UTC+8 time
      status: json['status']?.toString() ?? 'Unknown',
      download: json['download']?.toString() ?? '-',
      upload: json['upload']?.toString() ?? '-',
    );
  }

  // Method to return formatted UTC+8 date
  String getFormattedDate() {
    return DateFormat('yyyy-MM-dd HH:mm:ss').format(waktu);
  }

  // Convert back to UTC before saving to JSON
  Map<String, dynamic> toJson() => {
        'id_data': idData,
        'id': id,
        'waktu': waktu
            .subtract(const Duration(hours: 8))
            .toIso8601String(), // Convert back to original UTC
        'status': status,
        'download': download,
        'upload': upload,
      };
}
