<?php
/*
    =========================================
        Post functions
    =========================================
*/

require_once( INC . 'Section.php' );


//--------------------------------   GET CONTENT  ------------------------------------

function get_content_from_json ($file_name)
{
  return json_decode(file_get_contents(INC . "dictionnaries/$file_name.json"), true);
}

//--------------------------------   POSTS  ------------------------------------

function get_pages ()
{
  global $db;

  $sth = $db->pdo->prepare('
  SELECT *
  FROM pages
  ');

  $sth->execute();

  return $sth->fetchAll();
}


//--------------------------------   POSTS  ------------------------------------

function get_posts ( $type = DEFAULT_POST_TYPE, $limit = 2000, $lang = MAIN_LANGUAGE )
{
  global $db;

  $sth = $db->pdo->prepare('
  SELECT *, DATE_FORMAT(date_created, "%d-%m-%Y") AS date_mod_form
  FROM posts
  WHERE type = :type AND language = :language AND status = "public"
  ORDER BY date_created DESC
  LIMIT :limit
  ');

  $sth->bindParam(':type', $type, PDO::PARAM_STR);
  $sth->bindParam(':language', $lang, PDO::PARAM_STR);
  $sth->bindParam(':limit', $limit, PDO::PARAM_INT);
  $sth->execute();

  $posts = $sth->fetchAll();

  return $posts;
}


//------------------------------  NEXT POSTS  ----------------------------------

function get_next_post ( $current_post, $type = "post" )
{
  global $db;

  $current_id = $current_post['ID'];
  $select_next_post = $db->select( '*', 'posts', "ID >= $current_id AND type='post' ORDER BY ID ASC LIMIT 1,1" );

  $sth = $db->pdo->prepare('
  SELECT *, DATE_FORMAT(date_modified, "%d-%m-%Y") AS date_mod_form
  FROM posts
  WHERE ID >= ? AND type= ? AND status = "public" AND language = "fr"
  ORDER BY ID ASC
  LIMIT 1,1
  ');

  $sth->execute(array($current_id, $type));

  $select_next_post = $sth->fetchAll();

  if ( count($select_next_post) > 0 )
  {
    $next_post = $select_next_post[0];
  }
  else
  {
    $sth = $db->pdo->prepare('
    SELECT *, DATE_FORMAT(date_modified, "%d-%m-%Y") AS date_mod_form
    FROM posts
    WHERE type= ? AND status = "public" AND language = "fr"
    ORDER BY ID ASC
    LIMIT 1,1
    ');

    $sth->execute(array($type));

    $select_next_post = $sth->fetchAll();

    if ( count($select_next_post) > 0 )
    {
      $next_post = $select_next_post[0];
    }
  }

  return $next_post = $select_next_post[0];
}


//------------------------------  NEXT POSTS  ----------------------------------

function get_related_posts ( $current_post, $type = "projet", $limit = 1 )
{
  global $db;
  $current_id = $current_post['ID'];

  // 01 - Récupère les catégories du post

  $sth = $db->pdo->prepare('
  SELECT term_id
  FROM relationships
  WHERE object_id= ?
  ');

  $sth->execute(array($current_id));

  $categories_id = $sth->fetchAll(PDO::FETCH_COLUMN);

  if (empty($categories_id))
  {
    // 01 - Le post n'a pas de categories
    // Retourne les posts récents

    return get_posts( $type, $limit );
  }

  $categories_id_string = implode(',',array_map([$db->pdo,"quote"],$categories_id)) ;

  // 02 - Récupère les ID des posts qui ont une ou plusieurs catégories en commun

  $sth = $db->pdo->prepare('
  SELECT object_id
  FROM relationships
  WHERE term_id IN ( ' . $categories_id_string . ' )
  ');

  $sth->execute();

  $posts_id = $sth->fetchAll(PDO::FETCH_COLUMN);

  if (empty($posts_id))
  {
    // 02 - Aucun post n'a de categorie en commun
    // Retourne les posts récents

    return get_posts( $type, $limit );
  }

  $posts_id_string = implode(',',array_map([$db->pdo,"quote"],$posts_id)) ;

  // 03 - Récupère les posts grace aux ID obtenus

  $sth = $db->pdo->prepare('
  SELECT *
  FROM posts
  WHERE ID != :id AND language = "fr" AND status = "public" AND type = :type AND ID IN ( ' . $posts_id_string . ' )
  ORDER BY ID ASC
  LIMIT :limit
  ');

  $sth->bindParam(':id', $current_id, PDO::PARAM_STR);
  $sth->bindParam(':type', $type, PDO::PARAM_STR);
  $sth->bindParam(':limit', $limit, PDO::PARAM_INT);

  $sth->execute( );

  $posts = $sth->fetchAll();

  if ( count($posts) < $limit )
  {
    // 03 - Il y a moins de post similaire que la limite indiquée
    // Complèter avec des posts récents

    $missing_posts = $limit - count($posts);
  }

  return $posts;

}


//-------------------------------  GET MEDIA  ----------------------------------

function get_media ( $id, $size = "large" )
{
  global $db;

  $media = array();

  if ( $id != "" )
  {
    $sth = $db->pdo->prepare('
    SELECT slug, type, poster, alt, display_name, caption
    FROM uploads
    WHERE ID = ?
    ');

    $sth->execute( array( $id ) );

    $row = $sth->fetchAll();

    if ( count($row) > 0 )
    {
      $row = $row[0];
      $media['slug'] = $row['slug'];
      $media['poster'] = $row['poster'];
      $media['alt'] = $row['alt'];
      $media['display_name'] = $row['display_name'];
      $media['caption'] = $row['caption'];

      if ( preg_match( '/image/', $row['type'] ) )
      {
        // Image

        $media['type'] = 'image';
      }
      else
      {
        // Video

        $media['type'] = 'video';

        // Obtient le poster de la video
        $sth = $db->pdo->prepare('
        SELECT slug
        FROM uploads
        WHERE ID = ?
        ');

        $sth->execute( array( $row['poster'] ) );

        $poster_row = $sth->fetchAll();

        if ( count($poster_row) > 0 )
        {
          $media['poster'] = UPLOADS_URL . 'img/large/' . $poster_row[0]['slug'];
        }
        else
        {
          $media['poster'] = '';
        }
      }

    }
    else
    {
      $media = false;
    }
  }
  else
  {
    $media = false;
  }

  return $media;
}

//----------------------------  FONCTIONS GET  ---------------------------------

// Sommaire :
//
// 01 - Titre
// 02 - Date
// 03 - Description
// 04 - Contenu
// 05 - Miniature
// 06 - Catégories
// 07 - Année


// 01 - Titre

function post_title ( $posts )
{
  return $posts['title'];
}


// 02 - Date

function post_date ( $posts )
{
  return $posts['date_mod_form'];
}


// 03 - Description

function post_description ( $posts )
{
  return $posts['description'];
}


// 04 - Contenu

function post_content ( $post )
{
  global $db;

  $arrayContent = json_decode($post['content'], true);

  foreach ($arrayContent as $key => $value)
  {
    if ( function_exists ($value["type"]) )
    {
      $content = nl2br($value["type"]($value));
    }
    else
    {
      $content = "";
      // $content = "<div><p>Error: this type of section is not defined</p></div>";
    }

    echo $content;
  }
}


// 05 - Miniature

function post_thumb ( $post, $size = "large" )
{
  $post_thumb = get_media( $post['thumb'] );
  if (!$post_thumb) $post_thumb = array('slug' => '');
  return $post_thumb;
}


// 06 - Catégories

function post_categories ( $post )
{
  global $db;

  $r = array(
    'expertise' => array(),
    'domaine' => array(),
    'graphisme' => array(),
  );

  $sth = $db->pdo->prepare('
  SELECT term_id
  FROM relationships
  WHERE object_id = ?
  ');

  $sth->execute( array( $post['ID'] ) );

  $categories_id = $sth->fetchAll(PDO::FETCH_COLUMN);

  if ( count($categories_id ) > 0)
  {
    $test = implode(',',array_map([$db->pdo,"quote"],$categories_id)) ;

    $sth = $db->pdo->prepare('
    SELECT *
    FROM categories
    WHERE ID IN ( ' . $test . ' )
    ');

    $sth->execute(  );

    $categories = $sth->fetchAll( );

    foreach ($categories as $key => $value)
    {
      if ( !isset( $r[ $value['type'] ] ) )
      {
        $r[ $value['type'] ] = array();
      }
      $r[ $value['type'] ][] = $value;
    }
  }

  return $r;

}


// 07 - Année

function post_year ( $posts )
{
  $r = $posts['year'] === "" ? date('Y') : $posts['year'];
  return $r;
}
