<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
include('includes/config.php'); // expects $dbh (PDO)
date_default_timezone_set('Asia/Kolkata');
$updatetime = date('Y-m-d H:i:s');
if (strlen($_SESSION['alogin']) == 0) {
    header('location:index.php');
    exit;
}

// Set timezone
date_default_timezone_set('Asia/Kolkata');

// ---------- Helper: compute fine for an issue ----------
function compute_fine_amount(PDO $dbh, int $issue_id, ?string $dueDateStr = null): float
{
    // Get per day fine from tblfine_master
    $perDayFine = 10.0;
    try {
        $q = $dbh->prepare("SELECT fine_per_day FROM tblfine_master LIMIT 1");
        $q->execute();
        if ($r = $q->fetch(PDO::FETCH_OBJ)) {
            $perDayFine = (float) $r->fine_per_day;
        }
    } catch (Exception $e) {
        // fallback to default 10
        $perDayFine = 10.0;
    }

    // If due date provided use it; otherwise fetch from tblissuedbookdetails
    if ($dueDateStr === null) {
        $qq = $dbh->prepare("SELECT DueDate FROM tblissuedbookdetails WHERE id = :id LIMIT 1");
        $qq->bindParam(':id', $issue_id, PDO::PARAM_INT);
        $qq->execute();
        $row = $qq->fetch(PDO::FETCH_OBJ);
        $dueDateStr = $row->DueDate ?? null;
    }

    if (!$dueDateStr)
        return 0.0;

    $due = new DateTime($dueDateStr);
    $today = new DateTime();
    if ($today <= $due)
        return 0.0;

    $interval = $today->diff($due);
    $overdueDays = (int) $interval->days;
    return $overdueDays * $perDayFine;
}
// ---------- AJAX: Damaged or Lost ----------
if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    isset($_POST['ajax']) && $_POST['ajax'] === '1' &&
    isset($_POST['action']) && $_POST['action'] === 'mark_damage_lost'
) {
    header('Content-Type: application/json');

    $issue_id = intval($_POST['issue_id'] ?? 0);
    $book_id = intval($_POST['book_id'] ?? 0);
    $copy_id = intval($_POST['copy_id'] ?? 0);
    $condition = trim($_POST['condition_type'] ?? '');
    $reason = trim($_POST['reason'] ?? '');
    $admin_id = $_SESSION['id'] ?? 0; // admin ID from session

    if ($issue_id <= 0 || $book_id <= 0 || $copy_id <= 0 || !$condition) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid data provided.']);
        exit;
    }

    try {
        $dbh->beginTransaction();

        // Step 0: Fetch old book status
        $oldStatusQ = $dbh->prepare("SELECT book_status FROM tblbookcopies WHERE id=:copyid");
        $oldStatusQ->bindParam(':copyid', $copy_id, PDO::PARAM_INT);
        $oldStatusQ->execute();
        $oldStatus = $oldStatusQ->fetchColumn();

        // Step 1: Update book copy status
        $copyStatus = strtolower($condition); // 'damaged' or 'lost'
        $updateCopy = $dbh->prepare("UPDATE tblbookcopies SET book_status=:status WHERE id=:copyid");
        $updateCopy->bindParam(':status', $copyStatus);
        $updateCopy->bindParam(':copyid', $copy_id, PDO::PARAM_INT);
        $updateCopy->execute();

        // Step 2: Insert into reason history
        $insertReason = $dbh->prepare("
            INSERT INTO tblbookcopy_reason_history 
            (copy_id, old_status, new_status, reason, changed_by, changed_at)
            VALUES (:copyid, :old_status, :new_status, :reason, :updated_by, :updatetime)
        ");
        $insertReason->bindParam(':copyid', $copy_id, PDO::PARAM_INT);
        $insertReason->bindParam(':old_status', $oldStatus);
        $insertReason->bindParam(':new_status', $copyStatus);
        $insertReason->bindParam(':reason', $reason);
        $insertReason->bindParam(':updated_by', $admin_id, PDO::PARAM_INT);
        $insertReason->bindParam(':updatetime', $current_time);

        $insertReason->execute();

        // Step 3: Update available book count
        $cntQ = $dbh->prepare("SELECT COUNT(*) FROM tblbookcopies WHERE book_id=:bid AND book_status='available'");
        $cntQ->bindParam(':bid', $book_id, PDO::PARAM_INT);
        $cntQ->execute();
        $availableCount = (int) $cntQ->fetchColumn();

        $updBook = $dbh->prepare("UPDATE tblbooks SET current_count=:cc WHERE id=:bid");
        $updBook->bindParam(':cc', $availableCount, PDO::PARAM_INT);
        $updBook->bindParam(':bid', $book_id, PDO::PARAM_INT);
        $updBook->execute();

        // Step 4: Update issue record return status
        $statusMap = ['damaged' => 2, 'lost' => 3]; // 2 = Damaged, 3 = Lost
        $returnStatus = $statusMap[$copyStatus] ?? 1; // fallback 1 = normal return

        $updateIssue = $dbh->prepare("
            UPDATE tblissuedbookdetails 
            SET ReturnDate=:updatetime, RetrunStatus=:rs 
            WHERE id=:issueid
        ");
        $updateIssue->bindParam(':rs', $returnStatus, PDO::PARAM_INT);
        $updateIssue->bindParam(':issueid', $issue_id, PDO::PARAM_INT);
        $updateIssue->bindParam(':updatetime', $updatetime);

        $updateIssue->execute();

        $dbh->commit();

        echo json_encode([
            'status' => 'success',
            'message' => "Book marked as {$condition} successfully and reason logged."
        ]);

    } catch (Exception $e) {
        $dbh->rollBack();
        echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()]);
    }

    exit;
}


// ------------------- AJAX: process fine modal -------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax']) && $_POST['ajax'] === '1' && isset($_POST['action']) && $_POST['action'] === 'process_fine') {
    header('Content-Type: application/json');

    $issue_id = intval($_POST['issue_id'] ?? 0);
    if ($issue_id <= 0) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid issue id']);
        exit;
    }

    // Payment status must be provided
    $payment_status = trim($_POST['payment_status'] ?? '');
    if ($payment_status !== 'Paid' && $payment_status !== 'Unpaid') {
        echo json_encode(['status' => 'error', 'message' => 'Invalid payment status']);
        exit;
    }

    // Recompute fine server-side (do not trust client-sent fine)
    $fine_amount = compute_fine_amount($dbh, $issue_id);

    // Use posted actual_amount if given and paid, otherwise default to fine_amount
    $actual_amount_post = trim($_POST['actual_amount'] ?? '');
    $actual_amount = null;
    if ($payment_status === 'Paid') {
        if ($actual_amount_post !== '') {
            $actual_amount = (float) $actual_amount_post;
        } else {
            $actual_amount = $fine_amount;
        }
    }

    $payment_mode = trim($_POST['payment_mode'] ?? '');
    $remarks = trim($_POST['remarks'] ?? '');
    $payment_date = date('Y-m-d H:i:s');

    try {
        // fetch issue info
        $q = $dbh->prepare("SELECT BookId, CopyId, DueDate, ReturnDate FROM tblissuedbookdetails WHERE id = :id LIMIT 1");
        $q->bindParam(':id', $issue_id, PDO::PARAM_INT);
        $q->execute();
        $issue = $q->fetch(PDO::FETCH_OBJ);
        if (!$issue) {
            echo json_encode(['status' => 'error', 'message' => 'Issue record not found.']);
            exit;
        }

        // Insert into tblfine_payments
        $ins = $dbh->prepare("INSERT INTO tblfine_payments (tblissuedbookdetailsid, fine_amount, payment_status, payment_mode, actual_amount, remarks, payment_date)
                              VALUES (:issue_id, :fine_amount, :payment_status, :payment_mode, :actual_amount, :remarks, :payment_date)");
        $ins->bindValue(':issue_id', $issue_id, PDO::PARAM_INT);
        $ins->bindValue(':fine_amount', $fine_amount);
        $ins->bindValue(':payment_status', $payment_status);
        $ins->bindValue(':payment_mode', $payment_mode);
        if ($actual_amount === null)
            $ins->bindValue(':actual_amount', null, PDO::PARAM_NULL);
        else
            $ins->bindValue(':actual_amount', $actual_amount);
        $ins->bindValue(':remarks', $remarks);
        $ins->bindValue(':payment_date', $payment_date);
        $ins->execute();

        // If Paid => mark returned, update copy and book counts
        if ($payment_status === 'Paid') {
            // Update tblissuedbookdetails: fine + ReturnDate + RetrunStatus
            $returndate = $payment_date;
            $upd = $dbh->prepare("UPDATE tblissuedbookdetails SET fine = :fine, ReturnDate = :returndate, RetrunStatus = 1 WHERE id = :id");
            $upd->bindValue(':fine', $fine_amount);
            $upd->bindValue(':returndate', $returndate);
            $upd->bindValue(':id', $issue_id, PDO::PARAM_INT);
            $upd->execute();

            // Update copy to available
            $updCopy = $dbh->prepare("UPDATE tblbookcopies SET book_status = 'available' WHERE id = :copyid");
            $updCopy->bindValue(':copyid', $issue->CopyId, PDO::PARAM_INT);
            $updCopy->execute();

            // Increment book current_count
            $updBook = $dbh->prepare("UPDATE tblbooks SET current_count = current_count + 1 WHERE id = :bookid");
            $updBook->bindValue(':bookid', $issue->BookId, PDO::PARAM_INT);
            $updBook->execute();

            echo json_encode(['status' => 'success', 'message' => "Fine collected ₹" . number_format((float) $fine_amount, 2) . ". Book returned."]);
            exit;
        } else {
            // Unpaid: just update fine column on issue record so UI shows it
            $upd = $dbh->prepare("UPDATE tblissuedbookdetails SET fine = :fine WHERE id = :id");
            $upd->bindValue(':fine', $fine_amount);
            $upd->bindValue(':id', $issue_id, PDO::PARAM_INT);
            $upd->execute();

            echo json_encode(['status' => 'success', 'message' => "Fine recorded as unpaid: ₹" . number_format((float) $fine_amount, 2) . "."]);
            exit;
        }
    } catch (Exception $e) {
        // error
        echo json_encode(['status' => 'error', 'message' => 'Server error: ' . $e->getMessage()]);
        exit;
    }
}

// ----------------- POST: Manual update_fine (legacy button) -----------------
// We'll compute fine on server-side (ignore posted manual fine), then mark as returned
if (isset($_POST['update_fine'])) {
    $rid = intval($_POST['rid'] ?? 0);
    if ($rid <= 0) {
        $_SESSION['error'] = "Invalid record.";
        header("Location: manage-issued-books.php");
        exit;
    }

    // Compute fine using helper
    $fine = compute_fine_amount($dbh, $rid);

    // fetch issue row
    $sql = "SELECT BookId, CopyId, ReturnDate FROM tblissuedbookdetails WHERE id = :rid";
    $query = $dbh->prepare($sql);
    $query->bindParam(':rid', $rid, PDO::PARAM_INT);
    $query->execute();
    $issue = $query->fetch(PDO::FETCH_OBJ);

    if ($issue) {
        if (!empty($issue->ReturnDate)) {
            $_SESSION['error'] = "Book already returned.";
            header("Location: manage-issued-books.php");
            exit;
        }

        $returndate = date('Y-m-d H:i:s');

        $updateSql = "UPDATE tblissuedbookdetails 
                      SET fine = :fine, ReturnDate = :returndate, RetrunStatus = 1 
                      WHERE id = :rid";
        $updateQuery = $dbh->prepare($updateSql);
        $updateQuery->bindValue(':fine', $fine, PDO::PARAM_STR);
        $updateQuery->bindValue(':returndate', $returndate);
        $updateQuery->bindValue(':rid', $rid, PDO::PARAM_INT);
        $updateQuery->execute();

        // Update copy & book counts
        $updateCopy = $dbh->prepare("UPDATE tblbookcopies SET book_status='available' WHERE id=:copyid");
        $updateCopy->bindParam(':copyid', $issue->CopyId, PDO::PARAM_INT);
        $updateCopy->execute();

        $updateBook = $dbh->prepare("UPDATE tblbooks SET current_count = current_count + 1 WHERE id=:bookid");
        $updateBook->bindParam(':bookid', $issue->BookId, PDO::PARAM_INT);
        $updateBook->execute();

        $_SESSION['msg'] = "Fine updated (computed ₹" . number_format((float) $fine, 2) . ") and book returned successfully.";
    } else {
        $_SESSION['error'] = "Issue record not found.";
    }

    header("Location: manage-issued-books.php");
    exit;
}


// ----------------- Normal return via GET (no fine) -----------------
if (isset($_GET['returnid'])) {
    $issue_id = intval($_GET['returnid']);
    $sql = "SELECT BookId, CopyId, fine, ReturnDate FROM tblissuedbookdetails WHERE id=:issue_id";
    $query = $dbh->prepare($sql);
    $query->bindParam(':issue_id', $issue_id, PDO::PARAM_INT);
    $query->execute();
    $issue = $query->fetch(PDO::FETCH_OBJ);

    if ($issue && empty($issue->ReturnDate)) {
        if ($issue->fine > 0) {
            $_SESSION['error'] = "Please collect fine ₹" . $issue->fine . " before returning.";
            header("Location: manage-issued-books.php");
            exit;
        }

        $returndate = date('Y-m-d H:i:s');

        $updateSql = "UPDATE tblissuedbookdetails SET ReturnDate=:returndate, RetrunStatus=1 WHERE id=:issue_id";
        $updateQuery = $dbh->prepare($updateSql);
        $updateQuery->bindParam(':returndate', $returndate);
        $updateQuery->bindParam(':issue_id', $issue_id, PDO::PARAM_INT);
        $updateQuery->execute();

        $updateCopy = $dbh->prepare("UPDATE tblbookcopies SET book_status='available' WHERE id=:copyid");
        $updateCopy->bindParam(':copyid', $issue->CopyId, PDO::PARAM_INT);
        $updateCopy->execute();

        $updateBook = $dbh->prepare("UPDATE tblbooks SET current_count=current_count+1 WHERE id=:bookid");
        $updateBook->bindParam(':bookid', $issue->BookId, PDO::PARAM_INT);
        $updateBook->execute();

        $_SESSION['msg'] = "Book returned successfully.";
    } else {
        $_SESSION['error'] = "Book already returned or not found.";
    }

    // -----------------------
    // Redirect preserving filters
    // -----------------------


    $from = isset($_GET['from']) ? urlencode($_GET['from']) : '';
    $to = isset($_GET['to']) ? urlencode($_GET['to']) : '';
    $usertype = isset($_GET['usertype']) ? urlencode($_GET['usertype']) : '';

    $redirectUrl = "manage-issued-books.php?date_filter_type=return";
    if ($from !== '')
        $redirectUrl .= "&from={$from}";
    if ($to !== '')
        $redirectUrl .= "&to={$to}";
    if ($usertype !== '')
        $redirectUrl .= "&usertype={$usertype}";

    header("Location: {$redirectUrl}");
    exit;
}


?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Manage Issued Books | Library System</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="../<?php echo $_SESSION['logo']; ?>">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap4.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

    <!-- Flatpickr Core -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">

    <!-- ✅ Add Theme -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/themes/airbub.css">

    <style>
        .badge-student {
            background: #28a745;
            color: #fff;
        }

        .badge-staff {
            background: #007bff;
            color: #fff;
        }

        .table-wrapper {
            overflow-x: auto;
            padding: 10px;
        }

        .square-card {
            width: 100%;
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            box-shadow: 0 4px 8px rgba(0, 0, 0, .05);
            border-radius: 5px;
        }

        .flash-message {
            max-width: 600px;
            margin: 0 auto 15px;
        }

        /* Make select2 take full width */
        .select2-container {
            width: 100% !important;
        }

        #bookid+.select2-container {
            width: 750px !important;
        }

        .select2-selection {
            height: 38px !important;
            display: flex !important;
            align-items: center;
            border: 1px solid #ced4da;
            border-radius: 4px;
        }

        .table-success {
            background-color: #d4edda !important;
            transition: background-color 0.6s ease;
        }

        .flatpickr-day:hover,
        .flatpickr-day.today:hover {
            background: #c9f0ddff !important;
        }

        .flatpickr-day.selected {
            background:
                <?php echo $_SESSION['theme_color']; ?>
                !important;
            color: #fff !important;
        }

        .flatpickr-months .flatpickr-month,
        .flatpickr-weekdays .flatpickr-weekday {
            color: #000 !important;
            font-weight: 600;
        }
    </style>

</head>

<body>
    <div class="d-flex flex-column min-vh-100">
        <?php include('includes/header.php'); ?>


        <div class="main-content flex-grow-1">
            <div class="row pad-botm mb-4">
                <div class="col-md-12">
                    <h5 class="header-line" style="color:#0d6efd;"><i class="fa fa-book-reader mr-2"></i>MANAGE ISSUED
                        BOOKS</h5>
                </div>
            </div>

            <!-- Flash Messages -->
            <div class="row justify-content-center">
                <div class="col-md-8">
                    <?php foreach (['error', 'msg'] as $type):
                        if (!empty($_SESSION[$type])): ?>
                            <div class="alert alert-<?php echo ($type == 'error') ? 'danger' : 'success'; ?> flash-message">
                                <strong><?= ucfirst($type); ?> :</strong> <?= htmlentities($_SESSION[$type]); ?>
                                <?php $_SESSION[$type] = ""; ?>
                            </div>
                        <?php endif; endforeach; ?>
                </div>
            </div>


            <form method="get" class="row mb-4">
                <!--  Filters -->
                <?php
                $fromInput = $_GET['from'] ?? '';
                $toInput = $_GET['to'] ?? '';

                if ($fromInput !== '') {
                    $fromDateSQL = date('Y-m-d', strtotime(str_replace('/', '-', $fromInput)));
                } else {
                    $fromDateSQL = date('Y-m-01'); // today
                }

                if ($toInput !== '') {
                    $toDateSQL = date('Y-m-d', strtotime(str_replace('/', '-', $toInput)));
                } else {
                    $toDateSQL = date('Y-m-d'); // today
                }

                $fromDateTime = $fromDateSQL . " 00:00:00";
                $toDateTime = $toDateSQL . " 23:59:59";


                ?>
                <div class="col-md-4">
                    <div class="input-group align-items-center">
                        <span class="input-group-text">From</span>
                        <input type="text" id="fromDate" name="from" class="form-control"
                            value="<?= isset($_GET['from']) ? date('d-m-Y', strtotime($_GET['from'])) : date('01-m-Y'); ?>">


                        <span class="input-group-text">To</span>

                        <input type="text" id="toDate" name="to" class="form-control"
                            value="<?= isset($_GET['to']) ? date('d-m-Y', strtotime($_GET['to'])) : date('d-m-Y'); ?>">
                    </div>
                </div>


                <div class="col-md-2">
                    <select name="date_filter_type" id="date_filter_type" class="form-control">
                        <option value="issue" <?= (isset($_GET['date_filter_type']) && $_GET['date_filter_type'] == 'issue') ? 'selected' : '' ?>>Issued Date</option>
                        <option value="return" <?= (isset($_GET['date_filter_type']) && $_GET['date_filter_type'] == 'return') ? 'selected' : '' ?>>Returned Date</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <select name="usertype" class="form-control">
                        <option value="">All Borrowers</option>
                        <option value="student" <?= (isset($_GET['usertype']) && $_GET['usertype'] == 'student') ? 'selected' : '' ?>>Students</option>
                        <option value="staff" <?= (isset($_GET['usertype']) && $_GET['usertype'] == 'staff') ? 'selected' : '' ?>>Staff</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <button class="btn btn-primary"><i class="fa fa-filter"></i> Apply</button>
                </div>
            </form>

            <button class="btn btn-info btn-sm shadow-sm rounded-pill px-3 mb-4" style="color:white;"
                data-toggle="modal" data-target="#returnModal">
                <i class="fa fa-qrcode"></i> RETURN BOOK (SCAN)<br>
            </button>
            <br>

            <div class="card square-card mb-4">
                <div class="card-header bg-secondary text-white d-flex justify-content-between align-items-center">
                    <div><i class="fa fa-book mr-2"></i> Issued Books List</div>
                    <button class="btn btn-light btn-sm text-dark shadow-sm rounded-pill px-3" data-toggle="modal"
                        data-target="#issueModal">
                        <i class="fa fa-plus-circle"></i><b> ISSUE BOOK</b>
                    </button>
                </div>
                <div class="card-body table-wrapper">
                    <table id="issuedBooksTable" class="table table-striped table-bordered">
                        <thead class="table-theme-header">
                            <tr>
                                <th>#</th>
                                <th>Type</th>

                                <th>Borrower</th>
                                <th>Dept</th>
                                <th>Degree</th>
                                <th>Shift</th>
                                <th>Year</th>
                                <th>Book</th>
                                <th>ACC No</th>
                                <th>Book No</th>
                                <th>Issued Date</th>
                                <th>Due Date</th>
                                <th>Extended Due Date</th> <!-- ✅ New -->
                                <th>Returned Date</th>
                                <th>Fine (₹)</th>
                                <th>Status</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $filterType = isset($_GET['usertype']) ? strtolower($_GET['usertype']) : '';
                            $qrcodeFilter = $_GET['qrcode'] ?? '';

                            $sql = "SELECT 
        ib.id as rid, ib.BorrowerType, ib.BorrowerID, ib.BookId, ib.CopyId,
        ib.IssuesDate, ib.DueDate, ib.ReturnDate, ib.RetrunStatus, ib.fine,
        b.BookName, bc.accession_no, bc.book_no,
        
        -- Student Details
        s.FullName as StudentName,
        d.department_name AS DeptName,
        dg.degree_name AS DegreeName,
        s.shift AS ShiftName,
        s.passed_out_year AS YearName,
        
        -- Staff Details
        st.FullName as StaffName,
        
        be.approved_due_date

FROM tblissuedbookdetails ib
JOIN tblbooks b ON b.id = ib.BookId
LEFT JOIN tblbookcopies bc ON bc.id = ib.CopyId

LEFT JOIN tblstudents s 
    ON LOWER(ib.BorrowerType)='student' 
    AND ib.BorrowerID=s.StudentId

LEFT JOIN tbldepartment d ON s.department_id = d.department_id
LEFT JOIN tbldegree dg ON s.degree_id = dg.degree_id

LEFT JOIN tblstaff st 
    ON LOWER(ib.BorrowerType)='staff' 
    AND ib.BorrowerID=st.StaffId

LEFT JOIN (
   SELECT e.issue_id, e.approved_due_date
   FROM tblbook_extensions e
   WHERE e.status='Approved'
   AND e.decision_date = (
        SELECT MAX(e2.decision_date)
        FROM tblbook_extensions e2 
        WHERE e2.issue_id=e.issue_id 
        AND e2.status='Approved'
   )
) be ON ib.id=be.issue_id

WHERE 1=1";


                            $dateFilterType = $_GET['date_filter_type'] ?? 'issue'; // default to Issue Date
                            
                            if (!empty($qrcodeFilter)) {
                                $sql .= " AND (bc.book_no = :qrcode OR bc.QRCode = :qrcode)
              AND (ib.ReturnDate IS NULL OR ib.RetrunStatus = 0)";
                            } else {
                                if ($dateFilterType === 'return') {
                                    $sql .= " AND ib.ReturnDate BETWEEN :fromDate AND :toDate";
                                } else { // issue date
                                    $sql .= " AND ib.IssuesDate BETWEEN :fromDate AND :toDate";
                                }
                            }


                            if ($filterType == 'student')
                                $sql .= " AND LOWER(ib.BorrowerType)='student'";
                            elseif ($filterType == 'staff')
                                $sql .= " AND LOWER(ib.BorrowerType)='staff'";

                            $sql .= " ORDER BY ib.id DESC";

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

                            if (!empty($qrcodeFilter)) {
                                $query->bindParam(':qrcode', $qrcodeFilter);
                            } else {
                                $query->bindParam(':fromDate', $fromDateTime);
                                $query->bindParam(':toDate', $toDateTime);
                            }

                            $query->execute();
                            $results = $query->fetchAll(PDO::FETCH_OBJ);

                            $cnt = 1;
                            $today = new DateTime();

                            foreach ($results as $row):
                                $normalDue = $row->DueDate ? new DateTime($row->DueDate) : null;
                                $extDue = $row->approved_due_date ? new DateTime($row->approved_due_date) : null;
                                $finalDue = $extDue ?? $normalDue;

                                // Fine calculation
                                $displayFine = (float) ($row->fine ?? 0);
                                if (empty($row->ReturnDate) && $finalDue && $today > $finalDue) {
                                    $displayFine = compute_fine_amount($dbh, (int) $row->rid, $finalDue->format('Y-m-d'));
                                }

                                // ✅ Determine Status
                                if (!empty($row->ReturnDate)) {
                                    $status = "<span class='badge badge-success'>Returned</span>";
                                } else {
                                    $isExt = !empty($row->approved_due_date);
                                    if ($finalDue && $today->format('Y-m-d') === $finalDue->format('Y-m-d')) {
                                        $status = $isExt
                                            ? "<span class='badge badge-info'>Extended Due Today</span>"
                                            : "<span class='badge badge-info'>Due Today</span>";
                                    } elseif ($finalDue && $today < $finalDue && $today->diff($finalDue)->days <= 2) {
                                        $status = $isExt
                                            ? "<span class='badge badge-warning'>Extended Due Soon</span>"
                                            : "<span class='badge badge-warning'>Due Soon</span>";
                                    } elseif ($finalDue && $today > $finalDue) {
                                        $status = $isExt
                                            ? "<span class='badge badge-danger'>Extended Overdue</span>"
                                            : "<span class='badge badge-danger'>Overdue</span>";
                                    } else {
                                        $status = $isExt
                                            ? "<span class='badge badge-secondary'>Extended</span>"
                                            : "<span class='badge badge-secondary'>Not Returned</span>";
                                    }
                                }
                                ?>
                                <tr>
                                    <td><?= $cnt++; ?></td>
                                    <td>
                                        <span
                                            class="badge <?= strtolower($row->BorrowerType) == 'student' ? 'badge-student' : 'badge-staff' ?> text-capitalize">
                                            <?= htmlentities($row->BorrowerType); ?>
                                        </span>
                                    </td>
                                    <td><?= htmlentities($row->BorrowerType == 'student' ? ($row->StudentName ?? $row->BorrowerID) : ($row->StaffName ?? $row->BorrowerID)); ?>
                                    </td>
                                    <td><?= $row->DeptName ?? '-' ?></td>
                                    <td><?= $row->DegreeName ?? '-' ?></td>
                                    <!-- SHIFT -->
                                    <?php
                                    $shiftValue = $row->ShiftName;

                                    // If DB stores 1/2
                                    if ($shiftValue == 1) {
                                        $shiftText = "Morning";
                                    } elseif ($shiftValue == 2) {
                                        $shiftText = "Evening";
                                    }
                                    // If DB already stores text
                                    else {
                                        $shiftText = $shiftValue ?: '-';
                                    }
                                    ?>
                                    <td><?= $shiftText ?></td>

                                    <!-- YEAR -->
                                    <?php
                                    $yearText = "-";

                                    if (!empty($row->YearName) && strpos($row->YearName, '-') !== false) {

                                        $years = explode('-', $row->YearName);
                                        $passedOutYear = intval(trim($years[1] ?? 0));
                                        $current = date('Y');

                                        $diff = $passedOutYear - $current;

                                        if ($diff == 3) {
                                            $yearText = "I";
                                        } elseif ($diff == 2) {
                                            $yearText = "II";
                                        } elseif ($diff == 1) {
                                            $yearText = "III";
                                        } else {
                                            $yearText = "Completed";
                                        }
                                    }
                                    ?>
                                    <td><?= $yearText ?></td>

                                    <td><?= htmlentities($row->BookName); ?></td>
                                    <td><?= htmlentities($row->accession_no); ?></td>
                                    <td><?= htmlentities($row->book_no ?? '-'); ?></td>
                                    <td><?= $row->IssuesDate ? date("j-n-Y | g:i A", strtotime($row->IssuesDate)) : "-"; ?>
                                    </td>
                                    <td><?= $row->DueDate ? date("j-n-Y", strtotime($row->DueDate)) : "-"; ?></td>
                                    <td><?= $row->approved_due_date ? date("j-n-Y", strtotime($row->approved_due_date)) : "-"; ?>
                                    </td>
                                    <td><?= $row->ReturnDate ? date("j-n-Y | g:i A", strtotime($row->ReturnDate)) : "-"; ?>
                                    </td>
                                    <td>
                                        <?php if (!$row->ReturnDate && $finalDue && $today > $finalDue): ?>
                                            <form method="post" class="d-flex align-items-center">
                                                <input type="hidden" name="rid" value="<?= (int) $row->rid ?>">
                                                <input type="number" name="fine"
                                                    value="<?= number_format((float) $displayFine, 2, '.', '') ?>"
                                                    class="form-control form-control-sm mr-2" style="width:100px;" required
                                                    min="0" readonly>
                                            </form>
                                        <?php else: ?>
                                            <?= number_format((float) $displayFine, 2) ?>
                                        <?php endif; ?>
                                    </td>
                                    <td><?= $status; ?></td>
                                    <td>
                                        <?php if (!$row->ReturnDate): ?>
                                            <?php if ($displayFine > 0): ?>
                                                <button class="btn btn-warning btn-sm mb-1 openFineModal"
                                                    data-rid="<?= (int) $row->rid; ?>" data-bookid="<?= (int) $row->BookId; ?>"
                                                    data-copyid="<?= (int) $row->CopyId; ?>"
                                                    data-borrower="<?= htmlspecialchars($row->BorrowerID); ?>"
                                                    data-fine="<?= (float) $displayFine; ?>">
                                                    <i class="fa fa-undo"></i> Return / Fine
                                                </button>
                                            <?php else: ?>
                                                <a href="manage-issued-books.php?returnid=<?= htmlentities($row->rid); ?>"
                                                    onclick="return confirm('Mark as returned?')"
                                                    class="btn btn-sm btn-success mb-1">
                                                    <i class="fa fa-undo"></i> Return
                                                </a>
                                            <?php endif; ?>

                                            <button class="btn btn-danger btn-sm mb-1 openDamageLostModal"
                                                data-rid="<?= (int) $row->rid; ?>" data-bookid="<?= (int) $row->BookId; ?>"
                                                data-copyid="<?= (int) $row->CopyId; ?>"
                                                data-bookname="<?= htmlspecialchars($row->BookName); ?>">
                                                <i class="fa fa-exclamation-triangle"></i>
                                            </button>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>

                    <!-- Damaged/Lost Modal -->
                    <div class="modal fade" id="damageLostModal" tabindex="-1" role="dialog"
                        aria-labelledby="damageLostModalLabel" aria-hidden="true">
                        <div class="modal-dialog modal-dialog-centered" role="document">
                            <div class="modal-content">
                                <form id="damageLostForm">
                                    <div class="modal-header bg-danger text-white">
                                        <h5 class="modal-title" id="damageLostModalLabel"><i
                                                class="fa fa-exclamation-triangle"></i> Mark Book as Damaged / Lost</h5>
                                        <button type="button" class="close text-white" data-dismiss="modal"
                                            aria-label="Close">
                                            <span aria-hidden="true">&times;</span>
                                        </button>
                                    </div>

                                    <div class="modal-body">
                                        <input type="hidden" name="issue_id" id="dl_issue_id">
                                        <input type="hidden" name="book_id" id="dl_book_id">
                                        <input type="hidden" name="copy_id" id="dl_copy_id">

                                        <div class="form-group">
                                            <label><strong>Condition Type</strong></label>
                                            <select class="form-control" name="condition_type" id="dl_condition_type"
                                                required>
                                                <option value="">Select</option>
                                                <option value="Damaged">Damaged</option>
                                                <option value="Lost">Lost</option>
                                            </select>
                                        </div>

                                        <div class="form-group">
                                            <label><strong>Reason / Remarks</strong></label>
                                            <textarea class="form-control" name="reason" id="dl_reason" rows="3"
                                                placeholder="Describe what happened..." required></textarea>
                                        </div>

                                        <div class="alert alert-warning small">
                                            Once marked as <strong>Damaged/Lost</strong>, this book will not be
                                            available for borrowing until repaired or replaced.
                                        </div>
                                    </div>

                                    <div class="modal-footer">
                                        <button type="submit" class="btn btn-danger"><i class="fa fa-save"></i>
                                            Save</button>
                                        <button type="button" class="btn btn-secondary"
                                            data-dismiss="modal">Cancel</button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>

                    <div class="modal fade" id="issueModal" tabindex="-1" role="dialog"
                        aria-labelledby="issueModalLabel" aria-hidden="true">
                        <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
                            <div class="modal-content">
                                <div class="modal-header bg-primary text-white">
                                    <h5 class="modal-title" id="issueModalLabel">Issue a New Book</h5>
                                    <button type="button" style="color:white;" class="close" data-dismiss="modal"
                                        aria-label="Close">
                                        <span aria-hidden="true">&times;</span>
                                    </button>
                                </div>

                                <?php
                                // fetch borrow rules from DB
                                $rules = [];
                                $ruleQuery = $dbh->query("SELECT borrower_type, duration_days FROM borrow_rules");
                                while ($r = $ruleQuery->fetch(PDO::FETCH_ASSOC)) {
                                    $rules[$r['borrower_type']] = $r['duration_days'];
                                }
                                ?>

                                <form id="issueForm" method="post" action="issue-book.php">
                                    <div class="modal-body">
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label>Borrower Type <span class="text-danger">*</span></label>
                                                <select name="borrowertype" id="borrowertype" class="form-control"
                                                    required>
                                                    <option value="">Select Type</option>
                                                    <option value="Student">Student</option>
                                                    <option value="Staff">Staff</option>
                                                </select>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label>Borrower ID <span class="text-danger">*</span></label>
                                                <select name="borrowerid" id="borrowerid" class="form-control"
                                                    required></select>
                                                <small id="get_borrower_name" class="form-text text-muted"></small>
                                            </div>
                                            <div class="col-md-12 mb-3" id="studentDetailsBox" style="display:none;">
                                                <div class="p-2 rounded"
                                                    style="background:#f8f9fa; border:1px solid #dcdcdc;">
                                                    <div class="row">
                                                        <div class="col-3 mb-1">Dept: <span class="fw-bold"
                                                                id="stdDept"></span></div>
                                                        <div class="col-3 mb-1">Degree: <span class="fw-bold"
                                                                id="stdDegree"></span></div>

                                                        <div class="col-3 mb-1">Shift: <span class="fw-bold"
                                                                id="stdShift"></span></div>
                                                        <!-- <div class="col-3 mb-1"><strong>Mobile:</strong> <span
                                                                id="stdMobile"></span></div> -->

                                                        <div class="col-3 mb-1">Year: <span class="fw-bold"
                                                                id="stdYear"></span></div>
                                                    </div>
                                                </div>

                                            </div>
                                            <!-- QR Code Scanner -->
                                            <div class="col-md-12 mb-3">
                                                <label>Scan Book QR Code</label>
                                                <div id="qr-reader" style="width: 100%;"></div>
                                                <small class="form-text text-muted">Scan QR code OR search manually
                                                    below.</small>
                                            </div>

                                            <!-- Manual Book Selection -->
                                            <div class="col-md-12 mb-3">
                                                <label>Search Book (Book No / Accession No / Title / Authors) <span
                                                        class="text-danger">*</span></label>
                                                <select name="bookdetails" id="bookid" class="form-control"
                                                    required></select>
                                            </div>

                                            <!-- Auto Duration from DB -->
                                            <div class="col-md-6 mb-3">
                                                <label>Duration (Days) <span class="text-danger">*</span></label>
                                                <input type="number" id="days" name="days" class="form-control"
                                                    required>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="modal-footer justify-content-center py-2">
                                        <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">
                                            <i class="fa fa-times"></i> Cancel
                                        </button>
                                        <button type="submit" name="issue" class="btn btn-success btn-sm">
                                            <i class="fas fa-book-medical"></i> Issue Book
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>

                    <!-- Fine Payment Modal (keeps same markup you provided) -->
                    <!-- Fine Payment Modal -->
                    <div class="modal fade" id="finePaymentModal" tabindex="-1" role="dialog"
                        aria-labelledby="finePaymentModalLabel" aria-hidden="true">
                        <div class="modal-dialog modal-dialog-centered" role="document">
                            <div class="modal-content">
                                <form id="fineForm">
                                    <div class="modal-header bg-primary text-white">
                                        <h5 class="modal-title" id="finePaymentModalLabel">Return Book & Fine</h5>
                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"
                                            style="color:white;">
                                            <span aria-hidden="true">&times;</span>
                                        </button>
                                    </div>
                                    <div class="modal-body">
                                        <input type="hidden" name="issue_id" id="fm_issue_id">
                                        <input type="hidden" name="book_id" id="fm_book_id">
                                        <input type="hidden" name="copy_id" id="fm_copy_id">
                                        <input type="hidden" name="borrower_id" id="fm_borrower_id">

                                        <div class="form-group">
                                            <label><strong>Fine Amount (₹)</strong></label>
                                            <input type="number" class="form-control" name="fine_amount"
                                                id="fm_fine_amount" min="0" step="0.01" required readonly>
                                        </div>

                                        <div class="form-group">
                                            <label><strong>Payment Status</strong></label>
                                            <div class="d-flex align-items-center">
                                                <div class="form-check mr-3">
                                                    <input class="form-check-input" type="radio" name="payment_status"
                                                        id="psPaid" value="Paid" required>
                                                    <label class="form-check-label" for="psPaid">Paid</label>
                                                </div>
                                                <div class="form-check">
                                                    <input class="form-check-input" type="radio" name="payment_status"
                                                        id="psUnpaid" value="Unpaid" required>
                                                    <label class="form-check-label" for="psUnpaid">Unpaid</label>
                                                </div>
                                            </div>
                                        </div>

                                        <div id="paidFields" style="display:none;">
                                            <div class="form-group">
                                                <label>Mode of Payment</label>
                                                <select name="payment_mode" id="fm_payment_mode" class="form-control">
                                                    <option value="">Select Payment Mode</option>
                                                    <option value="Cash">Cash</option>
                                                    <option value="Card">Card</option>
                                                    <option value="UPI">UPI</option>
                                                </select>
                                            </div>
                                            <div class="form-group">
                                                <label>Actual Amount Paid (₹)</label>
                                                <input type="number" name="actual_amount" id="fm_actual_amount"
                                                    class="form-control" step="0.01"
                                                    placeholder="(Optional, defaults to fine)">
                                            </div>
                                        </div>

                                        <div id="unpaidFields" style="display:none;">
                                            <div class="form-group">
                                                <label>Remarks (optional)</label>
                                                <textarea name="remarks" id="fm_remarks" class="form-control" rows="2"
                                                    placeholder="Reason / note"></textarea>
                                            </div>
                                        </div>

                                        <div id="fineHelp" class="small text-muted"></div>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="submit" class="btn btn-success">Save & Continue</button>
                                        <button type="button" class="btn btn-secondary"
                                            data-dismiss="modal">Cancel</button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>

                    <!-- Return Book Modal -->
                    <div class="modal fade" id="returnModal" tabindex="-1" role="dialog"
                        aria-labelledby="returnModalLabel" aria-hidden="true">
                        <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
                            <div class="modal-content">
                                <div class="modal-header bg-primary text-white">
                                    <h5 class="modal-title" id="returnModalLabel">Return Book by QR Scan</h5>
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"
                                        style="color:white;">
                                        <span aria-hidden="true">&times;</span>
                                    </button>
                                </div>
                                <div class="modal-body text-center">
                                    <div id="return-qr-reader" style="width: 100%;"></div>
                                    <div id="return-result" class="mt-3"></div>
                                </div>
                                <div class="modal-footer justify-content-center py-2">
                                    <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">
                                        <i class="fa fa-times"></i> Close
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
        </div>
        <?php include('includes/footer.php'); ?>
    </div>

    <script src="https://unpkg.com/html5-qrcode" type="text/javascript"></script>
    <script src="https://unpkg.com/html5-qrcode@2.3.8/minified/html5-qrcode.min.js"></script>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap4.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

    <script>

        // Borrow rules from DB (PHP → JS)
        const borrowRules = <?php echo json_encode($rules); ?>;

        document.addEventListener("DOMContentLoaded", function () {

            const borrowerType = document.getElementById("borrowertype");
            const daysInput = document.getElementById("days");

            borrowerType.addEventListener("change", function () {
                let days = borrowRules[this.value] || "";
                daysInput.value = days;
            });
        });



        $('#issuedBooksTable').DataTable({
            pageLength: 10,
            lengthChange: true,
            ordering: true,
            responsive: true,
            language: { search: "🔍 Search issued books:" }
        });



        // Borrower select2 and book select2 omitted here (same as your original). Keep your existing JS for those.

        // ---------- Fine Modal Open ----------
        $(document).on('click', '.openFineModal', function () {
            const rid = $(this).data('rid');
            const bookId = $(this).data('bookid');
            const copyId = $(this).data('copyid');
            const borrower = $(this).data('borrower');
            const fine = parseFloat($(this).data('fine')) || 0;

            $('#fm_issue_id').val(rid);
            $('#fm_book_id').val(bookId);
            $('#fm_copy_id').val(copyId);
            $('#fm_borrower_id').val(borrower);
            $('#fm_fine_amount').val(fine.toFixed(2));

            // reset status/fields
            $('input[name="payment_status"]').prop('checked', false);
            $('#paidFields').hide();
            $('#unpaidFields').hide();
            $('#fm_payment_mode').val('Cash');
            $('#fm_actual_amount').val('');
            $('#fm_remarks').val('');
            $('#fineHelp').text('If status is Paid, the book will be returned now. If Unpaid, book will NOT be returned.');

            $('#finePaymentModal').modal('show');
        });

        // Toggle Paid/Unpaid sections
        $('input[name="payment_status"]').on('change', function () {
            if ($(this).val() === 'Paid') {
                $('#paidFields').show();
                $('#unpaidFields').hide();
            } else {
                $('#paidFields').hide();
                $('#unpaidFields').show();
            }
        });

        // Submit Fine (Paid / Unpaid) via AJAX
        $('#fineForm').on('submit', function (e) {
            e.preventDefault();

            const formData = {
                ajax: '1',
                action: 'process_fine',
                issue_id: $('#fm_issue_id').val(),
                // client fine is only for display; server recalculates for integrity
                fine_amount: $('#fm_fine_amount').val(),
                payment_status: $('input[name="payment_status"]:checked').val() || '',
                payment_mode: $('#fm_payment_mode').val(),
                actual_amount: $('#fm_actual_amount').val(),
                remarks: $('#fm_remarks').val()
            };

            if (!formData.payment_status) {
                alert('Select payment status');
                return;
            }

            $.post('manage-issued-books.php', formData, function (resp) {
                if (resp.status === 'success') {
                    $('#finePaymentModal').modal('hide');
                    alert(resp.message);
                    location.reload(); // refresh table
                } else {
                    alert(resp.message || 'Failed.');
                }
            }, 'json').fail(() => alert('Network error'));
        });
        $('#damageLostForm').on('submit', function (e) {
            e.preventDefault();

            $.ajax({
                url: 'manage-issued-books.php',
                type: 'POST',
                data: $(this).serialize() + '&ajax=1&action=mark_damage_lost',
                dataType: 'json',
                success: function (res) {
                    if (res.status === 'success') {
                        alert(res.message);
                        location.reload();
                    } else {
                        alert('Error: ' + res.message);
                    }
                },
                error: function () {
                    alert('Server error while marking as damaged/lost.');
                }
            });
        });


        // QR scanner JS for issue/return (kept same as your original). See your earlier code and keep it.
        // (Omitted here to keep response focused — keep the JS you already had for html5-qrcode usage.)


        // =======================
        // BORROWER SELECT2 DROPDOWN
        // =======================
        $('#borrowertype').on('change', function () {
            let type = $(this).val();
            $("#studentDetailsBox").hide();
            $('#borrowerid').val(null).trigger('change');

            if ($('#borrowerid').hasClass("select2-hidden-accessible")) {
                $('#borrowerid').select2('destroy');
            }

            if (type) {
                $('#borrowerid').select2({
                    placeholder: 'Search ' + type + ' ID / Name',
                    width: '100%',
                    dropdownParent: $('#issueModal'),
                    ajax: {
                        url: 'get_borrower_list.php',
                        dataType: 'json',
                        delay: 250,
                        data: params => ({ q: params.term, type: type }),
                        processResults: data => ({
                            results: data.map(item => ({
                                id: item.BorrowerID,
                                primary_id: item.PrimaryID,
                                text: item.BorrowerID + ' - ' + item.FullName
                            }))
                        }),
                        cache: true
                    }
                });
            }
        });
        $('#borrowerid').on('select2:select', function (e) {
            let studID = e.params.data.primary_id;
            let borrowerType = $('#borrowertype').val();   // always get current type

            $.ajax({
                url: "get_student_full_details.php",
                type: "GET",
                data: { id: studID },
                success: function (res) {
                    let d = JSON.parse(res);

                    $("#stdDept").text(d.department);
                    $("#stdShift").text(d.shift);

                    $("#stdMobile").text(d.mobile);
                    $("#stdYear").text(d.year);
                    $("#stdDegree").text(d.degree);
                    // show only for Students
                    if (borrowerType === 'Student') {
                        $("#studentDetailsBox").show();
                    } else {
                        $("#studentDetailsBox").hide();
                    }

                }
            });
        });
        // =======================
        // BOOK SELECT2 DROPDOWN
        // =======================
        $('#bookid').select2({
            placeholder: 'Select Book (Book No / Accession No / Title / Authors)',
            width: '100%',
            dropdownParent: $('#issueModal'),
            ajax: {
                url: 'get_book_list.php',
                dataType: 'json',
                delay: 250,
                data: params => ({ q: params.term }),
                processResults: data => {
                    if (data.error) {
                        console.error('Server Error:', data.error);
                        return { results: [] };
                    }
                    return { results: data };
                },
                error: function (xhr) {
                    console.error('AJAX Error:', xhr.responseText);
                },
                cache: true
            }
        });
        // =======================
        // ISSUE BOOK QR SCANNER
        // =======================
        let html5QrcodeScannerIssue;

        function onIssueScanSuccess(decodedText) {
            console.log(`Scanned Issue QR: ${decodedText}`);

            // Stop scanner immediately after a successful scan
            if (html5QrcodeScannerIssue) {
                html5QrcodeScannerIssue.clear().then(() => {
                    console.log("Issue scanner stopped after success");
                    html5QrcodeScannerIssue = null;
                    $("#qr-reader").html(""); // clear scanner UI
                }).catch(err => console.warn("Error stopping scanner:", err));
            }

            // Fetch book info via AJAX
            $.ajax({
                url: 'get_book_by_qr.php',
                method: 'POST',
                data: { qrcode: decodedText },
                dataType: 'json',
                success: function (data) {
                    if (data.status === 'success') {
                        let newOption = new Option(
                            `${data.book_no} | ${data.accession_no} | ${data.BookName} | Author: ${data.AuthorName}`,
                            data.CopyId,
                            true,
                            true
                        );
                        $('#bookid').append(newOption).trigger('change');
                    } else {
                        alert("Book not found or not available!\n\nDebug QR: " + data.debug_qr);
                    }
                }
            });
        }

        function onIssueScanFailure(error) {
            console.warn(`Issue QR scan error: ${error}`);
        }

        // ✅ Start issue scanner only when issue modal opens
        $("#issueModal").on("shown.bs.modal", function () {
            if (!html5QrcodeScannerIssue) {
                html5QrcodeScannerIssue = new Html5QrcodeScanner(
                    "qr-reader",
                    { fps: 10, qrbox: 250 }
                );
                html5QrcodeScannerIssue.render(onIssueScanSuccess, onIssueScanFailure);
            }
        });

        // ✅ Stop issue scanner when modal closes
        $("#issueModal").on("hidden.bs.modal", function () {
            if (html5QrcodeScannerIssue) {
                html5QrcodeScannerIssue.clear().catch(err => console.warn("Scanner clear error:", err));
                html5QrcodeScannerIssue = null;
            }
            $("#qr-reader").html("");
        });

        // =======================
        // RETURN BOOK QR SCANNER
        // =======================
        let html5QrcodeScannerReturn;
        let returnScanCompleted = false;

        // function onReturnScanSuccess(decodedText) {
        //     if (returnScanCompleted) return;
        //     returnScanCompleted = true;

        //     console.log("Scanned QR:", decodedText);

        //     let bookCode = decodedText;

        //     // ✅ Extract bookcopy param if QR contains ?bookcopy=
        //     if (decodedText.includes("bookcopy=")) {
        //         try {
        //             const url = new URL(decodedText);
        //             bookCode = url.searchParams.get("bookcopy") || decodedText;
        //         } catch (e) {
        //             const match = decodedText.match(/bookcopy=([^&]+)/);
        //             if (match) bookCode = match[1];
        //         }
        //     }

        //     console.log("Extracted Book Code:", bookCode);

        //     // ✅ Use DataTables search API to filter rows dynamically
        //     let table = $('#issuedBooksTable').DataTable();
        //     table.search(bookCode).draw();

        //     // ✅ Show success message
        //     let visibleRows = table.rows({ filter: 'applied' }).data().length;
        //     if (visibleRows > 0) {
        //         $("#return-result").html(`
        //             <div class="alert alert-success">
        //                 ✅ Showing issued books for <b>${bookCode}</b>
        //             </div>
        //         `);
        //     } else {
        //         $("#return-result").html(`
        //             <div class="alert alert-warning">
        //                 ⚠️ No issued books found for <b>${bookCode}</b>
        //             </div>
        //         `);
        //     }

        //     // ✅ Allow scanning again
        //     returnScanCompleted = false;
        // }

        function onReturnScanSuccess(decodedText) {
            if (returnScanCompleted) return;
            returnScanCompleted = true;

            let bookCode = decodedText;

            // ✅ Extract bookcopy param if QR contains ?bookcopy=
            if (decodedText.includes("bookcopy=")) {
                try {
                    const url = new URL(decodedText);
                    bookCode = url.searchParams.get("bookcopy") || decodedText;
                } catch (e) {
                    const match = decodedText.match(/bookcopy=([^&]+)/);
                    if (match) bookCode = match[1];
                }
            }

            console.log("Extracted Book Code:", bookCode);

            // ✅ Reload Manage Issued Books page ignoring date filters
            window.location.href = `manage-issued-books.php?qrcode=${bookCode}`;
        }

        function onReturnScanFailure(error) {
            console.warn(`Return QR scan error: ${error}`);
        }

        // ✅ Start return scanner only when modal opens
        $("#returnModal").on("shown.bs.modal", function () {
            returnScanCompleted = false;
            if (!html5QrcodeScannerReturn) {
                html5QrcodeScannerReturn = new Html5QrcodeScanner(
                    "return-qr-reader",
                    { fps: 10, qrbox: 250 }
                );
                html5QrcodeScannerReturn.render(onReturnScanSuccess, onReturnScanFailure);
            }
        });

        // ✅ Stop return scanner when modal closes
        $("#returnModal").on("hidden.bs.modal", function () {
            if (html5QrcodeScannerReturn) {
                html5QrcodeScannerReturn.clear().catch(err => console.warn("Scanner clear error:", err));
                html5QrcodeScannerReturn = null;
            }
            $("#return-qr-reader").html("");
            $("#return-result").html("");
        });
        // ---------- Damaged/Lost Modal ----------
        $(document).on('click', '.openDamageLostModal', function () {
            const rid = $(this).data('rid');
            const bookId = $(this).data('bookid');
            const copyId = $(this).data('copyid');
            const bookName = $(this).data('bookname');

            $('#dl_issue_id').val(rid);
            $('#dl_book_id').val(bookId);
            $('#dl_copy_id').val(copyId);
            $('#dl_condition_type').val('');
            $('#dl_reason').val('');
            $('#damageLostModalLabel').text(`Mark as Damaged/Lost - ${bookName}`);
            $('#damageLostModal').modal('show');
        });

        let monthdate = new Date();
        monthdate.setDate(1); // first day of current month

        flatpickr("#fromDate", {
            dateFormat: "d-m-Y",
            defaultDate: document.getElementById('fromDate').value.trim() || monthdate
        });

        flatpickr("#toDate", {
            dateFormat: "d-m-Y",
            defaultDate: document.getElementById('toDate').value.trim() || new Date()
        });



    </script>

</body>

</html>