<?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'];

//echo "Welcome " . htmlspecialchars($user['name'] ?? 'User') . "<br>";
//echo "Email: " . htmlspecialchars($user['email'] ?? '') . "<br>";
//echo "Phone: " . htmlspecialchars($user['phone'] ?? '') . "<br>";
$pid = $user['pid'];
// Fetch all users
$kycQuery = "SELECT k.*, c.acknowlegement, c.complain_name, c.mobile FROM kyc k LEFT JOIN cyber_police c ON k.c_id = c.id
    WHERE c.pid = '$pid' AND k.type = 'LIEN AMOUNT'
    ORDER BY k.id DESC
";
$resultKyc = mysqli_query($con, $kycQuery);



?>

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

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

    <title>BANK-LIEN AMOUNT</title>

    <!-- Main CSS -->
    <link rel="stylesheet" type="text/css" href="css/main.css">

    <!-- Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
</head>

<body class="app sidebar-mini">
    <!-- Navbar-->

    <!-- Navbar-->
    <?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>Lien Amount</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</li>
                <li class="breadcrumb-item active"><a href="lien_amount.php">Lien Amount</a></li>
            </ul>
        </div>

        <div class="tile-title-w-btn d-flex justify-content-end">
            <p class="mb-10">
                <a href="./export/lien_report.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/lien_report_excel.php" class="btn btn-primary icon-btn">
                    <i class="bi bi-plus-square me-2"></i>Export to EXCEL
                </a>
            </p>
            <p class="mb-10"> &nbsp;&nbsp;</p>

            <p class="mb-10">
                <a href="add_lien_amount.php" class="btn btn-primary icon-btn">
                    <i class="bi bi-plus-square me-2"></i>Add
                </a>
            </p>
        </div>



        <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>Acknowledgement /<br>FIR No</th>
                                        <th>Bank Details</th>
                                        <th>Update</th>
                                        <th>View</th>
                                        <th>Remarks</th>
                                    </tr>
                                    <tr>
                                        <th>આઈ.ડી.</th>
                                        <th>એકનૉલેજમેન્ટ /<br>એફ.આઈ.આર. નંબર</th>
                                        <th>બેંક વિગતો</th>
                                        <th>Update</th>
                                        <th>જુઓ</th>
                                        <th>ટિપ્પણી</th>
                                    </tr>

                                </thead>
                                <tbody>
                                    <?php if (mysqli_num_rows($resultKyc) > 0): ?>
                                        <?php $serial = 1; ?>
                                        <?php while ($row = mysqli_fetch_assoc($resultKyc)): ?>
                                            <tr>
                                                <td><?= $serial++; ?></td>
                                                <td>
                                                    <?php
                                                    if (!empty($row['acknowlegement'])) {
                                                        echo htmlspecialchars($row['acknowlegement']) . '<br>';
                                                        echo htmlspecialchars($row['complain_name']) . '<br>';
                                                        echo htmlspecialchars($row['mobile']);
                                                    } else {
                                                        echo '-';
                                                    }
                                                    ?>
                                                </td>

                                                <td>
                                                    <?php
                                                    $id = $row['id']; // KYC ID
                                            
                                                    // Fetch all bank accounts for this KYC
                                                    $BankQuery = mysqli_query($con, "SELECT * FROM bank_accounts WHERE kyc_id = '$id'");

                                                    if (mysqli_num_rows($BankQuery) > 0) {
                                                        echo '<table class="table table-sm table-bordered mb-10">';
                                                        echo '<thead><tr>
            <th>Bank</th>
            <th>Account No</th>
            <th>IFSC</th>
            <th>Hold Amount</th>
            <th>Remarks</th>
          </tr></thead>';
                                                        echo '<tbody>';
                                                        while ($BankRow = mysqli_fetch_assoc($BankQuery)) {
                                                            echo '<tr>';
                                                            echo '<td>' . htmlspecialchars($BankRow['bank_name']) . '</td>';
                                                            echo '<td>' . htmlspecialchars($BankRow['account_number']) . '</td>';
                                                            echo '<td>' . htmlspecialchars($BankRow['ifsc_code']) . '</td>';
                                                            echo '<td>' . htmlspecialchars($BankRow['hold_amount']) . '</td>';
                                                            echo '<td>' . htmlspecialchars($BankRow['remarks']) . '</td>';
                                                            echo '</tr>';
                                                        }
                                                        echo '</tbody></table>';
                                                    } else {
                                                        echo "No bank accounts";
                                                    }
                                                    ?>
                                                </td>


                                                <td>
                                                    <!-- Hidden POST form -->
                                                    <form action="update_lien_amount.php" method="POST" style="display:inline;">
                                                        <input type="hidden" name="kycid"
                                                            value="<?= htmlspecialchars($row['id']) ?>">
                                                        <input type="hidden" name="print" value="true">
                                                        <button type="submit" class="btn btn-primary btn-sm">Update</button>
                                                    </form>
                                                </td>

                                                <td>
                                                    <form action="view_lien_amount.php" method="POST" style="display:inline;"
                                                        target="_blank" rel="noopener">
                                                        <input type="hidden" name="kycid"
                                                            value="<?= htmlspecialchars($row['id']) ?>">
                                                        <input type="hidden" name="print" value="true">
                                                        <button type="submit" class="btn btn-primary btn-sm">View</button>
                                                    </form>
                                                </td>


                                                <td>
                                                    <button type="button" class="btn btn-sm btn-warning"
                                                        onclick="openStatusModal(<?= $row['id'] ?>)">
                                                        Update Status
                                                    </button>
                                                </td>


                                            </tr>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                    <?php endif; ?>

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

            <!-- Status Update Modal -->
            <div class="modal fade" id="statusModal" tabindex="-1" aria-hidden="true">
                <div class="modal-dialog modal-xl">
                    <div class="modal-content">
                        <div class="modal-header bg-primary text-white">
                            <h5 class="modal-title">Update Bank Status</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body">
                            <table class="table table-bordered" id="bankDetailsTable">
                                <thead>
                                    <tr>
                                        <th>Bank Name</th>
                                        <th>Account No</th>
                                        <th>IFSC</th>
                                        <th>Holder</th>
                                        <th>Hold Amount</th>
                                        <th>Status (Yes/No)</th>
                                    </tr>
                                </thead>
                                <tbody></tbody>
                            </table>
                        </div>
                        <div class="modal-footer">
                            <button type="button" id="saveBankStatusBtn" class="btn btn-success">Save</button>
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        </div>
                    </div>
                </div>
            </div>



        </div>
    </main>
    <!-- Essential javascripts for application to work-->
    <script src="js/jquery-3.7.0.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/main.js"></script>
    <!-- Page specific javascripts-->
    <link rel="stylesheet" href="https://cdn.datatables.net/v/bs5/dt-1.13.4/datatables.min.css" />
    <!-- Data table plugin-->
    <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 type="text/javascript">
        $('#sampleTable').DataTable();
    </script>
    <!-- Google analytics script-->

    <script>
        function openUpdateModal(id, pid, name, email, password) {
            document.getElementById('updateId').value = id;
            document.getElementById('updatePid').value = pid;
            document.getElementById('updateName').value = name;
            document.getElementById('updateEmail').value = email;
            //document.getElementById('updatePassword').value = "";

            var modal = new bootstrap.Modal(document.getElementById('updateModal'));
            modal.show();
        }


        function openDeleteModal(id, name, email, password) {
            document.getElementById('deleteId').value = id;
            document.getElementById('deleteUserName').textContent = name;

            var modal = new bootstrap.Modal(document.getElementById('deleteModal'));
            modal.show();
        }
    </script>

    <script>
        function openStatusModal(kycId) {
            console.log("🟦 Opening status modal for KYC ID:", kycId);

            $('#statusModal').modal('show');
            $('#bankDetailsTable tbody').html('<tr><td colspan="6">Loading...</td></tr>');

            $.ajax({
                url: 'fetch_bank_accounts.php',
                type: 'POST',
                data: {
                    kyc_id: kycId
                },
                dataType: 'json',

                success: function (response) {
                    console.log("✅ Fetched Bank Data:", response);

                    $('#bankDetailsTable tbody').empty();

                    if (Array.isArray(response) && response.length > 0) {
                        response.forEach(function (bank) {
                            const currentStatus = bank.remarks ? bank.remarks.toUpperCase() : 'NONE';

                            $('#bankDetailsTable tbody').append(`
                        <tr data-id="${bank.id}">
                            <td>${bank.bank_name}</td>
                            <td>${bank.account_number}</td>
                            <td>${bank.ifsc_code}</td>
                            <td>${bank.account_holder}</td>
                            <td>${bank.hold_amount}</td>
                            <td>
                                <select class="form-select form-select-sm bank-status">
                                    <option value="NONE" ${currentStatus === 'NONE' ? 'selected' : ''}>None</option>
                                    <option value="YES" ${currentStatus === 'YES' ? 'selected' : ''}>YES</option>
                                    <option value="NO" ${currentStatus === 'NO' ? 'selected' : ''}>NO</option>
                                </select>
                            </td>
                        </tr>
                    `);
                        });
                    } else {
                        $('#bankDetailsTable tbody').html(
                            '<tr><td colspan="6">No bank accounts found.</td></tr>');
                        console.warn("⚠️ No data found for KYC ID:", kycId);
                    }

                    // Save button click handler
                    $('#saveBankStatusBtn').off('click').on('click', function () {
                        let updates = [];

                        $('#bankDetailsTable tbody tr').each(function () {
                            updates.push({
                                id: $(this).data('id'),
                                status: $(this).find('.bank-status').val()
                            });
                        });

                        console.log("🟨 Sending updates:", updates);

                        $.ajax({
                            url: 'update_bank_status.php',
                            type: 'POST',
                            data: {
                                updates: JSON.stringify(updates)
                            },
                            success: function (res) {
                                console.log("✅ Update Response:", res);
                                alert('Status updated successfully!');
                                $('#statusModal').modal('hide');

                                // Refresh the page after update
                                location.reload();

                            },
                            error: function (xhr, status, error) {
                                console.error("❌ Error updating status:", error);
                                console.log("Response Text:", xhr.responseText);
                                alert('Error updating status!');
                            }
                        });
                    });
                },

                error: function (xhr, status, error) {
                    console.error("❌ AJAX Error while fetching bank data:", error);
                    console.log("Response Text:", xhr.responseText);
                    $('#bankDetailsTable tbody').html(
                        '<tr><td colspan="6" class="text-danger">Error loading data!</td></tr>');
                }
            });
        }
    </script>




</body>

</html>