<?php namespace jasonwilliams\feed\Models;

use Model;

/**
 * Model
 */
class FeedItem extends Model
{
    use \October\Rain\Database\Traits\Validation;

    /*
     * Disable timestamps by default.
     * Remove this line if timestamps are defined in the database table.
     */
    public $timestamps = false;


    /**
     * @var string The database table used by the model.
     */
    public $table = 'jasonwilliams_feed_';

    /**
     * @var array Validation rules
     */
    public $rules = [
    ];

    public $hasMany = [
      'links' => 'jasonwilliams\feed\Models\Links',
      'tags' => 'jasonwilliams\feed\Models\Tags'
    ];

    public $belongsTo = [
      'channel' => ['jasonwilliams\feed\Models\Channels', 'key' => 'channel_id']
    ];

    public function afterFetch()
    {
      // Add clickable hashtags to the title field
      $this->title = preg_replace('/#(\w*[a-zA-Z]+\w*)/', '<a href="/feed/all/$1">#$1</a>', $this->title);

      // Add a friendlytime field
      $this->friendlytime = date('M j, Y', $this->timestamp);

      // Expand extras to an object
      if ($this->extra) $this->extra = json_decode($this->extra);

      // Add twitter user links
      if ($this->channel_id == 2) $this->title = preg_replace('/@([a-zA-Z0-9_]+)/', '<a href="http://twitter.com/$1">@$1</a>', $this->title);

      // Add instagram user links
      if ($this->channel_id == 3) $this->title = preg_replace('/@([a-zA-Z0-9_]+)/', '<a href="https://www.instagram.com/$1">@$1</a>', $this->title);

      // Add foursquare user Links
      if ($this->channel_id == 6 && !empty($this->body)) $this->body = preg_replace('/@([a-zA-Z0-9_]+)/', '<a href="https://www.foursquare.com/$1">@$1</a>', $this->body);

      // Find and replace links
      foreach($this->links as $link)
      {
        $this->title = str_replace($link->addr, "<a href=\"".$link->addr."\">".$link->display."</a>", $this->title);
      }
    }
}