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

if (strlen($_SESSION['alogin']) == 0) {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

try {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $id = isset($_POST['publisherId']) ? intval($_POST['publisherId']) : 0;
        $rniNumber = trim($_POST['rniNumber']);
        $publisherName = trim($_POST['publisherName']);

        if (empty($publisherName)) {
            echo json_encode(['status' => 'error', 'message' => 'Publisher name is required']);
            exit;
        }

        if ($id > 0) {
            // ✅ Update publisher
            $sql = "UPDATE tblpublishers 
                    SET RniNumber = :rniNumber, PublisherName = :publisherName 
                    WHERE id = :id";
            $query = $dbh->prepare($sql);
            $query->bindParam(':rniNumber', $rniNumber, PDO::PARAM_STR);
            $query->bindParam(':publisherName', $publisherName, PDO::PARAM_STR);
            $query->bindParam(':id', $id, PDO::PARAM_INT);
            $query->execute();
            echo json_encode(['status' => 'success', 'message' => 'Publisher updated successfully']);
        } else {
            // ✅ Insert new publisher
            $sql = "INSERT INTO tblpublishers (RniNumber, PublisherName) 
                    VALUES (:rniNumber, :publisherName)";
            $query = $dbh->prepare($sql);
            $query->bindParam(':rniNumber', $rniNumber, PDO::PARAM_STR);
            $query->bindParam(':publisherName', $publisherName, PDO::PARAM_STR);
            $query->execute();
            echo json_encode(['status' => 'success', 'message' => 'Publisher added successfully']);
        }
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Invalid request']);
    }
} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>
