<?php
require_once '../connect.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
   try {
       $conn->beginTransaction();

       $authorId = $_POST['authorId'];
       
       $getImageQuery = "SELECT author_image FROM author WHERE authorid = :authorId";
       $imageStmt = $conn->prepare($getImageQuery);
       $imageStmt->execute([':authorId' => $authorId]);
       $imageResult = $imageStmt->fetch(PDO::FETCH_ASSOC);
       
       // Delete the author
       $query = "DELETE FROM author WHERE authorid = :authorId";
       $stmt = $conn->prepare($query);
       $stmt->execute([':authorId' => $authorId]);

       // If author had an image, delete the file
       if ($imageResult && $imageResult['author_image']) {
           $imagePath = 'AuthorImages/' . $imageResult['author_image'];
           if (file_exists($imagePath)) {
               unlink($imagePath);
           }
       }

       $conn->commit();
       
       echo json_encode(['success' => true]);

   } catch(PDOException $e) {
       if ($conn->inTransaction()) {
           $conn->rollBack();
       }
       echo json_encode(['success' => false, 'error' => $e->getMessage()]);
   } catch(Exception $e) {
       if ($conn->inTransaction()) {
           $conn->rollBack(); 
       }
       echo json_encode(['success' => false, 'error' => $e->getMessage()]);
   }
}
?>