<?php
require_once __DIR__ . "/../config/db.php";
require_once __DIR__ . "/../lib/auth.php";
require_once __DIR__ . "/../lib/helpers.php";
require_once __DIR__ . "/../admin/admin_menu.php";

require_admin();

$id=$_GET['edit'] ?? null;

$item=['title'=>'','slug'=>'','cover'=>'','pdf_file'=>''];

if($id){
  $st=$pdo->prepare("SELECT * FROM journals WHERE id=?");
  $st->execute([$id]);
  $item=$st->fetch();
}

if($_SERVER['REQUEST_METHOD']=='POST'){

$title=$_POST['title'];
$slug=slugify($title);

$cover=$item['cover'];
$pdf=$item['pdf_file'];

if(!empty($_FILES['cover']['name'])){
  $name=time().$_FILES['cover']['name'];
  move_uploaded_file($_FILES['cover']['tmp_name'],__DIR__."/../uploads/journals/".$name);
  $cover=$name;
}

if(!empty($_FILES['pdf_file']['name'])){
  $name=time().$_FILES['pdf_file']['name'];
  move_uploaded_file($_FILES['pdf_file']['tmp_name'],__DIR__."/../uploads/journals/".$name);
  $pdf=$name;
}

if($id){
$q=$pdo->prepare("UPDATE journals SET title=?,slug=?,cover=?,pdf_file=? WHERE id=?");
$q->execute([$title,$slug,$cover,$pdf,$id]);
}else{
$q=$pdo->prepare("INSERT INTO journals(title,slug,cover,pdf_file) VALUES(?,?,?,?)");
$q->execute([$title,$slug,$cover,$pdf]);
}

header("Location: journals.php");
exit;
}
?>

<form method="post" enctype="multipart/form-data">

Başlıq
<input name="title" value="<?=$item['title']?>">

Cover
<input type="file" name="cover">

PDF
<input type="file" name="pdf_file">

<button>Yadda saxla</button>

</form>