<?php
header("Content-Type: application/json");
require_once "../config.php"; // your DB connection

$action = $_POST['action'] ?? $_GET['action'] ?? '';

try {
    switch ($action) {

        // 👉 CREATE publisher
        case 'insert':
            $publisherName = $_POST['PublisherName'] ?? '';
            $rniNumber = $_POST['RniNumber'] ?? '';
            if ($publisherName !== '') {
                $sql = "INSERT INTO tblpublishers (PublisherName, RniNumber) VALUES (:name, :rni)";
                $stmt = $dbh->prepare($sql);
                $stmt->bindParam(':name', $publisherName);
                $stmt->bindParam(':rni', $rniNumber);
                $stmt->execute();
                echo json_encode(["status" => "success", "message" => "Publisher inserted"]);
            } else {
                echo json_encode(["status" => "error", "message" => "Missing PublisherName"]);
            }
            break;

        // 👉 READ all publishers
        case 'view':
        default:
            $stmt = $dbh->query("SELECT * FROM tblpublishers ORDER BY id DESC");
            $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
            if ($data) {
                echo json_encode(["status" => "success", "data" => $data]);
            } else {
                echo json_encode(["status" => "error", "message" => "No publishers found"]);
            }
            break;

        // 👉 UPDATE publisher
        case 'update':
            $id = $_POST['id'] ?? '';
            $publisherName = $_POST['PublisherName'] ?? '';
            $rniNumber = $_POST['RniNumber'] ?? '';

            if ($id !== '' && $publisherName !== '') {
                $sql = "UPDATE tblpublishers 
                        SET PublisherName = :name, RniNumber = :rni, UpdationDate = CURRENT_TIMESTAMP 
                        WHERE id = :id";
                $stmt = $dbh->prepare($sql);
                $stmt->bindParam(':name', $publisherName);
                $stmt->bindParam(':rni', $rniNumber);
                $stmt->bindParam(':id', $id, PDO::PARAM_INT);
                $stmt->execute();
                echo json_encode(["status" => "success", "message" => "Publisher updated"]);
            } else {
                echo json_encode(["status" => "error", "message" => "Missing data"]);
            }
            break;

        // 👉 DELETE publisher
        case 'delete':
            $id = $_POST['id'] ?? '';
            if ($id !== '') {
                $sql = "DELETE FROM tblpublishers WHERE id = :id";
                $stmt = $dbh->prepare($sql);
                $stmt->bindParam(':id', $id, PDO::PARAM_INT);
                $stmt->execute();
                echo json_encode(["status" => "success", "message" => "Publisher deleted"]);
            } else {
                echo json_encode(["status" => "error", "message" => "Missing id"]);
            }
            break;
    }
} catch (Exception $e) {
    echo json_encode(["status" => "error", "message" => $e->getMessage()]);
}
