<?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

$complyQuery = "
    SELECT k.*, c.acknowlegement, c.complain_name, c.mobile
    FROM comply_order k
    LEFT JOIN cyber_police c ON k.c_id = c.id  
    WHERE c.pid = '$pid'
    ORDER BY k.id DESC";

//$complyQuery = " SELECT * FROM `comply_order` ORDER BY `id` DESC";

$resultComply = mysqli_query($con, $complyQuery);


?>

<!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-COMPLY ORDER</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>Comply Order</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="comply_order.php">Comply Order</a></li>
            </ul>
        </div>

        <div class="tile-title-w-btn d-flex justify-content-end">
            <p class="mb-10">
                <a href="./export/comply_order_report_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/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_comply_order.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>View</th>
                                        <th class="d-none">Status</th>
                                        <th>Remarks</th>
                                    </tr>
                                    <tr>
                                        <th>આઈ.ડી.</th>
                                        <th>એકનૉલેજમેન્ટ /<br>એફ.આઈ.આર. નંબર</th>
                                        <th>બેંક વિગતો</th>
                                        <th>જુઓ</th>
                                        <th class="d-none">સ્થિતિ</th>
                                        <th>ટિપ્પણી</th>
                                    </tr>

                                </thead>
                                <tbody>
                                    <?php if (mysqli_num_rows($resultComply) > 0): ?>
                                    <?php $serial = 1; ?>
                                    <?php while($row = mysqli_fetch_assoc($resultComply)): ?>
                                    <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 cbd.*, b.b_name, b.timestamp
    FROM c_bank_data cbd
    LEFT JOIN bank b ON cbd.bank_id = b.id
    WHERE cbd.comply_order_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>Holder</th>
            <th>Release Amount</th>
            <th>Remarks</th>
          </tr></thead>';
    echo '<tbody>';
    while($BankRow = mysqli_fetch_assoc($BankQuery)){
        echo '<tr>';
        echo '<td>' . htmlspecialchars($BankRow['b_name']) . '</td>';
        echo '<td>' . htmlspecialchars($BankRow['account_number']) . '</td>';
        echo '<td>' . htmlspecialchars($BankRow['ifsc_code']) . '</td>';
        echo '<td>' . htmlspecialchars($BankRow['account_holder']) . '</td>';
        echo '<td>' . htmlspecialchars($BankRow['release_amount']) . '</td>';
        echo '<td>' . htmlspecialchars($BankRow['remarks']) . '</td>';
        echo '</tr>';
    }
    echo '</tbody></table>';
} else {
    echo "No bank accounts";
}
?>
                                        </td>
                                        <td>
                                            <form action="view_comply_order.php" method="POST" style="display:inline;">
                                                <input type="hidden" name="id"
                                                    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 class="d-none">
                                            <form action="update_status_comply_order.php" method="POST">
                                                <input type="hidden" name="id" value="<?= $row['id'] ?>">
                                                <select name="status" class="form-control"
                                                    onchange="this.form.submit()">
                                                    <option value="Pending"
                                                        <?= ($row['status'] == 'Pending') ? 'selected' : '' ?>>Pending
                                                    </option>
                                                    <option value="KYC Done"
                                                        <?= ($row['status'] == 'KYC Done') ? 'selected' : '' ?>>KYC Done
                                                    </option>
                                                </select>
                                            </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>

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

    </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 openStatusModal(comply_order_id) {
        console.log("🟦 Opening status modal for comply_order_id ID:", comply_order_id);

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

        $.ajax({
            url: 'fetch_bank_accounts_comply_order.php',
            type: 'POST',
            data: {
                comply_order_id: comply_order_id
            },
            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.release_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_comply_order.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>