<?php
error_reporting(E_ALL ^ E_NOTICE ^ E_STRICT ^ E_WARNING ^ E_DEPRECATED);
function __autoload_my_classes($classname)
{
  $q = explode('\\', $classname);
  $c = array_pop($q);
  $f = 'autoload/' . implode('/', $q) . '/class.' . $c . '.php';

  if (file_exists($f))
    require_once($f);
}
spl_autoload_register('__autoload_my_classes');
date_default_timezone_set('Europe/Warsaw');

require_once 'config.php';
require_once 'libraries/medoo/medoo.php';

session_start();

if (!isset($_SESSION['check']))
{
  session_regenerate_id();
  $_SESSION['check']  = true;
  $_SESSION['ip']     = $_SERVER['REMOTE_ADDR'];
}

if ($_SESSION['ip'] !== $_SERVER['REMOTE_ADDR'])
{
  session_destroy();
  header('Location: /');
  exit;
}

$mdb = new medoo([
  'database_type' => 'mysql',
  'database_name' => $database['name'],
  'server'        => $database['host'],
  'username'      => $database['user'],
  'password'      => $database['password'],
  'charset'       => 'utf8'
]);

$settings = \front\factory\Settings::settings_details();

if ( \S::get('action') == 'add_article' )
{
  // table pp_articles
  $show_title = 1;
  $show_table_of_contents = 1;
  $show_date_add = 1;
  $show_date_modify = 0;
  $date_add = date('Y-m-d H:i:s');
  $date_modify = date('Y-m-d H:i:s');
  $modify_by = 0;
  $layout_id = null;
  $status = 1;
  $repeat_entry = 0;
  $social_icons = 0;
  $date_start = null;
  $date_end = null;
  $priority = 0;
  $password = null;
  $pixieset = 0;
  $hash = null;
  $views = 0;
  $id_author = null;

  $mdb->insert( 'pp_articles', [
    'show_title' => $show_title,
    'show_table_of_contents' => $show_table_of_contents,
    'show_date_add' => $show_date_add,
    'show_date_modify' => $show_date_modify,
    'date_add' => $date_add,
    'date_modify' => $date_modify,
    'modify_by' => $modify_by,
    'layout_id' => $layout_id,
    'status' => $status,
    'repeat_entry' => $repeat_entry,
    'social_icons' => $social_icons,
    'date_start' => $date_start,
    'date_end' => $date_end,
    'priority' => $priority,
    'password' => $password,
    'pixieset' => $pixieset,
    'hash' => $hash,
    'views' => $views,
    'id_author' => $id_author
  ]);

  $article_id = $mdb->id();
  if ( !$article_id )
  {
    echo 'Error: ' . $mdb->error()[2];
    exit;
  }

  $file = $_FILES['main_image'];
  if ($file)
  {
    // Wyciągnięcie rozszerzenia oryginalnego pliku
    // Określenie rozszerzenia na podstawie typu MIME (zabezpieczenie przed fałszywymi nazwami plików)
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mimeType = $finfo->file($file['tmp_name']);

    // Mapowanie do rozszerzeń
    $allowedTypes = [
        'image/jpeg' => 'jpg',
        'image/png'  => 'png',
        'image/gif'  => 'gif',
        'image/webp' => 'webp'
    ];

    if (!isset($allowedTypes[$mimeType])) {
        http_response_code(400);
        echo json_encode(['error' => 'Nieobsługiwany typ pliku.']);
        exit;
    }

    $ext = $allowedTypes[$mimeType];
    // Tworzenie ścieżki katalogu docelowego
    $baseDir = __DIR__ . '/upload/filemanager/api';
    $targetDir = $baseDir . '/article_' . $article_id;

    // Jeżeli katalog nie istnieje, utwórz go
    if (!is_dir($targetDir))
    {
      mkdir( $targetDir, 0755, true );
    }

    // Nowa nazwa pliku: article_{id}.{ext}
    $targetName = 'article_' . $article_id . '.' . $ext;
    $targetPath = $targetDir . '/' . $targetName;

    // Przeniesienie pliku z tmp na docelową ścieżkę
    move_uploaded_file($file['tmp_name'], $targetPath);

    // Zwrócenie adresu URL do pliku (względem katalogu webroot)
    $publicUrl = '/upload/filemanager/api/article_' . $article_id . '/' . $targetName;
  }
  else
  {
    $publicUrl = null;
  }

  // table pp_articles_langs
  $lang_id = 'pl';
  $title = \S::get('title');
  $main_image = $publicUrl; // to do
  $entry = \S::get('entry');
  $text = \S::get('text');
  $table_of_contents = null;
  $meta_title = null;
  $meta_description = null;
  $meta_keywords = null;
  $seo_link = \S::seo(\S::get('title'));
  $noindex = 0;
  $copy_from = null;
  $block_direct_access = 0;

  $mdb -> insert( 'pp_articles_langs', [
    'lang_id' => $lang_id,
    'article_id' => $article_id,
    'title' => $title,
    'main_image' => $main_image,
    'entry' => $entry,
    'text' => $text,
    'table_of_contents' => $table_of_contents,
    'meta_title' => $meta_title,
    'meta_description' => $meta_description,
    'meta_keywords' => $meta_keywords,
    'seo_link' => $seo_link,
    'noindex' => $noindex,
    'copy_from' => $copy_from,
    'block_direct_access' => $block_direct_access
  ]);

  $page_id = \S::get( 'page_id' );
  $o = $mdb -> max( 'pp_articles_pages', 'o', [ 'page_id' => $page_id ] ) + 1;

  $mdb -> insert( 'pp_articles_pages', [
    'page_id' => $page_id,
    'article_id' => $article_id,
    'o' => $o
  ]);

  echo '{"status": "ok", "id": ' . $article_id . ', "title": "' . $title . '", "main_image": "' . $main_image . '"}';
}
