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

if(strlen($_SESSION['alogin']) == 0){
  header('location:index.php');
  exit;
}

$rid = intval($_GET['rid'] ?? 0);

// Manual fine update
if(isset($_POST['update_fine'])){
    $rid = $_POST['rid'];
    $fine = $_POST['fine'];

    $sql = "UPDATE tblissuedbookdetails SET fine = :fine WHERE id = :rid";
    $query = $dbh->prepare($sql);
    $query->bindParam(':fine', $fine, PDO::PARAM_STR);
    $query->bindParam(':rid', $rid, PDO::PARAM_INT);
    $query->execute();

    $_SESSION['msg'] = "Fine updated successfully.";
    header("Location: manage-issued-books.php");
    exit;
}

// Return book logic
if(isset($_GET['returnid'])){
    $issue_id = intval($_GET['returnid']);

    $sql = "SELECT BookId, CopyId, ReturnDate, fine 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 && $issue->ReturnDate == ""){
    if($issue->fine > 0){
        $_SESSION['error'] = "Please collect the fine amount ₹".$issue->fine." before returning the book.";
        header("Location: manage-issued-books.php");
        exit;
    }

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

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

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

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

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

    header('location:manage-issued-books.php');
    exit;
}

// Fetch issued book details with Copy Number
$sql = "SELECT ib.id as rid, ib.BorrowerType, ib.BorrowerID, ib.BookId, ib.CopyId, ib.IssuesDate, ib.DueDate, ib.ReturnDate, ib.fine,
               b.BookName, b.ISBNNumber,
               bc.book_no,
               s.FullName as StudentName,
               st.FullName as StaffName
        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 tblstaff st ON LOWER(ib.BorrowerType)='staff' AND ib.BorrowerID=st.StaffId
        WHERE ib.id = :rid";

$query = $dbh->prepare($sql);
$query->bindParam(':rid', $rid, PDO::PARAM_INT);
$query->execute();
$book = $query->fetch(PDO::FETCH_OBJ);
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Issued Book Details | 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">
<style>
  .square-card { background-color: #f8f9fa; border: 1px solid #dee2e6; border-radius: 6px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); }
  .header-line { font-size: 22px; font-weight: 600; color: #2258d5; }
  .flash-message { max-width: 600px; margin: 0 auto 15px; }
</style>
</head>

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

  <div class="main-content flex-grow-1 px-4 py-3">
    <div class="row mb-4">
      <div class="col-md-12 d-flex justify-content-between align-items-center">
        <h5 class="header-line"><i class="fas fa-book-open mr-2"></i>Issued Book Details</h5>
        <a href="manage-issued-books.php" class="btn btn-danger">
          <i class="fas fa-arrow-left"></i> Back to List
        </a>
      </div>
    </div>

    <div class="row justify-content-center">
      <div class="col-md-8">
        <?php if($book): ?>
        <div class="card square-card mb-4">
          <div class="card-header bg-secondary text-white">
            <i class="fas fa-info-circle mr-2"></i>Book Issue Info
          </div>
          <div class="card-body">
            <form method="post" class="mb-0">
              <div class="form-group">
                <label class="font-weight-bold">Borrower Name</label>
                <div><?= htmlentities($book->BorrowerType=='student'? $book->StudentName : $book->StaffName); ?></div>
              </div>

              <div class="form-group">
                <label class="font-weight-bold">Borrower Type</label>
                <div><?= ucfirst($book->BorrowerType); ?></div>
              </div>

              <div class="form-group">
                <label class="font-weight-bold">Book Name</label>
                <div><?= htmlentities($book->BookName); ?></div>
              </div>

              <div class="form-group">
                <label class="font-weight-bold">ISBN Number</label>
                <div><?= htmlentities($book->ISBNNumber); ?></div>
              </div>

              <div class="form-group">
                <label class="font-weight-bold">Copy Number</label>
                <div><?= htmlentities($book->book_no ?? '-'); ?></div>
              </div>

              <div class="form-group">
                <label class="font-weight-bold">Issued Date</label>
                <div><?= htmlentities($book->IssuesDate); ?></div>
              </div>

              <div class="form-group">
                <label class="font-weight-bold">Returned Date</label>
                <div><?= $book->ReturnDate ? htmlentities($book->ReturnDate) : "Not Returned Yet"; ?></div>
              </div>

              <div class="form-group">
                <label class="font-weight-bold">Fine (₹)</label>
                <?php if(!$book->fine): ?>
                  <input type="number" name="fine" class="form-control" required min="0">
                <?php else: ?>
                  <div><?= htmlentities($book->fine); ?></div>
                <?php endif; ?>
              </div>

              <?php if($book->ReturnDate==""): ?>
              <div class="d-flex justify-content-end">
                <input type="hidden" name="rid" value="<?= (int)$book->rid ?>">
                <button type="submit" name="update_fine" class="btn btn-success">
                  <i class="fas fa-undo-alt"></i> Return Book / Update Fine
                </button>
              </div>
              <?php endif; ?>
            </form>
          </div>
        </div>
        <?php else: ?>
          <div class="alert alert-danger">Invalid Book Record</div>
        <?php endif; ?>
      </div>
    </div>
  </div>

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

<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>
</body>
</html>
