<?php
session_start();
if (!isset($_SESSION['user'])) {
  header('Location: login.php'); exit;
}
require '../src/db.php';

// Directorios de subida
$uploadPdfDir    = __DIR__ . '/uploads/pdfs';
$uploadPortDir   = __DIR__ . '/uploads/portadas';

// Crear carpetas si no existen
foreach ([$uploadPdfDir, $uploadPortDir] as $dir) {
  if (!is_dir($dir)) {
    mkdir($dir, 0777, true);
  }
}

$cats     = $pdo->query("SELECT * FROM categorias")->fetchAll();
$errors   = [];
$success  = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $t = trim($_POST['titulo']);
  $a = trim($_POST['autor']);
  $c = intval($_POST['categoria']);
  $d = trim($_POST['descripcion']);

  if (!$t || !$a || !$c) {
    $errors[] = "Completa todos los campos obligatorios.";
  }

  // Procesar PDF y portada solo si no hay errores previos
  if (empty($errors)) {
    // Validar subida PDF
    if (!isset($_FILES['pdf']) || $_FILES['pdf']['error'] !== UPLOAD_ERR_OK) {
      $errors[] = "Debes subir un PDF válido.";
    } else {
      $pdfName = uniqid() . '_' . basename($_FILES['pdf']['name']);
      $pdfDest = "$uploadPdfDir/$pdfName";
      if (!move_uploaded_file($_FILES['pdf']['tmp_name'], $pdfDest)) {
        $errors[] = "Error subiendo el PDF.";
      }
    }

    // Validar subida Portada
    if (!isset($_FILES['portada']) || $_FILES['portada']['error'] !== UPLOAD_ERR_OK) {
      $errors[] = "Debes subir una portada válida.";
    } else {
      $imgName = uniqid() . '_' . basename($_FILES['portada']['name']);
      $imgDest = "$uploadPortDir/$imgName";
      if (!move_uploaded_file($_FILES['portada']['tmp_name'], $imgDest)) {
        $errors[] = "Error subiendo la portada.";
      }
    }
  }

  // Insertar en BD
  if (empty($errors)) {
    $stmt = $pdo->prepare("
      INSERT INTO libros
        (titulo, autor, categoria_id, descripcion, archivo, portada)
      VALUES (?, ?, ?, ?, ?, ?)
    ");
    $stmt->execute([$t, $a, $c, $d, $pdfName, $imgName]);
    $success = "Libro agregado correctamente.";
    header('Location: index.php?tab=manage');
exit;
  }
}
?>
