
<?php
class FmMagazine extends CDController{

  protected $last_magazine;

  public function __construct() {

    $this->last_magazine = cw_get_last_magazine();

    global $post;

    if ( is_single() ){
      if( $post->post_parent > 0 ) {
        $this->view = 'fm/magazine/single.twig';
      } else {
        $this->view = 'fm/magazine/index.twig';
      }
    }
    if ( is_archive() ){
      $this->view = 'fm/magazine/archive.twig';
    }

  }

  public function get_context(){
    global $post;

    $this->data = CDTimber::get_context();

    if ( is_single() ){
      if( $post->post_parent > 0 ) {
        $this->get_single_context();
      } else {
        $this->get_index_context($post->ID);
      }
    }
    if ( is_archive() ){
      $this->get_archive_context();
    }
  }

  public function get_single_context(){
    $this->data['post']->hero_title = $this->data['post']->title;
    $mazagine_post = CDTimber::get_post($this->data['post']->post_parent);

    $this->data['is_content_visible'] = $this->is_posts_visible($this->data['post']->post_parent);

    $this->data['post']->hero_lead = '#'.$mazagine_post->magazine_number.' '.ucwords(get_the_date("F Y", $mazagine_post->ID));

  }

  public function get_index_context($magazine_id){

    $args = array(
      'post_type' => 'fm_magazine',
      'posts_per_page' => -1,
      'post_parent' => $magazine_id
    );

    $this->data['magazine_posts'] = Timber::get_posts($args);

    $is_current = false;

    $this->data['is_content_visible'] = $this->is_posts_visible($this->data['post']->ID);


    $last_magazine = $this->last_magazine;

    if($last_magazine){
      if( $magazine_id == $last_magazine->ID){
        $is_current = true;
      }
    }

    $this->data['is_current'] = $is_current;

    $this->data['post']->hero_lead = '#'.get_field('magazine_number').' | '.ucwords(get_the_date("F Y", $this->data['post']->ID));

  }

  public function get_archive_context(){
    $hero_magazine_archive = get_field('option_magazine_archive_hero', 'option');
    $this->data['post'] = (object)array();
    $this->data['post']->hero_image = $hero_magazine_archive['image'];
    $this->data['post']->hero_lead = $hero_magazine_archive['lead'];
    $this->data['post']->hero_title = $hero_magazine_archive['title'];
    $this->data['post']->hero_subtitle = $hero_magazine_archive['subtitle'];

  }

  private function is_posts_visible($magazine_id){
    global $post;
    $is_visible = false;
    if( is_user_logged_in() ){
      $is_visible = true;
    }else{
      if( $magazine_id == $this->last_magazine->ID){
        $is_visible = true;
      }
    }

    return $is_visible;

  }

}
