<?php
include('includes/config.php');

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

$draw   = isset($_POST['draw']) ? intval($_POST['draw']) : 0;
$start  = isset($_POST['start']) ? intval($_POST['start']) : 0;
$length = isset($_POST['length']) ? intval($_POST['length']) : 10;
$searchValue = $_POST['search']['value'] ?? '';

$where = " WHERE is_deleted = 0 ";

if (!empty($searchValue)) {
    $searchValue = "%$searchValue%";
    $where .= " AND (PublisherName LIKE :search OR RniNumber LIKE :search)";
}

/* ---------- TOTAL RECORDS ---------- */
$totalStmt = $dbh->query("SELECT COUNT(*) FROM tblpublishers WHERE is_deleted = 0");
$totalRecords = $totalStmt->fetchColumn();

/* ---------- FILTERED RECORDS ---------- */
$countSql = "SELECT COUNT(*) FROM tblpublishers $where";
$countStmt = $dbh->prepare($countSql);

if (!empty($_POST['search']['value'])) {
    $countStmt->bindParam(':search', $searchValue, PDO::PARAM_STR);
}

$countStmt->execute();
$totalFiltered = $countStmt->fetchColumn();

/* ---------- FETCH DATA ---------- */
$dataSql = "SELECT * FROM tblpublishers
            $where
            ORDER BY id DESC
            LIMIT $start, $length";

$dataStmt = $dbh->prepare($dataSql);

if (!empty($_POST['search']['value'])) {
    $dataStmt->bindParam(':search', $searchValue, PDO::PARAM_STR);
}

$dataStmt->execute();

$data = [];
$counter = $start + 1;

while ($row = $dataStmt->fetch(PDO::FETCH_ASSOC)) {

    $actions = '
        <button class="btn btn-sm btn-info"
            onclick="editPublisher(' . $row['id'] . ', \'' . htmlspecialchars($row['RniNumber']) . '\', \'' . htmlspecialchars($row['PublisherName']) . '\')">
            <i class="fa fa-edit"></i> Edit
        </button>
        <a href="manage-publishers.php?del=' . $row['id'] . '"
           onclick="return confirm(\'Are you sure you want to delete this publisher?\');"
           class="btn btn-sm btn-danger">
            <i class="fa fa-trash"></i> Delete
        </a>
    ';

    $data[] = [
        $counter++,
        htmlspecialchars($row['RniNumber']),
        htmlspecialchars($row['PublisherName']),
        $actions
    ];
}

echo json_encode([
    "draw" => $draw,
    "recordsTotal" => intval($totalRecords),
    "recordsFiltered" => intval($totalFiltered),
    "data" => $data
]);

exit;