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

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

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

        $required = ['authorId', 'firstName', 'lastName', 'nationality', 'dateOfBirth', 'authorDescription'];
        foreach ($required as $field) {
            if (!isset($_POST[$field])) {
                throw new Exception("Missing required field: $field");
            }
        }

        $conn->beginTransaction();
        
        $authorId = $_POST['authorId'];
        $firstName = $_POST['firstName'];
        $lastName = $_POST['lastName'];
        $nationality = $_POST['nationality'];
        $dateOfBirth = $_POST['dateOfBirth'];
        $authorDescription = $_POST['authorDescription'];
        
        $imageName = null;

        if (isset($_FILES['authorImage']) && $_FILES['authorImage']['error'] === UPLOAD_ERR_OK) {
            $uploadDir = __DIR__ . "/../AuthorImages/"; 

            // Create directory if not exists
            if (!file_exists($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }

            $fileExtension = strtolower(pathinfo($_FILES['authorImage']['name'], PATHINFO_EXTENSION));
            $allowedTypes = ['jpg', 'jpeg', 'png', 'gif'];

            if (!in_array($fileExtension, $allowedTypes)) {
                throw new Exception('Invalid file type. Allowed: JPG, JPEG, PNG, GIF.');
            }

            $fileName = uniqid() . '_' . basename($_FILES['authorImage']['name']);
            $targetPath = $uploadDir . $fileName;
        
            if (!move_uploaded_file($_FILES['authorImage']['tmp_name'], $targetPath)) {
                throw new Exception('Failed to upload image.');
            }
            $imageName = $fileName;

            $stmt = $conn->prepare("SELECT author_image FROM author WHERE authorid = ?");
            $stmt->execute([$authorId]);
            $oldImage = $stmt->fetchColumn();
        }

        // Build query
        $query = "UPDATE author SET 
                    firstname = :firstName, 
                    lastname = :lastName, 
                    nationality = :nationality,
                    dateofbirth = :dateOfBirth,
                    author_description = :authorDescription
                  " . ($imageName ? ", author_image = :author_image" : "") . 
                  " WHERE authorid = :authorId";

        $params = [
            ':firstName' => $firstName,
            ':lastName' => $lastName,
            ':nationality' => $nationality,
            ':dateOfBirth' => $dateOfBirth,
            ':authorDescription' => $authorDescription,
            ':authorId' => $authorId
        ];

        if ($imageName) {
            $params[':author_image'] = $imageName;
        }

        $stmt = $conn->prepare($query);
        if (!$stmt->execute($params)) {
            throw new Exception('Failed to update author.');
        }

        if ($imageName && $oldImage) {
            $oldImagePath = __DIR__ . "/../AuthorImages/" . $oldImage;
            if (file_exists($oldImagePath)) {
                unlink($oldImagePath);
            }
        }

        $conn->commit();
        echo json_encode(['success' => true, 'message' => 'Author updated.']);
        
    } catch (Exception $e) {
        $conn->rollBack();
        if (isset($targetPath) && file_exists($targetPath)) {
            unlink($targetPath);
        }
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}
?>