// lib/models/marine_manual_pre_departure_checklist_data.dart

import 'dart:convert';

class MarineManualPreDepartureChecklistData {
  String? reporterName;
  int? reporterUserId;
  String? submissionDate;
  String? location;

  // Key: Item description, Value: true if 'Yes', false if 'No'
  Map<String, bool> checklistItems = {};

  // Key: Item description, Value: Remarks text
  Map<String, String> remarks = {};

  String? submissionStatus;
  String? submissionMessage;
  String? reportId;

  MarineManualPreDepartureChecklistData();

  /// Creates a JSON object for offline database storage.
  Map<String, dynamic> toDbJson() {
    return {
      'reporterName': reporterName,
      'reporterUserId': reporterUserId,
      'submissionDate': submissionDate,
      'location': location,
      'checklistItems': checklistItems,
      'remarks': remarks,
      'submissionStatus': submissionStatus,
      'submissionMessage': submissionMessage,
      'reportId': reportId,
    };
  }

  // MODIFIED: This method now builds the nested array structure the PHP controller expects.
  Map<String, dynamic> toApiFormData() {

    // Create the 'items' list required by the API
    List<Map<String, dynamic>> itemsList = [];

    // Iterate over the checklist items and build the list
    checklistItems.forEach((itemName, itemChecked) {
      itemsList.add({
        'item_name': itemName,
        'item_checked': itemChecked,
        'item_remark': remarks[itemName] ?? '' // Get the corresponding remark
      });
    });

    return {
      'reporter_user_id': reporterUserId.toString(),
      'submission_date': submissionDate,
      // Note: 'location' is not sent to the API in this method, but saved in db.json
      'items': itemsList, // Send the formatted list
    };
  }

  // --- START: ADDED TELEGRAM METHOD ---
  String generateTelegramAlertMessage() {
    int checkedCount = checklistItems.values.where((v) => v == true).length;
    int totalCount = checklistItems.length;

    final buffer = StringBuffer()
      ..writeln('🚤 *Pre-Departure Checklist Submitted*')
      ..writeln()
      ..writeln('*Reporter:* ${reporterName ?? "N/A"}')
      ..writeln('*Date:* ${submissionDate ?? "N/A"}')
      ..writeln('*Location:* ${location ?? "N/A"}')
      ..writeln('*Items Checked:* $checkedCount / $totalCount');

    // Add remarks only if they exist for specific items
    final activeRemarks = remarks.entries
        .where((e) => e.value.trim().isNotEmpty)
        .map((e) => "- ${e.key}: ${e.value}")
        .toList();

    if (activeRemarks.isNotEmpty) {
      buffer.writeln('\n*Specific Remarks:*');
      buffer.writeAll(activeRemarks, '\n');
    }

    buffer
      ..writeln()
      ..writeln('*Status of Submission:* Successful');

    return buffer.toString();
  }
// --- END: ADDED TELEGRAM METHOD ---
}