<?php
session_start();
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
include "../include/config.php";
$userlogin = $_SESSION['email'];
$intake = $_SESSION['department'];

if (isset($_SESSION['email'])) {

// ✅ Issue a book
if (isset($_POST['issue_book'])) {
    $book_id = intval($_POST['book_id']);
    $studentid = mysqli_real_escape_string($conn, $_POST['studentid']);
    $issue_date = mysqli_real_escape_string($conn, $_POST['issue_date']);
    $due_date = mysqli_real_escape_string($conn, $_POST['due_date']);
    
    // Check if book is available
    $book_check = mysqli_fetch_assoc(mysqli_query($conn, "SELECT copies FROM catalogue WHERE id = $book_id"));
    if ($book_check['copies'] > 0) {
        $sql = "INSERT INTO book_issues (book_id, studentid, issue_date, due_date, status) 
                VALUES ($book_id, '$studentid', '$issue_date', '$due_date', 'issued')";
        
        if (mysqli_query($conn, $sql)) {
            // Decrease available copies
            mysqli_query($conn, "UPDATE catalogue SET copies = copies - 1 WHERE id = $book_id");
            $successMsg = "Book issued successfully!";
        } else {
            $errorMsg = "Error: " . mysqli_error($conn);
        }
    } else {
        $errorMsg = "Error: This book is not available for issuing.";
    }
}

// ✅ Return a book
if (isset($_GET['return'])) {
    $issue_id = intval($_GET['return']);
    
    // Get issue details
    $issue = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM book_issues WHERE id = $issue_id"));
    $book_id = $issue['book_id'];
    $return_date = date('Y-m-d');
    
    // Calculate fine if overdue (assuming $1 per day overdue)
    $fine = 0;
    if (strtotime($return_date) > strtotime($issue['due_date'])) {
        $days_overdue = floor((strtotime($return_date) - strtotime($issue['due_date'])) / (60 * 60 * 24));
        $fine = $days_overdue * 1; // $1 per day
    }
    
    $sql = "UPDATE book_issues SET return_date = '$return_date', status = 'returned', fine_amount = $fine WHERE id = $issue_id";
    
    if (mysqli_query($conn, $sql)) {
        // Increase available copies
        mysqli_query($conn, "UPDATE catalogue SET copies = copies + 1 WHERE id = $book_id");
        $successMsg = "Book returned successfully!" . ($fine > 0 ? " Fine amount: $$fine" : "");
    } else {
        $errorMsg = "Error: " . mysqli_error($conn);
    }
}

// ✅ Mark as overdue (cron job would typically handle this)
if (isset($_GET['mark_overdue'])) {
    $issue_id = intval($_GET['mark_overdue']);
    mysqli_query($conn, "UPDATE book_issues SET status = 'overdue' WHERE id = $issue_id AND return_date IS NULL AND due_date < CURDATE()");
    $successMsg = "Status updated to overdue!";
}

// ✅ Fetch all book issues
$book_issues = mysqli_query($conn, "
    SELECT bi.*, c.title, c.author 
    FROM book_issues bi 
    JOIN catalogue c ON bi.book_id = c.id 
    ORDER BY bi.id DESC
");

// ✅ Fetch available books for issuing
$available_books = mysqli_query($conn, "SELECT * FROM catalogue WHERE copies > 0 ORDER BY title");

?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Book Issuing & Returns - UniCoHS</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
body { font-family: 'Roboto', sans-serif; background: #f5f7fa; }
.card { border-radius: 20px; box-shadow: 0 8px 25px rgba(0,0,0,0.1); padding: 30px; margin-top: 30px; margin-bottom: 30px; }
h2 { color: var(--primary); margin-bottom: 20px; font-weight: 700; }
.btn { border-radius: 8px; padding: 8px 16px; font-weight: 500; }
.status-issued { color: #ffc107; font-weight: bold; }
.status-returned { color: #198754; font-weight: bold; }
.status-overdue { color: #dc3545; font-weight: bold; }
.fine-amount { color: #dc3545; font-weight: bold; }
</style>
</head>
<body>
    <?php include "../include/nav.php"; ?>
    <div class="content">

        <div class="container">
               <div class="action-buttons">
                <a href="owing.php" class="btn btn-danger">
                    <i class="fas fa-exclamation-triangle me-2"></i>View Students Owing Books
                </a>
               
            </div>
            <h2 class="text-center mt-4">Book Issuing & Returns Management</h2>

            <?php if(isset($successMsg)) echo "<div class='alert alert-success'>$successMsg</div>"; ?>
            <?php if(isset($errorMsg)) echo "<div class='alert alert-danger'>$errorMsg</div>"; ?>

            <!-- Issue Book Form -->
            <div class="card">
                <h4><i class="fas fa-book-reader me-2"></i>Issue a Book</h4>
                <form method="post">
                    <div class="row">
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label class="form-label">Select Book</label>
                                <select name="book_id" class="form-select" required>
                                    <option value="">-- Select Book --</option>
                                    <?php while($book = mysqli_fetch_assoc($available_books)) { ?>
                                    <option value="<?php echo $book['id']; ?>">
                                        <?php echo $book['title']; ?> by <?php echo $book['author']; ?> (<?php echo $book['copies']; ?> available)
                                    </option>
                                    <?php } ?>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="mb-3">
                                <label class="form-label">StudentID</label>
                                <input type="text" name="studentid" class="form-control" required>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="mb-3">
                                <label class="form-label">Issue Date</label>
                                <input type="date" name="issue_date" class="form-control" value="<?php echo date('Y-m-d'); ?>" required>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="mb-3">
                                <label class="form-label">Due Date</label>
                                <input type="date" name="due_date" class="form-control" value="<?php echo date('Y-m-d', strtotime('+14 days')); ?>" required>
                            </div>
                        </div>
                        <div class="col-md-1">
                            <div class="mb-3">
                                <label class="form-label">&nbsp;</label>
                                <button type="submit" name="issue_book" class="btn btn-success w-100">
                                    <i class="fas fa-plus me-1"></i>Issue
                                </button>
                            </div>
                        </div>
                    </div>
                </form>
            </div>

            <!-- Book Issues Table -->
            <div class="card">
                <h4><i class="fas fa-list me-2"></i>Book Issue Records</h4>
                <div class="table-responsive">
                    <table class="table table-bordered table-hover">
                        <thead class="table-dark">
                            <tr>
                                <th>Book Title</th>
                                <th>StudentID</th>
                                <th>Issue Date</th>
                                <th>Due Date</th>
                                <th>Return Date</th>
                                <th>Status</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while($issue = mysqli_fetch_assoc($book_issues)) { 
                                $status_class = "status-" . $issue['status'];
                                $is_overdue = ($issue['status'] == 'issued' && strtotime($issue['due_date']) < strtotime(date('Y-m-d')));
                            ?>
                            <tr>
                                <td><?php echo $issue['title']; ?></td>
                                <td><?php echo $issue['studentid']; ?></td>
                                <td><?php echo date('M j, Y', strtotime($issue['issue_date'])); ?></td>
                                <td><?php echo date('M j, Y', strtotime($issue['due_date'])); ?></td>
                                <td><?php echo $issue['return_date'] ? date('M j, Y', strtotime($issue['return_date'])) : 'Not returned'; ?></td>
                                <td class="<?php echo $status_class; ?>">
                                    <?php 
                                    echo ucfirst($issue['status']);
                                    if ($is_overdue) echo " (Overdue)";
                                    ?>
                                </td>
                              
                                <td>
                                    <?php if($issue['status'] == 'issued') { ?>
                                        <a href="?return=<?php echo $issue['id']; ?>" class="btn btn-sm btn-success" onclick="return confirm('Mark this book as returned?');">
                                            <i class="fas fa-undo me-1"></i>Return
                                        </a>
                                        <?php if($is_overdue) { ?>
                                            <a href="?mark_overdue=<?php echo $issue['id']; ?>" class="btn btn-sm btn-warning mt-1">
                                                <i class="fas fa-exclamation-triangle me-1"></i>Mark Overdue
                                            </a>
                                        <?php } ?>
                                    <?php } else { ?>
                                        <span class="text-muted">Completed</span>
                                    <?php } ?>
                                </td>
                            </tr>
                            <?php } ?>
                        </tbody>
                    </table>
                </div>
            </div>

   
    <script>
    // Auto-update overdue status
    document.addEventListener('DOMContentLoaded', function() {
        // Check for overdue books every minute
        setInterval(function() {
            // This would typically be done via a cron job, but we'll just reload after 5 minutes
            console.log('Checking for overdue books...');
        }, 300000);
    });
    </script>
</body>
</html>
<?php
} else {
    header("location:../index.php");
}
?>