<?php
session_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
include('includes/config.php');

// ✅ Check login
if (strlen($_SESSION['alogin']) == 0) {
    header('location:index.php');
    exit;
}

/// ✅ Delete or Soft Delete Author (when authorid is comma-separated)
if (isset($_GET['del'])) {
    $id = intval($_GET['del']);

    // Step 1: Check if this author ID is present in any tblbooks row
    $checkSql = "SELECT COUNT(*) FROM tblbooks WHERE FIND_IN_SET(:id, AuthorIds)";
    $checkQuery = $dbh->prepare($checkSql);
    $checkQuery->bindParam(':id', $id, PDO::PARAM_INT);
    $checkQuery->execute();
    $count = $checkQuery->fetchColumn();

    if ($count > 0) {
        // Step 2: Soft delete (mark inactive)
        $sql = "UPDATE tblauthors SET is_deleted = 1 WHERE id = :id";
        $query = $dbh->prepare($sql);
        $query->bindParam(':id', $id, PDO::PARAM_INT);
        $query->execute();
        $_SESSION['delmsg'] = "Author deleted successfully";
    } else {
        // Step 3: Safe to hard delete
        $sql = "DELETE FROM tblauthors WHERE id = :id";
        $query = $dbh->prepare($sql);
        $query->bindParam(':id', $id, PDO::PARAM_INT);
        $query->execute();
        $_SESSION['delmsg'] = "Author deleted successfully";
    }

    header('location:manage-authors.php');
    exit;
}


?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Manage Authors | Library System</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="../<?php echo $_SESSION['logo']; ?>">

    <!-- ✅ Bootstrap 5 -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">

    <!-- ✅ DataTables Bootstrap 5 -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">

    <!-- ✅ FontAwesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">

    <style>
        .square-card {
            width: 100%;
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
            border-radius: 5px;
        }

        .flash-message {
            max-width: 600px;
            margin: 0 auto 15px;
        }

        .table-wrapper {
            overflow-x: auto;
            padding: 10px;
        }

        .col-md-12 h5 {
            color: #0d6efd;
            font-size: 20px;
        }

        .btn+.btn {
            margin-left: 5px;
        }
    </style>
</head>

<body>
    <div class="d-flex flex-column min-vh-100">
        <?php include('includes/header.php'); ?>

        <div class="main-content flex-grow-1">
            <div class="row pad-botm mb-4">
                <div class="col-md-12">
                    <h5 class="header-line" style="color:#0d6efd;">MANAGE AUTHORS</h5>
                </div>
            </div>

            <!-- Flash Messages Container -->
            <div class="row justify-content-center">
                <div class="col-md-8" id="flash-container">
                    <?php
                    foreach (['error', 'msg', 'updatemsg', 'delmsg'] as $type):
                        if (!empty($_SESSION[$type])): ?>
                            <div class="alert alert-<?php echo ($type == 'error') ? 'danger' : 'success'; ?> flash-message">
                                <strong><?php echo ucfirst($type); ?> :</strong> <?php echo htmlentities($_SESSION[$type]); ?>
                            </div>
                            <?php $_SESSION[$type] = ""; ?>
                            <?php
                        endif;
                    endforeach;
                    ?>
                </div>
            </div>


            <!-- ✅ Authors Table -->
            <div class="card square-card mb-5">
                <div class="card-header bg-secondary text-white d-flex justify-content-between align-items-center">
                    <span><i class="fa fa-user-edit mr-2"></i> Authors List</span>
                    <button class="btn btn-light btn-sm text-dark shadow-sm rounded-pill px-3"
                        onclick="openAuthorModal()">
                        <i class="fa fa-plus-circle"></i><b> ADD</b>
                    </button>
                </div>

                <div class="card-body table-wrapper">
                    <table id="authorsTable" class="table table-bordered table-hover table-sm text-dark">
                        <thead class="table-theme-header">
                            <tr>
                                <th>#</th>
                                <th>Author ID</th>
                                <th>Author Name</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>

                        </tbody>
                    </table>
                </div>
            </div>

            <!-- ✅ Author Modal -->
            <div class="modal fade" id="authorModal" tabindex="-1" role="dialog">
                <div class="modal-dialog modal-dialog-centered modal-md">
                    <div class="modal-content">
                        <div class="modal-header bg-primary text-white">
                            <h5 class="modal-title" id="authorModalTitle">Add Author</h5>
                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"
                                aria-label="Close"></button>
                        </div>
                        <form id="authorForm">
                            <div class="modal-body">
                                <input type="hidden" id="authorIdHidden" name="hidden_id">
                                <div class="form-group mb-3">
                                    <label>Author ID</label>
                                    <input type="text" id="authorId" name="author_id" class="form-control" readonly>
                                </div>
                                <div class="form-group mb-3">
                                    <label>Author Name</label>
                                    <input type="text" id="authorName" name="author_name" class="form-control" required>
                                </div>
                            </div>
                            <div class="modal-footer justify-content-center py-2">
                                <!-- <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> -->
                                <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">
                                    <i class="fa fa-times"></i> Cancel
                                </button>
                                <button type="submit" class="btn btn-success btn-sm">
                                    <i class="fa fa-save"></i> Save
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

        </div>
    </div>

    <?php include('includes/footer.php'); ?>

    <!-- ✅ Scripts -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

    <script>
        // $(document).ready(function(){
        //     $('#authorsTable').DataTable({pageLength:10,responsive:true});
        // });
        $(document).ready(function () {
            $('#authorsTable').DataTable({
                processing: true,
                serverSide: true,
                pageLength: 10,
                ajax: {
                    url: "fetch-authors.php",
                    type: "POST"
                },
                responsive: true,
                language: {
                    search: "🔍 Search Author Name:"
                }
            });
        });

        // Open Add Author Modal
        function openAuthorModal() {
            $("#authorModalTitle").text("Add Author");
            $("#authorIdHidden").val("");
            $("#authorId").val("");
            $("#authorName").val("");
            // Get next Author ID
            $.get("get-next-authorid.php", function (data) {
                $("#authorId").val(data);
            });
            const modal = new bootstrap.Modal(document.getElementById('authorModal'));
            modal.show();
        }

        // Open Edit Author Modal
        function editAuthor(id) {
            $.get("get-author.php", { id: id }, function (data) {
                let author = JSON.parse(data);
                $("#authorModalTitle").text("Edit Author");
                $("#authorIdHidden").val(author.id);
                $("#authorId").val(author.author_id);
                $("#authorName").val(author.author_name);
                const modal = new bootstrap.Modal(document.getElementById('authorModal'));
                modal.show();
            });
        }

        // Save / Update Author
        $("#authorForm").on("submit", function (e) {
            e.preventDefault();
            $.ajax({
                url: "save-author.php",
                type: "POST",
                data: $(this).serialize(),
                dataType: "json",
                success: function (response) {
                    $("#authorModal").modal("hide");
                    // Remove old messages
                    $("#flash-container .flash-message").remove();

                    // Add new message
                    let alertType = response.status === "success" ? "success" : "danger";
                    $("#flash-container").prepend(`
                <div class="alert alert-${alertType} flash-message text-center">
                    <strong>${response.status === "success" ? "Success!" : "Error!"}</strong> ${response.message}
                </div>
            `);

                    // Auto hide after 3s
                    setTimeout(() => $(".flash-message").fadeOut(), 3000);

                    if (response.status === "success") {
                        // Reload after short delay
                        setTimeout(() => location.reload(), 1500);
                    }
                },
                error: function () {
                    $("#flash-container .flash-message").remove();
                    $("#flash-container").prepend(`
                <div class="alert alert-danger flash-message text-center">
                    ⚠️ Something went wrong! Please try again.
                </div>
            `);
                    setTimeout(() => $(".flash-message").fadeOut(), 3000);
                }
            });
        });

    </script>
</body>

</html>