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

// Redirect if user is not logged in
if (!isset($_SESSION['user'])) {
    header("Location: index.php");
    exit();
}

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

//echo "Welcome " . htmlspecialchars($user['name'] ?? 'User') . "<br>";
//echo "Email: " . htmlspecialchars($user['email'] ?? '') . "<br>";
//echo "Phone: " . htmlspecialchars($user['phone'] ?? '') . "<br>";

// Fetch all users

//$ATFQuery = "SELECT * FROM `cyber_police`";
$ATFQuery = "SELECT * FROM `cyber_police` WHERE `pid` = '$policestation_id'";

$resultATF = mysqli_query($con, $ATFQuery);


$noticeQuery = "SELECT * FROM `notice`";
$resultNotice = mysqli_query($con, $noticeQuery);


$policeStationQuery = "SELECT * FROM `policestation` WHERE id='{$user['pid']}'";
$resultPoliceStation = mysqli_query($con, $policeStationQuery);

$policeQuery = "SELECT * FROM `police` WHERE pid = '{$user['pid']}'";
$resultPolice = mysqli_query($con, $policeQuery);

//$policeQuery = "SELECT * FROM `policestation` WHERE id='{$user['pid']}'";
//$resultPolice = mysqli_query($con, $policeQuery);

$subjectQuery = "SELECT * FROM `subject` WHERE `s_name` LIKE '%Provide Information related to Accounts to prepare a court order. %'";
$resultSubject = mysqli_query($con, $subjectQuery);

$noticeQuery = "SELECT * FROM `notice` WHERE `n_name` = 'NOTICE UNDER SECTION 94 OF B.N.S.S 2023 - UNDER SECTION 63 OF BSA ACT 2023'";
$resultNotice = mysqli_query($con, $noticeQuery);


$bankQuery = "SELECT * FROM `bank`";
$resultBank = mysqli_query($con, $bankQuery);

?>

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

        <form method="POST" action="lien_kyc.php">
            <div class="text-end mb-3">
                <button type="submit" class="btn btn-success">Submit FORM</button>
            </div>

            <div class="row">
                <div class="col-md-6">
                    <div class="tile">
                        <div class="tile-body">


                            <div class="mb-3">
                                <label class="form-label">Select Acknowledgement / FIR No.</label>
                                <select class="form-control" name="atf" id="atf_id" required>
                                    <option value="">-- Select Acknowledgement No / FIR No --</option>
                                    <?php
                                    while ($row = mysqli_fetch_assoc($resultATF)) {
                                        $displayText = htmlspecialchars($row['acknowlegement']) . ' - ' . htmlspecialchars($row['complain_name']);
                                        echo '<option value="' . $row['id'] . '">' . $displayText . '</option>';
                                    }
                                    ?>
                                </select>

                            </div>

                            <div class="mb-3" style="display:none;">
                                <label class="form-label">Select Police Station</label>
                                <select class="form-control" name="policestation_id" id="policestation_id" required>
                                    <?php while ($row = mysqli_fetch_assoc($resultPoliceStation)) { ?>
                                        <option value="<?php echo $row['id']; ?>">
                                            <?php echo htmlspecialchars($row['p_name']); ?>
                                        </option>
                                    <?php } ?>
                                </select>
                            </div>



                            <div class="mb-3">
                                <label class="form-label">Select Investigation Officer</label>
                                <select class="form-control" name="police_id" id="police_id" required>
                                    <option value="">-- Select Investigation Officer --</option>
                                    <?php
                                    while ($row = mysqli_fetch_assoc($resultPolice)) {
                                        echo '<option value="' . $row['id'] . '">' . htmlspecialchars($row['i_name']) . '</option>';
                                    }
                                    ?>
                                </select>
                            </div>

                            <div class="mb-3" style="display:none;">
                                <label class="form-label">Select Subject</label>
                                <select class="form-control" name="subject_id" required>
                                    <?php while ($row = mysqli_fetch_assoc($resultSubject)) { ?>
                                        <option value="<?php echo $row['id']; ?>">
                                            <?php echo htmlspecialchars($row['s_name']); ?>
                                        </option>
                                    <?php } ?>
                                </select>
                            </div>

                            <div class="mb-3" style="display:none;">
                                <label class="form-label">Select Notice</label>
                                <select class="form-control" name="notice_id" required>
                                    <?php while ($row = mysqli_fetch_assoc($resultNotice)) { ?>
                                        <option value="<?php echo $row['id']; ?>">
                                            <?php echo htmlspecialchars($row['n_name']); ?>
                                        </option>
                                    <?php } ?>
                                </select>
                            </div>

                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="tile">
                        <div class="tile-body">

                            <!-- BANK FIELDS -->
                            <div id="bank-form">
                                <div class="mb-3">
                                    <label class="form-label">Select Bank</label>
                                    <select class="form-control" id="bank_id" name="bank_id">
                                        <option value=""></option> <!-- Empty option for placeholder -->
                                        <?php while ($row = mysqli_fetch_assoc($resultBank)) { ?>
                                            <option value="<?php echo $row['id']; ?>"
                                                data-name="<?php echo htmlspecialchars($row['b_name']); ?>">
                                                <?php echo htmlspecialchars($row['b_name']); ?>
                                            </option>
                                        <?php } ?>
                                    </select>
                                </div>



                                <div class="mb-3">
                                    <label class="form-label">Account Number</label>
                                    <input class="form-control" type="text" id="account_number"
                                        placeholder="Enter Account Number">
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">IFSC Code</label>
                                    <input class="form-control" type="text" id="ifsc_code"
                                        placeholder="Enter IFSC Code">
                                </div>



                                <div class="mb-3">
                                    <label class="form-label">Transaction Id</label>
                                    <input class="form-control" type="text" id="txn_id"
                                        placeholder="Enter Transaction Id">
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">HOLD AMOUNT</label>
                                    <input class="form-control" type="number" id="account_hold_amount"
                                        placeholder="Enter Hold Amount">
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">Account Holder Name</label>
                                    <input class="form-control" type="text" id="account_holder"
                                        placeholder="Enter Account Holder Name">
                                </div>

                            </div>

                            <div class="text-end mb-3">
                                <button type="button" class="btn btn-primary btn-sm" onclick="addBank()">Add Bank
                                    Data</button>
                            </div>

                            <!-- Display added bank accounts -->


                        </div>
                    </div>
                </div>


            </div>


            <div class="row">
                <div class="col-md-12">
                    <div class="tile">
                        <div class="tile-body">
                            <h5 class="mt-3">Added Bank Accounts:</h5>


                            <table class="table" id="bank-table">
                                <thead>
                                    <tr>
                                        <th>Bank Name</th>
                                        <th>Account Number</th>
                                        <th>IFSC Code</th>
                                        <th>Account Holder Name</th>
                                        <th>Transaction ID</th>
                                        <th>Hold Amount</th>
                                        <th>Delete</th>
                                    </tr>
                                </thead>
                                <tbody></tbody>
                            </table>

                            <!-- Hidden input to store final JSON (optional for form submission) -->
                            <input type="hidden" name="bank_accounts_json" id="bank_accounts_json">


                        </div>
                    </div>
                </div>

            </div>

        </form>



    </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>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script type="text/javascript">
        $('#sampleTable').DataTable();
    </script>
    <!-- Google analytics script-->


    <script>
        $(document).ready(function () {
            $('#bank_id').select2({
                placeholder: "-- Select Bank --",
                allowClear: true,
                width: '100%',
                // Dropdown height limit
                dropdownCssClass: "custom-dropdown"
            });
        });
    </script>
    <script>
        $(document).ready(function () {
            $('#atf_id').select2({
                placeholder: "-- Select Acknowledgement No / FIR No --",
                allowClear: true
            });
        });
    </script>

    <script>
        $(document).ready(function () {
            $('.selectpicker').selectpicker();
        });
    </script>


    <script>
        let bankAccounts = [];

        function addBank() {
            const bankSelect = document.getElementById('bank_id');
            const bankId = bankSelect.value;
            const bankName = bankSelect.options[bankSelect.selectedIndex].getAttribute('data-name');
            const accountNumber = document.getElementById('account_number').value.replace(/\s+/g, '').trim();
            const accountHolder = document.getElementById('account_holder').value.replace(/\s+/g, '').trim();
            const holdAmount = document.getElementById('account_hold_amount').value.replace(/\s+/g, '').trim();
            const ifscCode = document.getElementById('ifsc_code').value.replace(/\s+/g, '').trim();
            const txnId = document.getElementById('txn_id').value.replace(/\s+/g, '').trim();

            if (!bankId || !accountNumber || !holdAmount) {
                alert("Please fill all fields.");
                return;
            }

            const isDuplicate = bankAccounts.some(account =>
                account.bank_id === bankId && account.account_number === accountNumber
            );

            if (isDuplicate) {
                alert("This bank account has already been added.");
                return;
            }

            const bankData = {
                bank_id: bankId,
                bank_name: bankName,
                account_number: accountNumber,
                ifsc_code: ifscCode,
                account_holder: accountHolder,
                transaction_id: txnId,
                account_hold_amount: holdAmount
            };

            bankAccounts.push(bankData);

            // Update hidden field for submission
            document.getElementById('bank_accounts_json').value = JSON.stringify(bankAccounts);


            // Add row to table
            const tableBody = document.querySelector('#bank-table tbody');
            const newRow = document.createElement('tr');

            newRow.innerHTML = `
    <td>${bankName}</td>
    <td>${accountNumber}</td>
    <td>${ifscCode}</td>
    <td>${accountHolder}</td>
    <td>${txnId}</td>
        <td>${holdAmount}</td>
    <td><button class="btn btn-danger btn-sm" onclick="deleteBank(this, '${bankId}', '${accountNumber}')">Delete</button></td>
`;

            tableBody.appendChild(newRow);

            // Reset form

            // ✅ Clear the form fields after adding data
            document.getElementById("bank_id").value = "";
            document.getElementById("account_hold_amount").value = "";
            document.getElementById("account_number").value = "";
            document.getElementById("ifsc_code").value = "";
            document.getElementById("account_holder").value = "";
            document.getElementById("txn_id").value = "";
            document.getElementById('bank-form').reset();
        }

        function deleteBank(button, bankId, accountNumber) {
            // Remove row from DOM
            const row = button.closest('tr');
            row.remove();

            // Remove from array
            bankAccounts = bankAccounts.filter(account => {
                return !(account.bank_id === bankId && account.account_number === accountNumber);
            });

            // Update hidden JSON field
            document.getElementById('bank_accounts_json').value = JSON.stringify(bankAccounts);
        }
    </script>

    <script>
        document.getElementById('policestation_id').addEventListener('change', function () {
            var stationId = this.value;
            var policeDropdown = document.getElementById('police_id');
            policeDropdown.innerHTML = '<option value="">Loading...</option>';

            fetch('get_police_by_station.php?station_id=' + stationId)
                .then(response => response.json())
                .then(data => {
                    console.log('Fetched Police Data:', data); // 👈 This prints data to the console
                    policeDropdown.innerHTML = '<option value="">-- Select Police --</option>';
                    data.forEach(function (police) {
                        var option = document.createElement('option');
                        option.value = police.id;
                        option.text = police.i_name;
                        policeDropdown.appendChild(option);
                    });
                })
                .catch(error => console.error('Error fetching police data:', error));
        });
    </script>

    <script>
        function updateLabel() {
            const selectedValue = document.querySelector('input[name="reference_type"]:checked').value;
            const label = document.getElementById("referenceLabel");
            const input = document.querySelector('input[name="reference_number"]');

            if (selectedValue === "0") {
                label.innerText = "Acknowledgement Number";
                input.placeholder = "Enter Acknowledgement Number";
            } else if (selectedValue === "1") {
                label.innerText = "Ticket No.";
                input.placeholder = "Enter Ticket No.";
            } else if (selectedValue === "2") {
                label.innerText = "FIR No.";
                input.placeholder = "Enter FIR No.";
            }
        }
    </script>


</body>

</html>