<?php

declare(strict_types=1);

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

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

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

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

// ======================================================
// VALIDATE MEMBER
// ======================================================

if ($member_id <= 0) {

    header(
        'Location: list_members.php?msg=' .
        urlencode('Invalid member.')
    );

    exit;
}

// ======================================================
// FETCH MEMBER
// ======================================================

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

    FROM library_members

    WHERE id = ?
    AND school_id = ?

    LIMIT 1
");

$stmt->execute([

    $member_id,
    $school_id

]);

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

if (!$member) {

    header(
        'Location: list_members.php?msg=' .
        urlencode('Member not found.')
    );

    exit;
}

$page_title = 'Edit Library Member';

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 Library Member

                    </h1>

                    <small class="text-muted">

                        Update member information

                    </small>

                </div>

                <div>

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

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

                        Back to List

                    </a>

                </div>

            </div>

        </div>

    </section>

    <!-- ============================================== -->
    <!-- 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-lg-6">

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

                        <div class="card-header">

                            <h3 class="card-title">

                                Update Member Details

                            </h3>

                        </div>

                        <!-- FORM -->

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

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

                            <div class="card-body">

                                <!-- USER TYPE -->

                                <div class="form-group">

                                    <label>

                                        User Type

                                    </label>

                                    <input
                                        type="text"
                                        class="form-control"
                                        value="<?= htmlspecialchars($member['user_type']) ?>"
                                        readonly
                                    >

                                </div>

                                <!-- CARD NUMBER -->

                                <div class="form-group">

                                    <label>

                                        Library Card Number *

                                    </label>

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

                                </div>

                                <!-- STATUS -->

                                <div class="form-group">

                                    <label>

                                        Status *

                                    </label>

                                    <select
                                        id="status"
                                        class="form-control"
                                        required
                                    >

                                        <option
                                            value="Active"

                                            <?= $member['status'] === 'Active'
                                                ? 'selected'
                                                : '' ?>
                                        >

                                            Active

                                        </option>

                                        <option
                                            value="Inactive"

                                            <?= $member['status'] === 'Inactive'
                                                ? 'selected'
                                                : '' ?>
                                        >

                                            Inactive

                                        </option>

                                    </select>

                                </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 Member

                                </button>

                                <!-- DELETE -->

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

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

                                    Delete Member

                                </button>

                            </div>

                        </form>

                    </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 () {

    // ==========================================
    // UPDATE MEMBER
    // ==========================================

    $('#editMemberForm').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: 'member_process.php',

            type: 'POST',

            dataType: 'json',

            data: {

                action: 'update',

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

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

                status:
                    $('#status').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 Member'
                );
            },

            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 Member'
                );
            }
        });
    });

    // ==========================================
    // DELETE MEMBER
    // ==========================================

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

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

            return;
        }

        const deleteBtn =
            $('#deleteBtn');

        deleteBtn.prop('disabled', true);

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

        $.ajax({

            url: 'member_process.php',

            type: 'POST',

            dataType: 'json',

            data: {

                action: 'delete',

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

            success: function (response) {

                window.location.href =
                    'list_members.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 Member'
                );
            }
        });
    });
});

</script>

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