<?php
session_start();
require_once '../config/database.php';

// Only admin and teacher can process returns
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['user_role'], ['admin','teacher'])) {
    header('Location: ../login.php');
    exit();
}

$success_message = '';
$error_message = '';

// Ensure required tables exist (align with manage.php usage)
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS library_books (
        id INT AUTO_INCREMENT PRIMARY KEY,
        title VARCHAR(255) NOT NULL,
        author VARCHAR(255) NULL,
        isbn VARCHAR(50) NULL,
        category VARCHAR(100) NULL,
        publisher VARCHAR(255) NULL,
        publication_year INT NULL,
        total_copies INT NOT NULL DEFAULT 0,
        available_copies INT NOT NULL DEFAULT 0,
        location VARCHAR(100) NULL,
        status ENUM('active','inactive') DEFAULT 'active',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    $pdo->exec("CREATE TABLE IF NOT EXISTS library_issues (
        id INT AUTO_INCREMENT PRIMARY KEY,
        book_id INT NOT NULL,
        student_id INT NOT NULL,
        issue_date DATE NOT NULL,
        due_date DATE NULL,
        return_date DATE NULL,
        status ENUM('issued','returned','overdue') DEFAULT 'issued',
        issued_by INT NOT NULL,
        returned_by INT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX (book_id), INDEX (student_id), INDEX (status),
        CONSTRAINT fk_issue_book FOREIGN KEY (book_id) REFERENCES library_books(id) ON DELETE CASCADE
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
} catch (Exception $e) {
    // ignore
}

// Mark return
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['return_issue'])) {
    $issue_id = (int)($_POST['issue_id'] ?? 0);
    if ($issue_id <= 0) {
        $error_message = 'সঠিক ইস্যু নির্বাচন করুন';
    } else {
        try {
            $pdo->beginTransaction();
            // Load issue
            $stmt = $pdo->prepare("SELECT id, book_id, status FROM library_issues WHERE id = ? FOR UPDATE");
            $stmt->execute([$issue_id]);
            $issue = $stmt->fetch(PDO::FETCH_ASSOC);
            if (!$issue) { throw new Exception('ইস্যু খুঁজে পাওয়া যায়নি'); }
            if ($issue['status'] !== 'issued') { throw new Exception('এই রেকর্ডটি ইতিমধ্যে রিটার্ন করা হয়েছে'); }
            // Update issue
            $stmt = $pdo->prepare("UPDATE library_issues SET status='returned', return_date = CURDATE(), returned_by = ? WHERE id = ?");
            $stmt->execute([$_SESSION['user_id'], $issue_id]);
            // Update copies
            $stmt = $pdo->prepare("UPDATE library_books SET available_copies = available_copies + 1 WHERE id = ?");
            $stmt->execute([(int)$issue['book_id']]);
            $pdo->commit();
            $success_message = 'বই সফলভাবে রিটার্ন হয়েছে';
        } catch (Exception $e) {
            $pdo->rollBack();
            $error_message = $e->getMessage();
        }
    }
}

// Load currently issued books
$issued = [];
try {
    $stmt = $pdo->query("SELECT 
        li.id as issue_id,
        lb.title, lb.author,
        s.first_name, s.last_name, s.student_id, s.roll_number,
        c.name as class_name, c.section,
        li.issue_date, li.due_date
      FROM library_issues li
      JOIN library_books lb ON lb.id = li.book_id
      JOIN students s ON s.id = li.student_id
      JOIN classes c ON c.id = s.class_id
      WHERE li.status = 'issued'
      ORDER BY li.issue_date ASC");
    $issued = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $error_message = 'ডেটা লোড করতে সমস্যা হয়েছে: ' . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>লাইব্রেরি রিটার্ন</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
    <div class="container-fluid">
        <a class="navbar-brand" href="../index.php"><i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট সিস্টেম</a>
        <div class="navbar-nav ms-auto">
            <a class="nav-link" href="manage.php"><i class="fas fa-tools"></i> ম্যানেজ</a>
            <a class="nav-link" href="index.php"><i class="fas fa-book"></i> বইয়ের তালিকা</a>
            <a class="nav-link" href="../logout.php"><i class="fas fa-sign-out-alt"></i> লগআউট</a>
        </div>
    </div>
</nav>

<div class="container-fluid mt-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h2><i class="fas fa-undo"></i> বই রিটার্ন</h2>
    </div>

    <?php if ($success_message): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle"></i> <?= htmlspecialchars($success_message) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>
    <?php if ($error_message): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-triangle"></i> <?= htmlspecialchars($error_message) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div class="card">
        <div class="card-header">
            <h5 class="mb-0"><i class="fas fa-list"></i> ইস্যুকৃত বই</h5>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>বই</th>
                            <th>স্টুডেন্ট</th>
                            <th>ক্লাস</th>
                            <th>ইস্যু তারিখ</th>
                            <th>ডিউ তারিখ</th>
                            <th class="text-end">রিটার্ন</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($issued)): ?>
                            <tr><td colspan="6" class="text-center text-muted">কোন ইস্যুকৃত বই নেই</td></tr>
                        <?php else: ?>
                            <?php foreach ($issued as $row): ?>
                                <tr>
                                    <td>
                                        <strong><?= htmlspecialchars($row['title']) ?></strong><br>
                                        <small class="text-muted"><?= htmlspecialchars($row['author']) ?></small>
                                    </td>
                                    <td>
                                        <strong><?= htmlspecialchars($row['first_name'] . ' ' . $row['last_name']) ?></strong><br>
                                        <small class="text-muted">ID: <?= htmlspecialchars($row['student_id']) ?> | Roll: <?= htmlspecialchars((string)$row['roll_number']) ?></small>
                                    </td>
                                    <td><?= htmlspecialchars($row['class_name'] . ' - ' . $row['section']) ?></td>
                                    <td><?= htmlspecialchars(date('d/m/Y', strtotime($row['issue_date']))) ?></td>
                                    <td><?= $row['due_date'] ? htmlspecialchars(date('d/m/Y', strtotime($row['due_date']))) : '-' ?></td>
                                    <td class="text-end">
                                        <form method="POST" action="" onsubmit="return confirm('রিটার্ন নিশ্চিত করবেন?');">
                                            <input type="hidden" name="issue_id" value="<?= (int)$row['issue_id'] ?>">
                                            <button type="submit" name="return_issue" class="btn btn-sm btn-success">
                                                <i class="fas fa-undo"></i> রিটার্ন
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>