<?php
session_start();
include "config.php";

// Redirect if user is not logged in
if (!isset($_SESSION['user'])) {
    echo '<script>window.location.href = "index.php";</script>';
    exit();
}

// Get user details from session
$user = $_SESSION['user'];
$pid = $user['pid'];

// Fetch all nodel officers
$sql = "SELECT id, bank_name, email_id, time_stamp FROM nodel_officer";
$result = mysqli_query($con, $sql);
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <title>BANK-NODEL</title>
    <link rel="icon" href="images/favicon.ico" sizes="32x32" type="image/x-icon">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Main CSS -->
    <link rel="stylesheet" type="text/css" href="css/main.css">
    <!-- Bootstrap icons -->
    <link rel="stylesheet" type="text/css"
        href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
    <!-- DataTables CSS -->
    <link rel="stylesheet" href="https://cdn.datatables.net/v/bs5/dt-1.13.4/datatables.min.css" />
</head>

<body class="app sidebar-mini">

    <!-- Loading Modal -->
    <div class="modal fade" id="pageLoadingModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static"
        data-bs-keyboard="false">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-body d-flex align-items-center justify-content-center">
                    <div class="m-loader me-3">
                        <svg class="m-circular" viewBox="50 50 100 100" width="100" height="100">
                            <circle class="path" cx="100" cy="100" r="40" fill="none" stroke-width="4"
                                stroke-miterlimit="10" />
                        </svg>
                    </div>
                    <h3 class="l-text mb-0">Please wait while loading...</h3>
                </div>
            </div>
        </div>
    </div>



    <?php include "header.php"; ?>

    <!-- Sidebar menu -->
    <div class="app-sidebar__overlay" data-toggle="sidebar"></div>
    <aside class="app-sidebar">
        <?php include "./common/name.php"; ?>
        <?php include 'sidebar.php'; ?>
    </aside>

    <main class="app-content">

        <div class="app-title">
            <div>
                <h1>BANK NODEL EMAIL</h1>
            </div>
            <ul class="app-breadcrumb breadcrumb side">
                <li class="breadcrumb-item"><i class="bi bi-house-door fs-6"></i></li>
                <li class="breadcrumb-item">Bank Nodel List</li>
            </ul>
        </div>

        <!-- Export buttons -->
        <div class="tile-title-w-btn d-flex justify-content-end">
            <p class="mb-10">
                <a href="./export/export_bank_nodel_pdf.php" class="btn btn-primary icon-btn" target="_blank">
                    <i class="bi bi-plus-square me-2"></i>Export to PDF
                </a>
            </p>
            <p class="mb-10">&nbsp;&nbsp;</p>
            <p class="mb-10">
                <a href="./export/export_bank_nodel_excel.php" class="btn btn-primary icon-btn">
                    <i class="bi bi-plus-square me-2"></i>Export to EXCEL
                </a>
            </p>
        </div>

        <!-- Table -->
        <div class="row">
            <div class="col-md-12">
                <div class="tile">
                    <div class="tile-body">
                        <div class="table-responsive">
                            <table class="table table-hover table-bordered" id="sampleTable">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Bank Name</th>
                                        <th>Email</th>
                                        <th>Copy</th>
                                    </tr>
                                    <tr>
                                        <th>આઈડી</th>
                                        <th>બઁકનું નામ</th>
                                        <th>ઈમેલ</th>
                                        <td>Copy</td>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $sr = 1;
                                    while ($row = mysqli_fetch_assoc($result)) { ?>
                                        <tr>
                                            <td><?= $sr++; ?></td>
                                            <td><?= htmlspecialchars($row['bank_name']); ?></td>
                                            <td>
                                                <?php
                                                $emails_display = str_replace(";", ";<br>", $row['email_id']);
                                                echo $emails_display;
                                                ?>
                                            </td>
                                            <td>
                                                <?php
                                                $email = trim($row['email_id']);
                                                $isEmpty = empty($email) || strtolower($email) === 'null';
                                                ?>
                                                <button
                                                    class="btn btn-sm <?= $isEmpty ? 'btn-danger' : 'btn-primary copy-email-btn'; ?>"
                                                    <?= $isEmpty ? 'disabled' : 'data-email="' . htmlspecialchars($email) . '"'; ?>>
                                                    Copy Email
                                                </button>
                                            </td>
                                        </tr>
                                    <?php } ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Copy Email Modal -->
        <div class="modal fade" id="copyEmailModal" tabindex="-1" aria-labelledby="copyEmailLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Copied Email(s)</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <table class="table table-bordered" id="emailModalTable">
                            <thead>
                                <tr>
                                    <th>Email</th>
                                </tr>
                            </thead>
                            <tbody></tbody>
                        </table>
                        <div id="copyNote" style="color:red; font-weight:bold; text-align:center; margin-top:10px;">
                            Copied Successfully
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </main>

    <!-- JS Scripts -->
    <script src="js/jquery-3.7.0.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/main.js"></script>
    <script type="text/javascript" src="js/plugins/jquery.dataTables.min.js"></script>
    <script type="text/javascript" src="js/plugins/dataTables.bootstrap.min.js"></script>

    <script>
        $(document).ready(function () {

            // ======= Loading Modal =======
            var loadingModalEl = document.getElementById('pageLoadingModal');
            var loadingModal = new bootstrap.Modal(loadingModalEl, {
                backdrop: true,
                keyboard: false
            });
            loadingModal.show();

            setTimeout(function () {
                loadingModal.hide();
            }, 2000);

            loadingModalEl.addEventListener('hidden.bs.modal', function () {
                $('.modal-backdrop').remove(); // ensure backdrop is removed
            });

            // ======= DataTable =======
            //        var table = $("#sampleTable").DataTable();
            var table = $("#sampleTable").DataTable({
                "pageLength": 10, // show 10 rows per page
                "lengthMenu": [10, 25, 50, 100, 200, 300, 500, 700, 1000], // options for rows per page
                "ordering": true, // enable sorting
                "searching": true, // enable search
                "paging": true, // enable pagination
                "info": true // show info text
            });

            // ======= Copy Email =======
            var copyModal = new bootstrap.Modal(document.getElementById('copyEmailModal'));

            $(document).on('click', '.copy-email-btn', function (e) {
                e.preventDefault();
                var email = $(this).data('email');

                if (navigator.clipboard && window.isSecureContext) {
                    navigator.clipboard.writeText(email).then(function () {
                        showEmailModal(email);
                    }).catch(function () {
                        fallbackCopyTextToClipboard(email);
                    });
                } else {
                    fallbackCopyTextToClipboard(email);
                }
            });

            function fallbackCopyTextToClipboard(text) {
                var textArea = document.createElement("textarea");
                textArea.value = text;
                textArea.style.position = "fixed";
                textArea.style.top = "-1000px";
                textArea.style.left = "-1000px";
                document.body.appendChild(textArea);
                textArea.focus();
                textArea.select();

                try {
                    document.execCommand('copy');
                    showEmailModal(textArea.value);
                } catch (err) {
                    showEmailModal("Copy failed. Please copy manually.");
                }

                document.body.removeChild(textArea);
            }

            function showEmailModal(emails) {
                $('#emailModalTable tbody').empty();
                var emailArray = emails.split(';');

                emailArray.forEach(function (email) {
                    email = email.trim();
                    if (email) {
                        $('#emailModalTable tbody').append(`<tr><td>${email}</td></tr>`);
                    }
                });

                copyModal.show();

                setTimeout(function () {
                    copyModal.hide();
                }, 2500);
            }

        });
    </script>

</body>

</html>