<?php

namespace GPLoker\Inc;

use WP_Post;

class Company {
	private $company;
	private $phone;
	private $email;
	private $website;

	public function __construct( $post = null ) {
		$this->company = get_post( $post );
	}

	public static function get( $post ) {
		return new self( $post );
	}

	public function info() {
		return $this->company;
	}

	public function getId() {
		return $this->company && $this->company->ID ? $this->company->ID : 0;
	}

	/**
	 * @return mixed
	 */
	public function getLogo( $size = 'medium' ) {
		$company_logo_url = get_the_post_thumbnail_url( $this->company, $size );
		if ( empty( $company_logo_url ) ) {
			$company_logo_url = '//placehold.co/300x300';
		}
		
		return $company_logo_url;
	}

	/**
	 * @return mixed
	 */
	public function getPhone() {
		if ( empty( $this->phone ) ) {
			$this->phone = $this->meta( 'phone' );
		}

		return $this->phone;
	}

	/**
	 * @return mixed
	 */
	public function getEmail() {
		if ( empty( $this->email ) ) {
			$this->email = $this->meta( 'email' );
		}

		return $this->email;
	}

	/**
	 * @return mixed
	 */
	public function getWebsite() {
		if ( empty( $this->website ) ) {
			$this->website = $this->meta( 'website' );
		}

		return $this->website;
	}

	/**
	 * @return mixed
	 */
	public function getTitle() {
		return $this->company instanceof WP_Post ? $this->company->post_title : '';
	}

	/**
	 * @return mixed
	 */
	public function getDescription() {
		return wpautop( $this->company->post_content );
	}
	public function getShortDescription() {
		$short_description = $this->meta('short_description');
		if ( empty($short_description) ) {
			$short_description = wp_trim_words($this->company->post_content);
			update_post_meta($this->company->ID, 'short_description', $short_description);
		}

		return wpautop($short_description);
	}

	public function getAddresses() {
		return $this->meta('addresses');
	}

	public function getCompanyUrl() {
		return get_permalink( $this->getId() );
	}

	public function getCompanyLink() {
		return sprintf(
			'<a href="%s" title="Profile: %s">%s</a>',
			$this->getCompanyUrl(),
			$this->getTitle(),
			$this->getTitle()
		);
	}

	public function meta( $name, $default = null ) {
		$meta = get_post_meta( $this->getId(), $name, true );
		if ( ! empty( $meta ) ) {
			return $meta;
		}

		return $default;
	}

}
