<?php

declare(strict_types=1);

require_once __DIR__ . '/../library/auth.php';

$school_id = (int) $_SESSION['school_id'];

allow_roles(['admin', 'teacher']);

// ======================================================
// FETCH ISSUED BOOKS
// ======================================================

$query = "
    SELECT

        bi.*,

        b.book_title,

        lm.card_no,
        lm.user_type,

        s.name AS student_name,

        t.name AS teacher_name

    FROM book_issues bi

    INNER JOIN books b
        ON bi.book_id = b.id

    INNER JOIN library_members lm
        ON bi.member_id = lm.id

    LEFT JOIN students s
        ON lm.reference_id = s.id
        AND lm.user_type = 'Student'

    LEFT JOIN teachers t
        ON lm.reference_id = t.id
        AND lm.user_type = 'Teacher'

    WHERE bi.school_id = ?

    ORDER BY bi.id DESC
";

$stmt = $pdo->prepare($query);

$stmt->execute([$school_id]);

$issued_books = $stmt->fetchAll(PDO::FETCH_ASSOC);

$page_title = 'Issued Books';

require_once __DIR__ . '/../include/header.php';
require_once __DIR__ . '/../include/sidebar.php';

?>

<div class="content-wrapper">

    <!-- ============================================== -->
    <!-- PAGE HEADER -->
    <!-- ============================================== -->

    <section class="content-header">

        <div class="container-fluid">

            <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center">

                <div class="mb-2 mb-md-0">

                    <h1>

                        <i class="fas fa-book-open text-primary"></i>

                        Issued Books

                    </h1>

                    <small class="text-muted">

                        Track issued and returned books

                    </small>

                </div>

                <div>

                    <a
                        href="book_issue.php"
                        class="btn btn-primary"
                    >

                        <i class="fas fa-plus"></i>

                        Issue Book

                    </a>

                </div>

            </div>

        </div>

    </section>

    <!-- ============================================== -->
    <!-- MAIN CONTENT -->
    <!-- ============================================== -->

    <section class="content">

        <div class="container-fluid">

            <!-- ALERT -->

            <div
                id="responseMessage"
                style="display:none;"
            ></div>

            <!-- ========================================== -->
            <!-- STATS -->
            <!-- ========================================== -->

            <div class="row mb-3">

                <!-- TOTAL -->

                <div class="col-12 col-md-4">

                    <div class="card shadow-sm border-0">

                        <div class="card-body">

                            <div class="d-flex justify-content-between align-items-center">

                                <div>

                                    <h6 class="text-muted">

                                        Total Records

                                    </h6>

                                    <h3>

                                        <?= count($issued_books) ?>

                                    </h3>

                                </div>

                                <div class="text-primary">

                                    <i class="fas fa-book fa-2x"></i>

                                </div>

                            </div>

                        </div>

                    </div>

                </div>

                <!-- ISSUED -->

                <div class="col-12 col-md-4">

                    <div class="card shadow-sm border-0">

                        <div class="card-body">

                            <div class="d-flex justify-content-between align-items-center">

                                <div>

                                    <h6 class="text-muted">

                                        Issued Books

                                    </h6>

                                    <h3>

                                        <?= count(array_filter($issued_books, fn($b) => $b['status'] === 'Issued')) ?>

                                    </h3>

                                </div>

                                <div class="text-warning">

                                    <i class="fas fa-book-reader fa-2x"></i>

                                </div>

                            </div>

                        </div>

                    </div>

                </div>

                <!-- RETURNED -->

                <div class="col-12 col-md-4">

                    <div class="card shadow-sm border-0">

                        <div class="card-body">

                            <div class="d-flex justify-content-between align-items-center">

                                <div>

                                    <h6 class="text-muted">

                                        Returned Books

                                    </h6>

                                    <h3>

                                        <?= count(array_filter($issued_books, fn($b) => $b['status'] === 'Returned')) ?>

                                    </h3>

                                </div>

                                <div class="text-success">

                                    <i class="fas fa-undo fa-2x"></i>

                                </div>

                            </div>

                        </div>

                    </div>

                </div>

            </div>

            <!-- ========================================== -->
            <!-- TABLE -->
            <!-- ========================================== -->

            <div class="card card-outline card-primary shadow-sm">

                <div class="card-header">

                    <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center">

                        <h3 class="card-title mb-2 mb-md-0">

                            <i class="fas fa-table"></i>

                            Issued Books Records

                        </h3>

                        <!-- SEARCH -->

                        <div style="max-width:300px; width:100%;">

                            <input
                                type="text"
                                id="searchInput"
                                class="form-control"
                                placeholder="Search records..."
                            >

                        </div>

                    </div>

                </div>

                <div class="card-body p-0">

                    <!-- DESKTOP TABLE -->

                    <div class="table-responsive d-none d-md-block">

                        <table class="table table-hover mb-0">

                            <thead class="thead-light">

                                <tr>

                                    <th width="70">

                                        #

                                    </th>

                                    <th>

                                        Book

                                    </th>

                                    <th>

                                        Member

                                    </th>

                                    <th>

                                        Issue Date

                                    </th>

                                    <th>

                                        Due Date

                                    </th>

                                    <th>

                                        Status

                                    </th>

                                    <th width="140">

                                        Actions

                                    </th>

                                </tr>

                            </thead>

                            <tbody id="issueTable">

                                <?php if (!empty($issued_books)) : ?>

                                    <?php foreach ($issued_books as $index => $row) : ?>

                                        <?php

                                        $name =
                                            $row['user_type'] === 'Student'

                                                ? $row['student_name']

                                                : $row['teacher_name'];

                                        ?>

                                        <tr>

                                            <td>

                                                <?= $index + 1 ?>

                                            </td>

                                            <td>

                                                <strong>

                                                    <?= htmlspecialchars($row['book_title']) ?>

                                                </strong>

                                            </td>

                                            <td>

                                                <?= htmlspecialchars($name ?? '-') ?>

                                                <br>

                                                <small class="text-muted">

                                                    <?= htmlspecialchars($row['card_no']) ?>

                                                </small>

                                            </td>

                                            <td>

                                                <?= date('d M Y', strtotime($row['issue_date'])) ?>

                                            </td>

                                            <td>

                                                <?= date('d M Y', strtotime($row['due_date'])) ?>

                                            </td>

                                            <td>

                                                <?php if ($row['status'] === 'Issued') : ?>

                                                    <span class="badge badge-warning p-2">

                                                        Issued

                                                    </span>

                                                <?php else : ?>

                                                    <span class="badge badge-success p-2">

                                                        Returned

                                                    </span>

                                                <?php endif; ?>

                                            </td>

                                            <td>

                                                <?php if ($row['status'] === 'Issued') : ?>

                                                    <button
                                                        type="button"
                                                        class="btn btn-success btn-sm returnBtn"
                                                        data-id="<?= (int) $row['id'] ?>"
                                                    >

                                                        <i class="fas fa-undo"></i>

                                                    </button>

                                                <?php else : ?>

                                                    <span class="text-success font-weight-bold">

                                                        Completed

                                                    </span>

                                                <?php endif; ?>

                                            </td>

                                        </tr>

                                    <?php endforeach; ?>

                                <?php else : ?>

                                    <tr>

                                        <td
                                            colspan="7"
                                            class="text-center text-muted p-5"
                                        >

                                            No issue records found.

                                        </td>

                                    </tr>

                                <?php endif; ?>

                            </tbody>

                        </table>

                    </div>

                    <!-- MOBILE VIEW -->

                    <div class="d-block d-md-none p-3">

                        <?php if (!empty($issued_books)) : ?>

                            <?php foreach ($issued_books as $row) : ?>

                                <?php

                                $name =
                                    $row['user_type'] === 'Student'

                                        ? $row['student_name']

                                        : $row['teacher_name'];

                                ?>

                                <div class="card shadow-sm border-0 mb-3">

                                    <div class="card-body">

                                        <div class="d-flex justify-content-between align-items-start">

                                            <div>

                                                <h5 class="mb-1">

                                                    <?= htmlspecialchars($row['book_title']) ?>

                                                </h5>

                                                <small class="text-muted">

                                                    <?= htmlspecialchars($name ?? '-') ?>

                                                </small>

                                            </div>

                                            <div>

                                                <?php if ($row['status'] === 'Issued') : ?>

                                                    <span class="badge badge-warning">

                                                        Issued

                                                    </span>

                                                <?php else : ?>

                                                    <span class="badge badge-success">

                                                        Returned

                                                    </span>

                                                <?php endif; ?>

                                            </div>

                                        </div>

                                        <hr>

                                        <div class="mb-2">

                                            <small class="text-muted">

                                                Card No:

                                            </small>

                                            <?= htmlspecialchars($row['card_no']) ?>

                                        </div>

                                        <div class="mb-2">

                                            <small class="text-muted">

                                                Issue Date:

                                            </small>

                                            <?= date('d M Y', strtotime($row['issue_date'])) ?>

                                        </div>

                                        <div class="mb-3">

                                            <small class="text-muted">

                                                Due Date:

                                            </small>

                                            <?= date('d M Y', strtotime($row['due_date'])) ?>

                                        </div>

                                        <?php if ($row['status'] === 'Issued') : ?>

                                            <button
                                                type="button"
                                                class="btn btn-success btn-sm btn-block returnBtn"
                                                data-id="<?= (int) $row['id'] ?>"
                                            >

                                                <i class="fas fa-undo"></i>

                                                Return Book

                                            </button>

                                        <?php else : ?>

                                            <div class="text-success text-center font-weight-bold">

                                                Completed

                                            </div>

                                        <?php endif; ?>

                                    </div>

                                </div>

                            <?php endforeach; ?>

                        <?php else : ?>

                            <div class="alert alert-warning text-center">

                                No issue records found.

                            </div>

                        <?php endif; ?>

                    </div>

                </div>

            </div>

        </div>

    </section>

</div>

<!-- ============================================== -->
<!-- SCRIPTS -->
<!-- ============================================== -->

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<script>

'use strict';

$(document).ready(function () {

    // ==========================================
    // SEARCH
    // ==========================================

    $('#searchInput').on('keyup', function () {

        let value =
            $(this).val().toLowerCase();

        $('#issueTable tr').filter(function () {

            $(this).toggle(

                $(this)
                    .text()
                    .toLowerCase()
                    .indexOf(value) > -1
            );
        });
    });

    // ==========================================
    // RETURN BOOK
    // ==========================================

    $('.returnBtn').on('click', function () {

        if (!confirm(
            'Return this book?'
        )) {

            return;
        }

        const button =
            $(this);

        button.prop('disabled', true);

        button.html(
            '<i class="fas fa-spinner fa-spin"></i>'
        );

        $.ajax({

            url: 'issue_process.php',

            type: 'POST',

            dataType: 'json',

            data: {

                action: 'return',

                issue_id:
                    button.data('id')
            },

            success: function (response) {

                $('#responseMessage')

                    .removeClass()

                    .addClass(
                        'alert alert-success'
                    )

                    .html(response.message)

                    .fadeIn();

                setTimeout(function () {

                    location.reload();

                }, 1000);
            },

            error: function (xhr) {

                let response =
                    xhr.responseJSON;

                $('#responseMessage')

                    .removeClass()

                    .addClass(
                        'alert alert-danger'
                    )

                    .html(
                        response?.message ||
                        'Something went wrong.'
                    )

                    .fadeIn();

                button.prop('disabled', false);

                button.html(
                    '<i class="fas fa-undo"></i>'
                );
            }
        });
    });
});

</script>

<?php require_once __DIR__ . '/../include/footer.php'; ?>