<?php

namespace PloverCRM\Modules\Integrations\Models;

/**
 * Meta CAPI Connection Model
 * 
 * Represents a Meta Conversion API connection with credentials.
 */
class MetaCapiConnection
{
  public ?int $id;
  public string $name;
  public string $dataset_id;
  public string $access_token;
  public string $status;
  public int $connected_at;
  public int $updated_at;

  public function __construct(array $data)
  {
    $this->id = isset($data['id']) ? (int) $data['id'] : null;
    $this->name = $data['name'] ?? '';
    $this->dataset_id = $data['dataset_id'] ?? '';
    $this->access_token = $data['access_token'] ?? '';
    $this->status = $data['status'] ?? 'active';
    $this->connected_at = (int) ($data['connected_at'] ?? 0);
    $this->updated_at = (int) ($data['updated_at'] ?? 0);
  }

  /**
   * Check if the connection has valid credentials
   */
  public function isValid(): bool
  {
    return !empty($this->dataset_id)
      && !empty($this->access_token)
      && $this->status === 'active';
  }

  /**
   * Check if the connection is active
   */
  public function isActive(): bool
  {
    return $this->status === 'active';
  }

  /**
   * Get status display string
   */
  public function getStatusDisplay(): string
  {
    return $this->status === 'active' ? 'Active' : 'Inactive';
  }

  /**
   * Get connected date display
   */
  public function getConnectedDisplay(): string
  {
    if ($this->connected_at <= 0) {
      return 'Unknown';
    }
    return date('M j, Y', $this->connected_at);
  }

  /**
   * Convert to array for storage/API response
   */
  public function toArray(): array
  {
    return [
      'id' => $this->id,
      'name' => $this->name,
      'dataset_id' => $this->dataset_id,
      'access_token' => $this->access_token,
      'status' => $this->status,
      'connected_at' => $this->connected_at,
      'updated_at' => $this->updated_at,
    ];
  }

  /**
   * Convert to safe array for API response (no sensitive data)
   */
  public function toPublicArray(): array
  {
    return [
      'id' => $this->id,
      'name' => $this->name,
      'dataset_id' => $this->dataset_id,
      'status' => $this->status,
      'status_display' => $this->getStatusDisplay(),
      'connected_at' => $this->connected_at,
      'connected_display' => $this->getConnectedDisplay(),
    ];
  }
}
