<?php
session_start();
include('includes/config.php');
header('Content-Type: application/json');

try {
    if($_SERVER['REQUEST_METHOD']==='POST'){
        $id = isset($_POST['hidden_id']) ? intval($_POST['hidden_id']) : 0;
        $author_id = trim($_POST['author_id']);
        $author_name = trim($_POST['author_name']);

        if(empty($author_name) || empty($author_id)){
            echo json_encode(['status'=>'error','message'=>'Author ID and Name are required']);
            exit;
        }

        if($id > 0){
            // Update
            $sql = "UPDATE tblauthors SET AuthorName=:author_name WHERE id=:id";
            $stmt = $dbh->prepare($sql);
            $stmt->bindParam(':author_name',$author_name);
            $stmt->bindParam(':id',$id);
            $stmt->execute();
            echo json_encode(['status'=>'success','message'=>'Author updated successfully']);
        } else {
            // Insert
            $sql = "INSERT INTO tblauthors (AuthorID, AuthorName) VALUES (:author_id, :author_name)";
            $stmt = $dbh->prepare($sql);
            $stmt->bindParam(':author_id',$author_id);
            $stmt->bindParam(':author_name',$author_name);
            $stmt->execute();
            echo json_encode(['status'=>'success','message'=>'Author added successfully']);
        }
    } else {
        echo json_encode(['status'=>'error','message'=>'Invalid request']);
    }
}catch(Exception $e){
    echo json_encode(['status'=>'error','message'=>$e->getMessage()]);
}
?>
