<?php

session_start();

if (!isset($_SESSION['userid'])) {
    header("Location: ./Sign&Log.php");
    exit();
}


require "./connect.php";

try {
    $stmt = $conn->prepare("SELECT role FROM users WHERE userid = :userid");
    $stmt->bindParam(':userid', $_SESSION['userid'], PDO::PARAM_INT);
    $stmt->execute();

    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$user || $user['role'] !== 'Admin') {
        header("Location: ./Sign&Log.php");
        exit();
    }

} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
    exit();
}


// Query the users table
//Indexed
$query = "
    SELECT users.userid, users.username, users.email, member.membership_status, member.memberid
    FROM users
    LEFT JOIN member ON users.userid = member.userid
";

$res = $conn->query($query);

$users = [];

while($row = $res->fetch(PDO::FETCH_ASSOC)) {
    $users[] = $row;
}


// SQL query to get loan, book, book_copies, and member information
    $query = "
        SELECT loan.loanid, loan.memberid, book.bookid, book_copies.copyid, loan.status
        FROM loan
        INNER JOIN book_copies ON loan.bookcopyid = book_copies.copyid
        INNER JOIN book ON book_copies.bookid = book.bookid
        INNER JOIN member ON loan.memberid = member.memberid
    ";

    $res = $conn->query($query);

    $loans = [];
    while ($row = $res->fetch(PDO::FETCH_ASSOC)) {
        $loans[] = $row;
    }

// SQL Query to get Fine

$query = " SELECT * FROM Fine";
$res = $conn->query($query);

$fines = [];

while($row = $res->fetch(PDO::FETCH_ASSOC)){
    $fines[] = $row;
}


// SQL Query to get Author
$query = "SELECT * FROM Author ORDER BY authorid";
$res = $conn->query($query);

$authors = [];

while($row = $res->fetch(PDO::FETCH_ASSOC)){
    $authors[] = $row;
}

// SQL Query to get Book
$query = "
    SELECT b.*, a.FirstName, a.LastName
    FROM Book b
    JOIN Book_Author ba ON b.BookID = ba.BookID
    JOIN Author a ON ba.AuthorID = a.AuthorID";
$res = $conn->query($query);

$books = [];

while($row = $res->fetch(PDO::FETCH_ASSOC)){
    $books[] = $row;
}


// SQL Query for Dashboiard
$totalBooksQuery = "SELECT COUNT(*) AS total_books FROM Book";
$borrowedBooksQuery = "SELECT COUNT(*) AS borrowed_books FROM Loan WHERE status != 'Returned'";
$totalUsersQuery = "SELECT COUNT(*) AS total_users FROM Users";
$unpaidFinesQuery = "SELECT SUM(FineAmount) AS unpaid_fines FROM Fine WHERE Status = 'Unpaid'";

// Execute queries
$totalBooksResult = $conn->query($totalBooksQuery)->fetch(PDO::FETCH_ASSOC);
$borrowedBooksResult = $conn->query($borrowedBooksQuery)->fetch(PDO::FETCH_ASSOC);
$totalUsersResult = $conn->query($totalUsersQuery)->fetch(PDO::FETCH_ASSOC);
$unpaidFinesResult = $conn->query($unpaidFinesQuery)->fetch(PDO::FETCH_ASSOC);

// Data for the dashboard
$totalBooks = $totalBooksResult['total_books'];
$borrowedBooks = $borrowedBooksResult['borrowed_books'];
$totalUsers = $totalUsersResult['total_users'];
$unpaidFines = $unpaidFinesResult['unpaid_fines'];


?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Librarian Dashboard</title>
    <link href='https://fonts.googleapis.com/css?family=EB Garamond' rel='stylesheet'>
    <link href='https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css' rel='stylesheet'>
    <link rel="stylesheet" href="./CSS/Admin.css">
    <link rel="stylesheet" href="DashboardMBooks.css">

    <link rel="stylesheet" href="">

    <style>
    .autocomplete-wrapper {
        position: relative;
    }

    .suggestions-list {
        position: absolute;
        top: 100%;
        left: 0;
        right: 0;
        background: white;
        border: 1px solid #ddd;
        border-top: none;
        max-height: 200px;
        overflow-y: auto;
        display: none;
        z-index: 1000;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }

    .suggestion-item {
        padding: 8px 12px;
        cursor: pointer;
    }

    .suggestion-item:hover {
        background-color: #f5f5f5;
    }
    </style>

</head>

<body>
    <div class="sidebar">
        <div class="logo-details">
            <div class="logo_name">Book Tracker</div>
            <i class='bx bx-menu' id="btn"></i>
        </div>
        <ul class="nav-list">
            <!-- Dashboard link -->
            <li>
                <a href="#" onclick="showContent('dashboard')">
                    <i class='bx bx-grid-alt'></i>
                    <span class="links_name">Dashboard</span>
                </a>
            </li>

            <!-- Books section -->
            <li>
                <a href="#" onclick="toggleSubmenu('books-submenu')">
                    <i class='bx bx-book'></i>
                    <span class="links_name">Books</span>
                </a>
                <ul class="submenu" id="books-submenu">
                    <li>
                        <a href="#" onclick="showContent('view-books')">
                            <i class='bx bx-library'></i>
                            <span class="links_name">View & Manage</span>
                        </a>
                    </li>
                    <li>
                        <a href="#" onclick="showContent('add-book')">
                            <i class='bx bx-plus'></i>
                            <span class="links_name">Add New Book</span>
                        </a>
                    </li>
                    <li>
                        <a href="#" onclick="showContent('view-authors')">
                            <i class='bx bx-group'></i>
                            <span class="links_name">View & Manage</span>
                        </a>
                    </li>
                    <li>
                        <a href="#" onclick="showContent('add-author')">
                            <i class='bx bx-user-plus'></i>
                            <span class="links_name">Add New Author</span>
                        </a>
                    </li>
                </ul>
            </li>

            <!-- Users section -->
            <li>
                <a href="#" onclick="showContent('user')">
                    <i class='bx bx-user'></i>
                    <span class="links_name">Users</span>
                </a>
            </li>
            <!-- Loans section -->
            <li>
                <a href="#" onclick="showContent('loans')">
                    <i class='bx bx-cart'></i>
                    <span class="links_name">Loan</span>
                </a>
            </li>
            <!-- Fines section -->
            <li>
                <a href="#" onclick="toggleSubmenu('fines-submenu')">
                    <i class='bx bx-money'></i>
                    <span class="links_name">Fines</span>
                </a>
                <ul class="submenu" id="fines-submenu">
                    <li>
                        <a href="#" onclick="showContent('view-fines')">
                            <i class='bx bx-list-ul'></i>
                            <span class="links_name">View Fines</span>
                        </a>
                    </li>
                    <li>
                        <a href="#" onclick="showContent('issue-fine')">
                            <i class='bx bx-plus-circle'></i>
                            <span class="links_name">Issue a Fine</span>
                        </a>
                    </li>
                </ul>
            </li>

            <!-- Logout & Toggle Mode section -->
            <li>
                <a href="./Logout.php" class="action-link">
                    <i class='bx bx-log-out'></i>
                    <span class="links_name">Logout</span>
                </a>
            </li>

            <li>
                <a href="#" onclick="toggleMode()">
                    <i class='bx bx-moon'></i>
                    <span class="links_name">Toggle Mode</span>
                </a>
            </li>

            <li>
                <a href="./CaseViews.php" class="action-link">
                    <i class='bx bx-low-vision'></i>
                    <span class="links_name">Case Views</span>
                </a>
            </li>
        </ul>
    </div>

    <div id="content-area"></div>

    <script>

        function showContent(contentId) {
        const contentArea = document.getElementById('content-area');

    switch(contentId) {
        case 'dashboard':
            contentArea.innerHTML = `
                <section class="home-section">
                    <div class="dashboard-container">
                        <div class="cards-container">
                            <!-- Total Books Card -->
                            <div class="card books">
                                <i class='bx bx-book card-icon'></i>
                                <h3 class="card-title">Total Books</h3>
                                <div class="card-value"><?php echo number_format($totalBooks); ?></div>
                            </div>

                            <!-- Books Borrowed Card -->
                            <div class="card borrowed">
                                <i class='bx bx-bookmark card-icon'></i>
                                <h3 class="card-title">Books Borrowed</h3>
                                <div class="card-value"><?php echo number_format($borrowedBooks); ?></div>
                            </div>

                            <!-- Total Users Card -->
                            <div class="card users">
                                <i class='bx bx-user card-icon'></i>
                                <h3 class="card-title">Total Users</h3>
                                <div class="card-value"><?php echo number_format($totalUsers); ?></div>
                            </div>

                            <!-- Unpaid Fines Card -->
                            <div class="card fines">
                                <i class='bx bx-money card-icon'></i>
                                <h3 class="card-title">Unpaid Fines</h3>
                                <div class="card-value">$<?php echo number_format($unpaidFines); ?></div>
                            </div>
                        </div>
                    </div>
                </section>
            `;
            break;

            
    case 'add-book':
        contentArea.innerHTML = `
        <section class="home-section" id="add-book-section">
            <div class="add-book-container">
                <h2 class="form-header">Add New Book</h2>
                <form id="addBookForm" onsubmit="addBook(event)">
                    <!-- Book Table Fields -->
                    <div class="form-row">
                        <div class="form-group">
                            <label for="title">Book Title*</label>
                            <input type="text" id="title" name="title" required>
                            <div class="error-message" id="titleError">Please enter a valid title</div>
                        </div>
                        <div class="form-group">
                            <label for="isbn">ISBN*</label>
                            <input type="text" id="isbn" name="isbn" required>
                            <div class="error-message" id="isbnError">Please enter a valid ISBN</div>
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label for="genre">Genre*</label>
                                <input type="text" id="genre" name="genre" required>
                        </div>
                        <div class="form-group">
                            <label for="publishedYear">Published Year*</label>
                            <input type="number" id="publishedYear" name="publishedYear" required>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="description">Book Description</label>
                        <textarea id="description" name="description" rows="4"></textarea>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label for="totalCopies">Total Copies*</label>
                            <input type="number" id="totalCopies" name="totalCopies" min="1" required>
                        </div>
                        <div class="form-group">
                            <label for="coverImage">Cover Image</label>
                            <div class="file-upload">
                                <label for="coverImage" class="file-upload-label">
                                    <i class='bx bx-upload'></i> Choose Cover Image
                                </label>
                                <input type="file" id="coverImage" name="coverImage" accept="image/*">
                            </div>
                        </div>
                    </div>

                    <!-- Book_Details Table Fields -->
                    <div class="form-row">
                        <div class="form-group">
                            <label for="format">Format*</label>
                                <select id="format" name="format" required>
                                    <option value="">Select Format</option>
                                    <option value="Hardcover">Hardcover</option>
                                    <option value="Paperback">Paperback</option>
                                </select>
                        </div>
                        <div class="form-group">
                            <label for="language">Language*</label>
                            <input type="text" id="language" name="language" required>
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label for="pages">Number of Pages*</label>
                            <input type="number" id="pages" name="pages" min="1" required>
                        </div>
                        <div class="form-group">
                            <label for="publisher">Publisher*</label>
                            <input type="text" id="publisher" name="publisher" required>
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label for="author">Author*</label>
                            <div class="autocomplete-wrapper">
                                <input type="text" 
                                    id="authorSearch" 
                                    name="authorSearch" 
                                    placeholder="Start typing author name..." 
                                    required>
                                <input type="hidden" id="authorId" name="author">
                                <div id="authorSuggestions" class="suggestions-list"></div>
                            </div>
                        </div>
                    </div>

                    <!-- Book_Copies Table Fields -->
                    <div id="copiesSection">
                        <h3>Book Copies</h3>
                        <div id="copiesContainer">
                            <div class="copy-entry form-row">
                                <div class="form-group">
                                    <label for="condition">Condition*</label>
                                    <select name="condition[]" required>
                                        <option value="">Select Condition</option>
                                        <option value="New">New</option>
                                        <option value="Good">Good</option>
                                        <option value="Damaged">Damaged</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label for="quantity">Quantity*</label>
                                    <input type="number" name="quantity[]" min="1" required>
                                </div>
                                <button type="button" class="btn btn-secondary remove-copy" style="display: none;"> <i class='bx bx-x'></i> </button>
                            </div>
                        </div>
                        <button type="button" class="btn btn-secondary" onclick="addCopyEntry()">Add Another Condition</button>
                    </div>

                    <div class="btn-container">
                        <button type="button" class="btn btn-secondary" onclick="resetForm()">Clear Form</button>
                        <button type="submit" class="btn btn-primary">Add Book</button>
                    </div>
                </form>
            </div>
        </section>
    `;

        const script = document.createElement('script');
        script.textContent = `
            let timeoutId;

            document.getElementById('authorSearch').addEventListener('input', function(e) {
            clearTimeout(timeoutId);
            const searchTerm = e.target.value;
            
            // Clear previous selection when input changes
            document.getElementById('authorId').value = '';
            
            if (searchTerm.length < 2) {
                document.getElementById('authorSuggestions').style.display = 'none';
                return;
            }

            // Add delay to prevent too many requests
            timeoutId = setTimeout(() => {
                fetchAuthors(searchTerm);
            }, 300);
        });

        // Prevent manual entry without selection
        document.getElementById('authorSearch').addEventListener('change', function(e) {
            const authorId = document.getElementById('authorId').value;
            if (!authorId || authorId.trim() === '') {
                // If no author is selected from suggestions, clear the input
                setTimeout(() => {
                    if (!document.getElementById('authorId').value) {
                        this.value = '';
                    }
                }, 200);
            }
        });

        function fetchAuthors(searchTerm) {
            fetch('../Admin Actions/GetAuthor.php?search=' + encodeURIComponent(searchTerm))
                .then(response => response.json())
                .then(authors => {
                    console.log('Authors response:', authors); // Add this line to see the response
                    const suggestionsDiv = document.getElementById('authorSuggestions');
                    suggestionsDiv.innerHTML = '';
                    
                    if (authors.length > 0) {
                        authors.forEach(author => {
                            const div = document.createElement('div');
                            div.className = 'suggestion-item';
                            div.textContent = \`\${author.firstname} \${author.lastname}\`;
                            div.addEventListener('click', () => {
                                // Update both the visible search field and hidden author ID
                                document.getElementById('authorSearch').value = \`\${author.firstname} \${author.lastname}\`;
                                document.getElementById('authorId').value = author.authorid;
                                console.log('Set author ID to:', author.authorid); // Add this line
                                suggestionsDiv.style.display = 'none';
                            });
                            suggestionsDiv.appendChild(div);
                        });
                        suggestionsDiv.style.display = 'block';
                    } else {
                        suggestionsDiv.style.display = 'none';
                    }
                })
                .catch(error => {
                    console.error('Error fetching authors:', error);
                });
        }

            // Close suggestions when clicking outside
            document.addEventListener('click', function(e) {
                if (!e.target.closest('.autocomplete-wrapper')) {
                    document.getElementById('authorSuggestions').style.display = 'none';
                }
            });

            function addCopyEntry() {
            const container = document.getElementById('copiesContainer');
            const firstEntry = container.querySelector('.copy-entry');
            const newEntry = firstEntry.cloneNode(true); // Clone the first entry

            // Reset values for the new entry
            newEntry.querySelector('select').value = '';
            newEntry.querySelector('input').value = '';

            // Show the remove button for the new entry
            const removeButton = newEntry.querySelector('.remove-copy');
            removeButton.style.display = 'block';

            // Add remove button functionality
            removeButton.addEventListener('click', function() {
                newEntry.remove(); // Remove the entry
                updateTotalCopies(); // Update the total copies
            });

            // Append the new entry to the container
            container.appendChild(newEntry);

            // Update the total copies after adding a new entry
            updateTotalCopies();
        }

        function updateTotalCopies() {
            const quantityInputs = document.querySelectorAll('#copiesContainer input[name="quantity[]"]');
            let totalCopies = 0;

            // Sum up all the quantities
            quantityInputs.forEach(input => {
                const quantity = parseInt(input.value) || 0; // Convert to integer or default to 0
                totalCopies += quantity;
            });

            // Update the totalCopies input field (if it exists)
            const totalCopiesInput = document.querySelector('input[name="totalCopies"]');
            if (totalCopiesInput) {
                totalCopiesInput.value = totalCopies;
            }
        }

        // Add event listener to the copies container for quantity changes
        document.getElementById('copiesContainer').addEventListener('input', function(e) {
            if (e.target.name === 'quantity[]') {
                updateTotalCopies();
            }
        });

        // Disable remove button for the first entry
        const firstEntryRemoveButton = document.querySelector('#copiesContainer .copy-entry .remove-copy');
        if (firstEntryRemoveButton) {
            firstEntryRemoveButton.style.display = 'none';
        }

            function resetForm() {
                document.getElementById('addBookForm').reset();
                const container = document.getElementById('copiesContainer');
                const entries = container.querySelectorAll('.copy-entry');
                // Keep the first entry, remove the rest
                for (let i = 1; i < entries.length; i++) {
                    entries[i].remove();
                }
                updateTotalCopies();
            }`;
        document.body.appendChild(script);
        break;

        case 'view-books':
            contentArea.innerHTML = `
                <section class="home-section">
                    <div class="manage-books-container">
                        <div class="controls-section">
                            <div class="search-container">
                                <input type="text" class="search-input" placeholder="Search by title, author, or ISBN...">
                                <button class="btn btn-edit" onclick="searchBooks()">Search</button>
                            </div>
                        </div>

                        <table class="books-table">
                            <thead>
                                <tr>
                                    <th>Book ID</th>
                                    <th>Title</th>
                                    <th>Author</th>
                                    <th>ISBN</th>
                                    <th>Copies</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody id="booksTableBody">
                            <?php foreach($books as $book): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($book['bookid']); ?></td>
                                        <td><?php echo htmlspecialchars($book['title']); ?></td>
                                        <td><?php echo htmlspecialchars($book['firstname'] . ' ' . $book['lastname']); ?></td>
                                        <td><?php echo htmlspecialchars($book['isbn']); ?></td>
                                        <td><?php echo htmlspecialchars($book['totalcopies']); ?></td>
                                        <td>
                                            <button class="btn btn-edit" onclick="editBook(<?php echo $book['bookid']; ?>)">Edit</button>
                                            <button class="btn btn-delete" onclick="deleteBook(<?php echo $book['bookid']; ?>)">Delete</button>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>

                        <div class="pagination">
                            <button onclick="changePage(1)">1</button>
                            <button onclick="changePage(2)">2</button>
                            <button onclick="changePage(3)">3</button>
                            <button>...</button>
                        </div>
                    </div>
                </section>

                <!-- Edit Book Modal -->
                <div id="editModal" class="modal">
                <div class="modal-content">
                    <span class="close-modal" onclick="closeModal()">&times;</span>
                    <h2>Edit Book</h2>
                    <form id="editBookForm" onsubmit="updateBook(event)">
                        <input type="hidden" id="bookId" name="bookId">

                        <!-- Book Table Fields -->
                        <div class="form-row">
                            <div class="form-group">
                                <label for="editTitle">Book Title*</label>
                                <input type="text" id="editTitle" name="title" required>
                                <div class="error-message" id="editTitleError">Please enter a valid title</div>
                            </div>
                            <div class="form-group">
                                <label for="editIsbn">ISBN*</label>
                                <input type="text" id="editIsbn" name="isbn" required>
                                <div class="error-message" id="editIsbnError">Please enter a valid ISBN</div>
                            </div>
                        </div>

                        <div class="form-row">
                            <div class="form-group">
                                <div class="form-group">
                                    <label for="editGenre">Genre*</label>
                                    <input type="text" id="editGenre" name="genre" required>
                                    <div class="error-message" id="editGenreError">Please enter a valid Genre</div>
                            </div>
                            </div>
                            <div class="form-group">
                                <label for="editPublishedYear">Published Year*</label>
                                <input type="number" id="editPublishedYear" name="publishedYear" required min="1800" max="2024">
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="editDescription">Book Description</label>
                            <textarea id="editDescription" name="description" rows="4"></textarea>
                        </div>

                        <div class="form-row">
                            <div class="form-group">
                                <label for="editTotalCopies">Total Copies*</label>
                                <input type="number" id="editTotalCopies" name="totalCopies" min="1" required>
                            </div>
                            <div class="form-group">
                                <label for="editCoverImage">Cover Image</label>
                                <div class="file-upload">
                                    <label for="editCoverImage" class="file-upload-label">
                                        <i class='bx bx-upload'></i> Choose Cover Image
                                    </label>
                                    <input type="file" id="editCoverImage" name="coverImage" accept="image/*">
                                    <div id="currentCoverImage"></div>
                                </div>
                            </div>
                        </div>

                        <!-- Book_Details Table Fields -->
                        <div class="form-row">
                            <div class="form-group">
                                <div class="form-group">
                                    <label for="editFormat">Format*</label>
                                    <input type="text" id="editFormat" name="format" required>
                                <div class="error-message" id="editFormatError">Please enter a valid Format</div>
                            </div>
                            </div>
                            <div class="form-group">
                                <label for="editLanguage">Language*</label>
                                <input type="text" id="editLanguage" name="language" required>
                            </div>
                        </div>

                        <div class="form-row">
                            <div class="form-group">
                                <label for="editPages">Number of Pages*</label>
                                <input type="number" id="editPages" name="pages" min="1" required>
                            </div>
                            <div class="form-group">
                                <label for="editPublisher">Publisher*</label>
                                <input type="text" id="editPublisher" name="publisher" required>
                            </div>
                        </div>

                        <div class="form-actions">
                            <button type="submit" class="btn btn-primary">Save Changes</button>
                            <button type="button" class="btn btn-secondary" onclick="closeModal()">Cancel</button>
                        </div>
                    </form>
                </div>
            </div>`;
        break;
        
        // ====================== ADD AUTHORS ====================== //
        case 'add-author':
            contentArea.innerHTML = `
                <section class="home-section" id="add-author-section">
                    <div class="add-book-container">
                        <h2 class="form-header">Add New Author</h2>
                    <form id="addAuthorForm" onsubmit="handleAuthorSubmit(event)">
                    <div class="form-row">
                        <div class="form-group">
                            <label for="firstName">First Name*</label>
                            <input type="text" id="firstName" name="firstName" required>
                            <div class="error-message" id="firstNameError">Please enter a valid first name</div>
                        </div>
                        <div class="form-group">
                            <label for="lastName">Last Name*</label>
                            <input type="text" id="lastName" name="lastName" required>
                            <div class="error-message" id="lastNameError">Please enter a valid last name</div>
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label for="nationality">Nationality*</label>
                            <input type="text" id="nationality" name="nationality" required>
                            <div class="error-message" id="nationalityError">Please enter nationality</div>
                        </div>
                        <div class="form-group">
                            <label for="dateOfBirth">Date of Birth*</label>
                            <input type="date" id="dateOfBirth" name="dateOfBirth" required>
                            <div class="error-message" id="dobError">Please enter a valid date</div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="authorDescription">Author Description</label>
                        <textarea id="authorDescription" name="authorDescription" rows="4" placeholder="Enter author's biography, achievements, and other relevant information..."></textarea>
                    </div>

                    <div class="form-group">
                        <label for="authorImage">Author Image</label>
                        <div class="file-upload">
                            <label for="authorImage" class="file-upload-label">
                                <i class='bx bx-upload'></i> Choose Author Image
                            </label>
                            <input type="file" id="authorImage" name="authorImage" accept="image/*">
                        </div>
                    </div>

                    <div class="btn-container">
                        <button type="button" class="btn btn-secondary" onclick="resetAuthorForm()">Clear Form</button>
                        <button type="submit" class="btn btn-primary">Add Author</button>
                    </div>
                    </form>
                </div>
            </section>`;
        break;
        // ====================== VIEW AUTHORS ====================== //
        case 'view-authors':
            contentArea.innerHTML = `
                <section class="home-section">
                    <div class="manage-authors-container">
                        <div class="controls-section">
                            <div class="search-container">
                                <input type="text" class="search-input" placeholder="Search by name, nationality...">
                                <button class="btn btn-edit" onclick="searchAuthors()">Search</button>
                            </div>
                        </div>

                        <table class="authors-table">
                            <thead>
                                <tr>
                                    <th>Author ID</th>
                                    <th>First Name</th>
                                    <th>Last Name</th>
                                    <th>Nationality</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody id="authorsTableBody">
                                <?php foreach($authors as $author): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($author['authorid']); ?></td>
                                        <td><?php echo htmlspecialchars($author['firstname']); ?></td>
                                        <td><?php echo htmlspecialchars($author['lastname']); ?></td>
                                        <td><?php echo htmlspecialchars($author['nationality']); ?></td>
                                        <td>
                                            <button class="btn btn-edit" onclick="editAuthor(<?php echo $author['authorid']; ?>)">Edit</button>
                                            <button class="btn btn-delete" onclick="deleteAuthor(<?php echo $author['authorid']; ?>)">Delete</button>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </section>

            <!-- EDIT AUTHOR -->
            <div id="editAuthorModal" class="modal">
            <div class="modal-content">
                <span class="close-modal" onclick="closeAuthorModal()">&times;</span>
                <h2>Edit Author Information</h2>
            <form id="editAuthorForm" onsubmit="updateAuthor(event)" enctype="multipart/form-data">
                    <input type="hidden" id="authorId" name="authorId">
                        
                <div class="form-row">
                    <div class="form-group">
                        <label for="firstName">First Name*</label>
                        <input type="text" id="firstName" name="firstName" required>
                    </div>
                    <div class="form-group">
                        <label for="lastName">Last Name*</label>
                        <input type="text" id="lastName" name="lastName" required>
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label for="nationality">Nationality*</label>
                        <input type="text" id="nationality" name="nationality" required>
                    </div>
                    <div class="form-group">
                        <label for="dateOfBirth">Date of Birth*</label>
                        <input type="date" id="dateOfBirth" name="dateOfBirth" required>
                    </div>
                </div>

                <div class="form-group">
                    <label for="authorDescription">Author Description</label>
                    <textarea id="authorDescription" name="authorDescription" rows="4" placeholder="Enter author's biography, achievements, and other relevant information..."></textarea>
                </div>

                <div class="form-group">
                    <label for="authorImage">Author Image</label>
                    <div class="file-upload">
                        <label for="authorImage" class="file-upload-label">
                            <i class='bx bx-upload'></i> Choose Author Image
                        </label>
                        <input type="file" id="authorImage" name="authorImage" accept="image/*">
                    </div>
                    <div id="currentImage"></div>
                </div>

                <div class="button-group">
                    <button type="submit" class="btn btn-primary">Update</button>
                    <button type="button" class="btn btn-secondary" onclick="closeAuthorModal()">Cancel</button>
                </div>
            </form>
                </div>
            </div>
        `;
        break;
        // ====================== VIEW USERS ====================== //                            
        case 'user':
            contentArea.innerHTML = `
                <section class="home-section">
                    <div class="manage-users-container">
                        <div class="controls-section">
                            <div class="search-container">
                                <input type="text" class="search-input" placeholder="Search by username or email...">
                                <button class="btn btn-edit" onclick="searchUsers()">Search</button>
                            </div>
                        </div>

                        <table class="users-table">
                            <thead>
                                <tr>
                                    <th>User ID</th>
                                    <th>Username</th>
                                    <th>Email</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody id="usersTableBody">
                                <?php foreach($users as $user): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($user['userid']); ?></td>
                                        <td><?php echo htmlspecialchars($user['username']); ?></td>
                                        <td><?php echo htmlspecialchars($user['email']); ?></td>
                                        <td><?php echo (isset($user['membership_status'])) ? htmlspecialchars($user['membership_status']) : 'Not a Member'; ?></td>
                                        <td>
                                            <button class="btn btn-edit" onclick="editUser(<?php echo $user['userid']; ?>)">Edit</button>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </section>

            <!-- Edit User Modal -->
            <div id="editModal" class="modal">
            </div>`;
        break;
        // ====================== VIEW LOANS ====================== //                            
        case 'loans':
            contentArea.innerHTML = `
                <section class="home-section">
                    <div class="manage-loans-container">
                        <div class="controls-section">
                            <div class="search-container">
                                <input type="text" class="search-input" placeholder="Search by loan, book or copy...">
                                <button class="btn btn-edit" onclick="searchLoans()">Search</button>
                            </div>
                        </div>
                        <table class="loans-table">
                            <thead>
                                <tr>
                                    <th>Loan ID</th>
                                    <th>Member ID</th>
                                    <th>Book ID</th>
                                    <th>Copy ID</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody id="loansTableBody">
                            <?php foreach($loans as $loan): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($loan['loanid']); ?></td>
                                        <td><?php echo htmlspecialchars($loan['memberid']); ?></td>
                                        <td><?php echo htmlspecialchars($loan['bookid']); ?></td>
                                        <td><?php echo htmlspecialchars($loan['copyid']); ?></td>
                                        <td style="color: 
                                                <?php 
                                                    if ($loan['status'] === 'Returned') {
                                                        echo '#1e7e34'; // Green
                                                    } elseif ($loan['status'] === 'Overdue') {
                                                        echo '#c81e1e'; // Red
                                                    } else {
                                                        echo '#000000'; // Default black
                                                    }
                                                    ?>;">
                                                    <?php echo htmlspecialchars($loan['status']); ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </section>`;
        break;
        // ====================== VIEW FINES ====================== //                                             
        case 'view-fines':
            contentArea.innerHTML = `
                <section class="home-section">
                    <div class="manage-fines-container">
                        <div class="controls-section">
                            <div class="search-container">
                                <input type="text" class="search-input" placeholder="Search by loan, fine or amount...">
                                <button class="btn btn-edit" onclick="searchFines()">Search</button>
                            </div>
                        </div>

                        <table class="fines-table">
                            <thead>
                                <tr>
                                    <th>Loan ID</th>
                                    <th>Fine ID</th>
                                    <th>Amount</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody id="finesTableBody">
                            <?php foreach($fines as $fine): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($fine['loanid']); ?></td>
                                        <td><?php echo htmlspecialchars($fine['fineid']); ?></td>
                                        <td>$<?php echo number_format(htmlspecialchars($fine['fineamount']), 2); ?></td>
                                        <td style="color: 
                                                <?php 
                                                    if ($fine['status'] === 'Paid') {
                                                        echo '#1e7e34'; // Green
                                                    } elseif ($fine['status'] === 'Unpaid') {
                                                        echo '#c81e1e'; // Red
                                                    } else {
                                                        echo '#000000'; // Default black
                                                    }
                                                    ?>;">
                                                <?php echo htmlspecialchars($fine['status']); ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </section>`;
        break;
        // ====================== ISSUE FINE ====================== //  
        case 'issue-fine':
            loadScript('/Admin Scripts/Fines.js'); 
        break;

        case 'case-views':
        break;
        
        default:
            contentArea.innerHTML = `<h2>Content Not Found</h2>`;
        }
    }

    </script>

    <script>
    function handleSubmit(event) {
        event.preventDefault();
        const formData = new FormData(event.target);
        console.log('Adding Book:', Object.fromEntries(formData));
    }
    </script>

    <script src="/Admin Scripts/UpdateUserStatus.js"></script>
    <script src="/Admin Scripts/Loans.js"></script>
    <script src="/Admin Scripts/Fines.js"></script>
    <script src="/Admin Scripts/Author.js"></script>
    <script src="/Admin Scripts/Sidebar.js"></script>
    <script src="/Admin Scripts/Books.js"></script>


    <script>
        function loadScript(filename) {
            const script = document.createElement('script');
            script.src = filename; 
            script.type = 'text/javascript';
            script.onload = function() {
                console.log(`${filename} loaded successfully`);
                if (filename === '/Admin Scripts/Fines.js') {
                    showIssueFineContent(); // Call function after script loads
                }
            };
            script.onerror = function() {
                console.error(`Failed to load script: ${filename}`);
            };
            document.head.appendChild(script); 
        }
    </script>


</body>
</html>
