<?php
global $xajax;
$xajax -> register( XAJAX_FUNCTION, 'cloneArticle' );
$xajax -> register( XAJAX_FUNCTION, 'deleteArticleThumbnail' );
$xajax -> register( XAJAX_FUNCTION, 'savePageCookie' );
$xajax -> register( XAJAX_FUNCTION, 'saveArticlesOrder' );

function saveArticlesOrder( $articles, $page_id )
{
  global $db;
  
  if ( is_array( $articles ) )
  {    
    $query = $db -> prepare( 'UPDATE pp_articles_pages SET o = 0 WHERE page_id = :page_id' );
    $query -> bindValue( ':page_id', $page_id, \PDO::PARAM_INT );
    $query -> execute();
    $query -> closeCursor();
    
    for ( $i = 0; $i < count( $articles ); $i++ )
    {
      if ( $articles[$i]['item_id'] )
      {
        $query = $db -> prepare( 'UPDATE pp_articles_pages SET o = :o WHERE article_id = :article_id AND page_id = :page_id' );
        $query -> bindValue( ':article_id', $articles[$i]['item_id'],   \PDO::PARAM_INT );
        $query -> bindValue( ':page_id',    $page_id,                   \PDO::PARAM_INT );
        $query -> bindValue( ':o',          $x,                         \PDO::PARAM_INT );
        $query -> execute();
        $query -> closeCursor();
        $x++;
      }
    }
  }

  \System::deleteCacheAdmin();
  \System::deleteCache();

  $objResponse  = new xajaxResponse();
  $message = '$( ".jqibox" ).remove();;';
  $objResponse -> script( $message );
  return $objResponse;
}

function savePageCookie( $id )
{
  $array = unserialize( $_COOKIE[ 'savePageCookie' ] );
  
  if ( $array[ $id ] == 0 )
    $array[ $id ] = 1;
  else
    $array[ $id ] = 0;
  
  $array = serialize( $array );
  
  setcookie( 'savePageCookie', $array, time() + 3600 * 24 * 365 );
}

function deleteArticleThumbnail( $id )
{
  global $db;
  
  try {
    $query = $db -> prepare( 'SELECT thumbnail FROM pp_articles WHERE id = :id AND thumbnail IS NOT NULL' );
    $query -> bindValue( ':id', $id, \PDO::PARAM_INT );
    $query -> execute();
    if ( $query -> rowCount() ) while ( $row = $query -> fetch() )
    {
      if ( file_exists( '../' . $row['thumbnail'] ) )
      {
        if ( !unlink( '../' . $row['thumbnail'] ) )
          echo 'Brak możliwości usunięcia zdjęcia';
        else
        {
          $query2 = $db -> prepare( 'UPDATE pp_articles SET thumbnail = NULL WHERE id = :id' );
          $query2 -> bindValue( ':id', $id, \PDO::PARAM_INT );
          $query2 -> execute();
          $query2 -> closeCursor();
        }
      }
    }
    $query -> closeCursor();
  }
  catch ( PDOException $e )
  {
    echo 'Błąd: ' . $e -> getMessage();
  }
  
  $ajax = new xajaxResponse;
  $ajax -> script( '$( ".thumbnail, .thumbnail-delete" ).remove();' );
  return $ajax;
}

function cloneArticle( $id )
{ 
  if ( \admin\factory\Articles::cloneArticle( $id ) )
    \System::setAlert( 'Artykuł został zduplikowany.' );
  
  $ajax = new xajaxResponse;
  $ajax -> script( 'document.location.href="./";' );
  return $ajax;
}