<?php

declare(strict_types=1);

namespace PloverCRM\Modules\Integrations\Models;

/**
 * Meta Connection Model
 * 
 * Represents a Facebook Page connection.
 */
class MetaConnection
{
    public ?int $id;
    public string $pageId;
    public string $pageName;
    public string $pageAccessToken;
    public string $status;
    public int $connectedAt;
    public int $updatedAt;

    public function __construct(array $data)
    {
        $this->id = isset($data['id']) ? (int) $data['id'] : null;
        $this->pageId = $data['page_id'] ?? '';
        $this->pageName = $data['page_name'] ?? '';
        $this->pageAccessToken = $data['page_access_token'] ?? '';
        $this->status = $data['status'] ?? 'active';
        $this->connectedAt = (int) ($data['connected_at'] ?? time());
        $this->updatedAt = (int) ($data['updated_at'] ?? time());
    }

    /**
     * Check if connection is active and valid
     */
    public function isActive(): bool
    {
        return $this->status === 'active' && !empty($this->pageAccessToken);
    }

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

    /**
     * Convert to array for API response
     */
    public function toArray(): array
    {
        return [
            'id' => $this->id,
            'page_id' => $this->pageId,
            'page_name' => $this->pageName,
            'status' => $this->status,
            'connected_at' => $this->connectedAt,
            'connected_display' => $this->getConnectedDisplay(),
        ];
    }
}
