<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

header('Content-Type: application/json');

require '../connect.php';

try {
   // Start transaction
   $conn->beginTransaction();

   if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
       throw new Exception('Invalid request method');
   }

   $firstName = $_POST['firstName'] ?? '';
   $lastName = $_POST['lastName'] ?? '';
   $nationality = $_POST['nationality'] ?? '';
   $dateOfBirth = $_POST['dateOfBirth'] ?? '';
   $authorDescription = $_POST['authorDescription'] ?? '';

   if (empty($firstName) || empty($lastName) || empty($nationality) || empty($dateOfBirth)) {
       throw new Exception('Required fields cannot be empty');
   }

   // image upload
   $imageName = null;
   if (isset($_FILES['authorImage']) && $_FILES['authorImage']['error'] === UPLOAD_ERR_OK) {
       $uploadDir = '../AuthorImages/';
       /*
       if (!file_exists($uploadDir)) {
           mkdir($uploadDir, 0777, true);
       }*/

       $fileExtension = strtolower(pathinfo($_FILES['authorImage']['name'], PATHINFO_EXTENSION));
       $imageName = uniqid() . '_author.' . $fileExtension;
       $targetPath = $uploadDir . $imageName;

       $allowedTypes = ['jpg', 'jpeg', 'png', 'gif'];
       if (!in_array($fileExtension, $allowedTypes)) {
           throw new Exception('Invalid file type. Only JPG, JPEG, PNG, and GIF are allowed.');
       }

       if (!move_uploaded_file($_FILES['authorImage']['tmp_name'], $targetPath)) {
           throw new Exception('Failed to upload image');
       }
   }

   $sql = "INSERT INTO author (firstname, lastname, nationality, dateofbirth, author_description, author_image) 
           VALUES (:firstname, :lastname, :nationality, :dateofbirth, :author_description, :author_image)";
   
   $stmt = $conn->prepare($sql);
   $stmt->execute([
       ':firstname' => $firstName,
       ':lastname' => $lastName,
       ':nationality' => $nationality,
       ':dateofbirth' => $dateOfBirth,
       ':author_description' => $authorDescription,
       ':author_image' => $imageName
   ]);

   $conn->commit();

   echo json_encode(['success' => true, 'message' => 'Author added successfully']);

} catch (Exception $e) {
   // Rollback the transaction if it's active
   if ($conn->inTransaction()) {
       $conn->rollBack();
   }

   if (isset($imageName) && file_exists($uploadDir . $imageName)) {
       unlink($uploadDir . $imageName);
   }

   echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

?>