<?php
session_start();
include('includes/config.php');
function toRoman($number)
{
    $map = [
        'M' => 1000,
        'CM' => 900,
        'D' => 500,
        'CD' => 400,
        'C' => 100,
        'XC' => 90,
        'L' => 50,
        'XL' => 40,
        'X' => 10,
        'IX' => 9,
        'V' => 5,
        'IV' => 4,
        'I' => 1
    ];

    $result = '';
    foreach ($map as $roman => $value) {
        while ($number >= $value) {
            $result .= $roman;
            $number -= $value;
        }
    }
    return $result;
}

$limit = intval($_POST['limit']);
$offset = intval($_POST['offset']);

$degree = $_POST['degree'] ?? '';
$department = $_POST['department'] ?? '';
$search = trim($_POST['search'] ?? '');

$sql = "SELECT b.id, b.BookName, b.Edition,
        c.degree_name, d.department_name
        FROM tblbooks b
        LEFT JOIN tbldegree c ON c.degree_id = b.degree_id
        LEFT JOIN tbldepartment d ON d.department_id = b.department_id
        WHERE b.current_count > 0
        AND b.BookName iS NOT NULL";

$params = [];

if ($degree !== '') {
    $sql .= " AND b.degree_id = :degree";
    $params[':degree'] = $degree;
}

if ($department !== '') {
    $sql .= " AND b.department_id = :department";
    $params[':department'] = $department;
}

if ($search !== '') {
    $sql .= " AND b.BookName LIKE :search";
    $params[':search'] = "%$search%";
}

$sql .= " ORDER BY b.BookName ASC LIMIT :offset, :limit";

$stmt = $dbh->prepare($sql);

foreach ($params as $key => $val) {
    $stmt->bindValue($key, $val);
}

$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->execute();

$cnt = $offset + 1;

while ($row = $stmt->fetch(PDO::FETCH_OBJ)) {
    echo "<tr>
            <td>{$cnt}</td>
            <td>" . htmlentities($row->BookName) . "</td>
            <td>" . htmlentities($row->degree_name) . "</td>
            <td>" . htmlentities($row->department_name) . "</td>
            <td>";
    echo is_numeric($row->Edition)
        ? toRoman((int) $row->Edition)
        : htmlentities($row->Edition);
    echo "</td>
            <!-- <td><span class='badge badge-available'>Available</span></td> -->
            <td>
                <button class='btn btn-sm btn-info viewBookBtn' data-id='{$row->id}'>
                    <i class='fa fa-eye'></i> View
                </button>
            </td>
        </tr>";
    $cnt++;
}
