<?php
session_start();
header('Content-Type: application/json; charset=utf-8');
include('includes/config.php');

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

    $qrcode = isset($_POST['qrcode']) ? trim($_POST['qrcode']) : '';
    if (empty($qrcode)) {
        echo json_encode(['status' => 'error', 'message' => 'QR code is missing']);
        exit;
    }

    $qrcode = basename($qrcode);

    $sql = "SELECT 
                bc.id AS CopyID,
                bc.book_no AS CopyNo,
                bc.QRCode,
                bc.book_status,
                b.id AS BookID,
                b.BookName,
                b.ISBNNumber,
                ib.id AS IssueID,
                ib.BorrowerType,
                ib.BorrowerID,
                ib.IssuesDate,
                ib.DueDate,
                ib.ReturnDate,
                COALESCE(ib.fine, 0) AS Fine,
                s.FullName AS StudentName,
                st.FullName AS StaffName
            FROM tblbookcopies bc
            JOIN tblbooks b ON b.id = bc.book_id
            LEFT JOIN tblissuedbookdetails ib 
              ON ib.CopyId = bc.id AND COALESCE(ib.RetrunStatus,0)=0 AND ib.ReturnDate IS NULL
            LEFT JOIN tblstudents s 
              ON LOWER(ib.BorrowerType) = 'student' AND ib.BorrowerID = s.StudentId
            LEFT JOIN tblstaff st 
              ON LOWER(ib.BorrowerType) = 'staff' AND ib.BorrowerID = st.StaffId
            WHERE bc.QRCode LIKE :qr
            LIMIT 1";

    $stmt = $dbh->prepare($sql);
    $stmt->bindValue(':qr', "%$qrcode%", PDO::PARAM_STR);
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$row) {
        echo json_encode(['status' => 'not_found', 'message' => 'Book not found for this QR']);
        exit;
    }

    // If currently issued
    if (!empty($row['IssueID']) && empty($row['ReturnDate'])) {
        $borrowerName = ($row['BorrowerType'] === 'student') ? $row['StudentName'] : $row['StaffName'];
        echo json_encode([
            'status' => 'issued',
            'borrower' => [
                'Name' => $borrowerName,
                'Type' => ucfirst($row['BorrowerType']),
                'ID'   => $row['BorrowerID']
            ],
            'book' => [
                'BookID'   => $row['BookID'],
                'BookName' => $row['BookName'],
                'CopyId'   => $row['CopyID'],
                'CopyNo'   => $row['CopyNo'],
                'ISBNNumber'=> $row['ISBNNumber']
            ]
        ]);
        exit;
    }

    // Available => allow preselecting this copy to issue
    echo json_encode([
        'status' => 'available',
        'book' => [
            'BookID'    => $row['BookID'],
            'BookName'  => $row['BookName'],
            'CopyId'    => $row['CopyID'],
            'CopyNo'    => $row['CopyNo'],
            'ISBNNumber'=> $row['ISBNNumber']
        ]
    ]);

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