<?php

namespace ModernFields\FieldGroups\Entities;

use WP_Post;

/**
 * Represents an attachment entity.
 * 
 * @since 1.0.0
 */
class Attachment extends Entity
{

  /**
   * @var int
   */
  protected int $ID;

  /**
   * @var string
   */
  protected string $title;

  /**
   * @var string
   */
  protected string $filename;

  /**
   * @var string
   */
  protected string $mime_type;

  /**
   * @var string
   */
  protected string $url;

  /**
   * @var string
   */
  protected string $date;

  /**
   * @var array
   */
  protected array $meta;

  /**
   * @param WP_Post $attachment
   */
  public function __construct(WP_Post $attachment)
  {
    $this->ID = (int) $attachment->ID;
    $this->title = $attachment->post_title;
    $this->mime_type = $attachment->post_mime_type ?? '';
    $this->date = $attachment->post_date;

    # Get attachment URL
    $this->url = wp_get_attachment_url($attachment->ID);

    # Get filename from attachment metadata or guid
    $attachment_metadata = wp_get_attachment_metadata($attachment->ID);
    if ($attachment_metadata && isset($attachment_metadata['file'])) {
      $this->filename = basename($attachment_metadata['file']);
    } else {
      # Fallback to guid if metadata not available
      $this->filename = basename($attachment->guid);
    }

    # Get all meta for this attachment
    $this->meta = get_post_meta($attachment->ID);
  }

  public function getId(): int
  {
    return $this->ID;
  }

  public function getTitle(): string
  {
    return $this->title;
  }

  public function getFilename(): string
  {
    return $this->filename;
  }

  public function getMimeType(): string
  {
    return $this->mime_type;
  }

  public function getUrl(): string
  {
    return $this->url;
  }

  public function getDate(): string
  {
    return $this->date;
  }

  public function toArray(): array
  {
    return [
      'ID' => $this->ID,
      'title' => $this->title,
      'filename' => $this->filename,
      'mime_type' => $this->mime_type,
      'url' => $this->url,
      'date' => $this->date,
      'meta' => $this->prepareMetaForJson(),
    ];
  }
}
