<?php

declare(strict_types=1);

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

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

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

$book_id = (int)
    ($_GET['id'] ?? 0);

// ======================================================
// VALIDATE BOOK
// ======================================================

if ($book_id <= 0) {

    header(
        'Location: list_books.php?msg=' .
        urlencode('Invalid book.')
    );

    exit;
}

// ======================================================
// FETCH BOOK
// ======================================================

$stmt = $pdo->prepare("
    SELECT *

    FROM books

    WHERE id = ?
    AND school_id = ?

    LIMIT 1
");

$stmt->execute([

    $book_id,
    $school_id

]);

$book = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$book) {

    header(
        'Location: list_books.php?msg=' .
        urlencode('Book not found.')
    );

    exit;
}

$page_title = 'Edit Book';

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-edit text-success"></i>

                        Edit Book

                    </h1>

                    <small class="text-muted">

                        Update library book details

                    </small>

                </div>

                <div>

                    <a
                        href="list_books.php"
                        class="btn btn-info"
                    >

                        <i class="fas fa-arrow-left"></i>

                        Back to Books

                    </a>

                </div>

            </div>

        </div>

    </section>

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

    <section class="content">

        <div class="container-fluid">

            <!-- RESPONSE -->

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

            <div class="row justify-content-center">

                <div class="col-12 col-xl-10">

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

                        <div class="card-header">

                            <h3 class="card-title">

                                Edit Book Information

                            </h3>

                        </div>

                        <!-- FORM -->

                        <form
                            id="editBookForm"
                            autocomplete="off"
                        >

                            <input
                                type="hidden"
                                id="book_id"
                                value="<?= (int) $book['id'] ?>"
                            >

                            <div class="card-body">

                                <div class="row">

                                    <!-- BOOK TITLE -->

                                    <div class="col-md-6">

                                        <div class="form-group">

                                            <label>

                                                Book Title *

                                            </label>

                                            <input
                                                type="text"
                                                id="book_title"
                                                class="form-control"
                                                maxlength="255"
                                                value="<?= htmlspecialchars($book['book_title']) ?>"
                                                required
                                            >

                                        </div>

                                    </div>

                                    <!-- BOOK NO -->

                                    <div class="col-md-6">

                                        <div class="form-group">

                                            <label>

                                                Book Number

                                            </label>

                                            <input
                                                type="text"
                                                id="book_no"
                                                class="form-control"
                                                maxlength="100"
                                                value="<?= htmlspecialchars($book['book_no']) ?>"
                                            >

                                        </div>

                                    </div>

                                    <!-- ISBN -->

                                    <div class="col-md-6">

                                        <div class="form-group">

                                            <label>

                                                ISBN Number

                                            </label>

                                            <input
                                                type="text"
                                                id="isbn_no"
                                                class="form-control"
                                                maxlength="100"
                                                value="<?= htmlspecialchars($book['isbn_no']) ?>"
                                            >

                                        </div>

                                    </div>

                                    <!-- PUBLISHER -->

                                    <div class="col-md-6">

                                        <div class="form-group">

                                            <label>

                                                Publisher

                                            </label>

                                            <input
                                                type="text"
                                                id="publish"
                                                class="form-control"
                                                maxlength="255"
                                                value="<?= htmlspecialchars($book['publish']) ?>"
                                            >

                                        </div>

                                    </div>

                                    <!-- AUTHOR -->

                                    <div class="col-md-6">

                                        <div class="form-group">

                                            <label>

                                                Author

                                            </label>

                                            <input
                                                type="text"
                                                id="author"
                                                class="form-control"
                                                maxlength="255"
                                                value="<?= htmlspecialchars($book['author']) ?>"
                                            >

                                        </div>

                                    </div>

                                    <!-- SUBJECT -->

                                    <div class="col-md-6">

                                        <div class="form-group">

                                            <label>

                                                Subject

                                            </label>

                                            <input
                                                type="text"
                                                id="subject"
                                                class="form-control"
                                                maxlength="255"
                                                value="<?= htmlspecialchars($book['subject']) ?>"
                                            >

                                        </div>

                                    </div>

                                    <!-- RACK -->

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

                                        <div class="form-group">

                                            <label>

                                                Rack Number

                                            </label>

                                            <input
                                                type="text"
                                                id="rack_no"
                                                class="form-control"
                                                maxlength="50"
                                                value="<?= htmlspecialchars($book['rack_no']) ?>"
                                            >

                                        </div>

                                    </div>

                                    <!-- QUANTITY -->

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

                                        <div class="form-group">

                                            <label>

                                                Quantity *

                                            </label>

                                            <input
                                                type="number"
                                                id="qty"
                                                class="form-control"
                                                min="0"
                                                value="<?= (int) $book['qty'] ?>"
                                                required
                                            >

                                        </div>

                                    </div>

                                    <!-- PRICE -->

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

                                        <div class="form-group">

                                            <label>

                                                Price

                                            </label>

                                            <input
                                                type="number"
                                                step="0.01"
                                                id="perunitcost"
                                                class="form-control"
                                                min="0"
                                                value="<?= htmlspecialchars($book['perunitcost']) ?>"
                                            >

                                        </div>

                                    </div>

                                    <!-- DATE -->

                                    <div class="col-md-6">

                                        <div class="form-group">

                                            <label>

                                                Purchase Date

                                            </label>

                                            <input
                                                type="date"
                                                id="postdate"
                                                class="form-control"
                                                value="<?= htmlspecialchars($book['postdate']) ?>"
                                            >

                                        </div>

                                    </div>

                                    <!-- DESCRIPTION -->

                                    <div class="col-12">

                                        <div class="form-group">

                                            <label>

                                                Description

                                            </label>

                                            <textarea
                                                id="description"
                                                class="form-control"
                                                rows="4"
                                            ><?= htmlspecialchars($book['description']) ?></textarea>

                                        </div>

                                    </div>

                                </div>

                            </div>

                            <!-- FOOTER -->

                            <div class="card-footer d-flex flex-column flex-md-row justify-content-between">

                                <!-- UPDATE -->

                                <button
                                    type="submit"
                                    class="btn btn-success mb-2 mb-md-0"
                                    id="updateBtn"
                                >

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

                                    Update Book

                                </button>

                                <!-- DELETE -->

                                <button
                                    type="button"
                                    class="btn btn-danger"
                                    id="deleteBtn"
                                >

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

                                    Delete Book

                                </button>

                            </div>

                        </form>

                    </div>

                </div>

            </div>

        </div>

    </section>

</div>

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

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

<script src="assets/js/books.js"></script>

<script>

'use strict';

$(document).ready(function () {

    // ==========================================
    // UPDATE BOOK
    // ==========================================

    $('#editBookForm').on('submit', function (event) {

        event.preventDefault();

        const updateBtn =
            $('#updateBtn');

        updateBtn.prop('disabled', true);

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

        $.ajax({

            url: 'book_process.php',

            type: 'POST',

            dataType: 'json',

            data: {

                action: 'update',

                book_id:
                    $('#book_id').val(),

                book_title:
                    $('#book_title').val(),

                book_no:
                    $('#book_no').val(),

                isbn_no:
                    $('#isbn_no').val(),

                publish:
                    $('#publish').val(),

                author:
                    $('#author').val(),

                subject:
                    $('#subject').val(),

                rack_no:
                    $('#rack_no').val(),

                qty:
                    $('#qty').val(),

                perunitcost:
                    $('#perunitcost').val(),

                postdate:
                    $('#postdate').val(),

                description:
                    $('#description').val()
            },

            success: function (response) {

                $('#responseMessage')

                    .removeClass()

                    .addClass(
                        'alert alert-success'
                    )

                    .html(response.message)

                    .fadeIn();

                updateBtn.prop('disabled', false);

                updateBtn.html(
                    '<i class="fas fa-save"></i> Update Book'
                );
            },

            error: function (xhr) {

                let response =
                    xhr.responseJSON;

                $('#responseMessage')

                    .removeClass()

                    .addClass(
                        'alert alert-danger'
                    )

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

                    .fadeIn();

                updateBtn.prop('disabled', false);

                updateBtn.html(
                    '<i class="fas fa-save"></i> Update Book'
                );
            }
        });
    });

    // ==========================================
    // DELETE BOOK
    // ==========================================

    $('#deleteBtn').on('click', function () {

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

            return;
        }

        const deleteBtn =
            $('#deleteBtn');

        deleteBtn.prop('disabled', true);

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

        $.ajax({

            url: 'book_process.php',

            type: 'POST',

            dataType: 'json',

            data: {

                action: 'delete',

                book_id:
                    $('#book_id').val()
            },

            success: function (response) {

                window.location.href =
                    'list_books.php?msg=' +
                    encodeURIComponent(
                        response.message
                    );
            },

            error: function (xhr) {

                let response =
                    xhr.responseJSON;

                $('#responseMessage')

                    .removeClass()

                    .addClass(
                        'alert alert-danger'
                    )

                    .html(
                        response?.message ||
                        'Delete failed.'
                    )

                    .fadeIn();

                deleteBtn.prop('disabled', false);

                deleteBtn.html(
                    '<i class="fas fa-trash"></i> Delete Book'
                );
            }
        });
    });
});

</script>

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