<!DOCTYPE html>
<html lang="en" data-bs-theme="dark">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ဘဏ်အသစ်ထည့်ရန်</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha2/dist/css/bootstrap.min.css">
<script src="https://kit.fontawesome.com/ae360af17e.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="css/style.css">
<link rel="icon" href="image/logo.png" type="image/png">
</head>

<script>
        function formatNumber(input) {
            // Remove all non-digit characters
            let value = input.value.replace(/\D/g, '');
            
            // Format the number with commas
            let formattedValue = new Intl.NumberFormat().format(value);
            
            // Update the input value
            input.value = formattedValue;
        }

        document.addEventListener('DOMContentLoaded', function () {
            const formattedInput = document.getElementById('formatted');
            formattedInput.addEventListener('input', function () {
                formatNumber(this);
            });
        });
    </script>


<?php
session_start();
                                
if (isset($_SESSION['browser_id'])) {
    $browserId = $_SESSION['browser_id'];
} else {
    // Generate a new browser ID
    $browserId = generateUniqueBrowserId();

    // Store the browser ID in the session for future use
    $_SESSION['browser_id'] = $browserId;
}

include "database/database.php";
include "database/data.php";
include "login_check.php";
include "cal_banking.php";





if (isset($_POST['add'])) {


      // Perform a database query to check if the browser ID exists in the user_database table
        $bank_type = $_POST['bank_type'];
        $currency = $_POST['currency'];

        #point_1
        $sql = "SELECT * FROM ".$banking." where type='$bank_type'";
        $result = $connection->query($sql);
        if ($result && $result->num_rows > 0) {
          while ($row = $result->fetch_assoc()) {
            echo '<script>alert("Bank name already exist") ;</script>';
        }
      } else { 

        $b_id = $browserId;
    
        $sql = "SELECT * FROM ".$user_database." WHERE browser_id='$b_id'";
        $result = $connection->query($sql);
        if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
        $user_name = $row['user_name']; 

        $sql = "INSERT INTO ".$banking."(type,currency, cash_in, sell,customer_pay, pay_after,pay_now,expense,remain,user)
                    VALUES ('$bank_type','$currency','0','0','0','0','0','0','0','$user_name')";
                    if (mysqli_query($connection, $sql)) {
                        header('location:banking.php');
                        echo '<script>alert("Refill Product Success") ;</script>';
                        // echo "Insert successful";
                    } else {
                        echo "Error: " . $sql . " " . mysqli_error($connection);
                    }


        }
    }
            

        
      }

        }
    


if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $id = isset($_POST['id']) ? $_POST['id'] : null;
    $action = isset($_POST['action']) ? $_POST['action'] : null;

    switch ($action) {
        case 'info':
            

            break;


        case 'delete':
       
                    

                    $query = "DELETE FROM `$banking` WHERE id = '$id'";
                    if ($connection->query($query)) {
                        
                    } else {
                       
                    }

                
             
         
            break;

        default:
            
    }
} else {
}


?>

<script>
    function refreshPage() {
        location.reload();
    }
</script>


<body>
<div class="wrapper">
    <?php 
    include "sidebar.php";
    ?>

    <div class="main">
        <nav class="navbar navbar-expand px-3 border-bottom">
            <button class="btn" id="sidebar-toggle" type="button">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="navbar-collapse navbar">
                <ul class="navbar-nav">
                <div class="mb-3" style="margin-right:30px">
                <h4 style="font-size:25px">ဘဏ်အသစ်ဖွင့်ရန်</h4>
                </div>

                    <li class="nav-item dropdown">
                        <a href="#" data-bs-toggle="dropdown" class="nav-icon pe-md-0">
                            <img src="image/logo.png" class="avatar img-fluid rounded" alt="">
                        </a>
                        <?php include "logo_profile.php";?>
                    </li>
                </ul>
            </div>
        </nav>

        <main class="content px-3 py-2">
            <div class="container-fluid">


                <div class="row">

                    <div class="col-sm-4" style="background-color:#19242e;border-radius:20px;color:orange;margin-bottom:20px">

                    <form action="banking.php" method="POST" style="margin-top:20px;margin-left:20px" enctype="multipart/form-data">
                    
                    <table style="border:none;">

                        <tr style="height: 50px;">
                            <th> <label for="pwd" alt="hi"> ဘဏ်အမည်:</label></th>
                            <th><input type="text" class="form-control"  name="bank_type" placeholder=""  autofocus ></th>
                        </tr>

                        <tr style="height: 50px;">
                            <th> <label for="pwd">ငွေအမျိုးစား:</label></th>
                            <th>
                                <select name="currency" id="typeInput" class="form-control">
                                <option value="kyat">kyat</option>
                                <option value="baht">baht</option>
                                <option value="yuan">yuan</option>
                                <option value="dollar">dollar</option>
                                </select>
                            </th>
                        </tr>

                     



                    </table>

                    <div style="margin-top: 20px; display: flex; justify-content: center;" class="container-fluid">

                    <table class="table table-borderless">

                        <tr>
                        <td colspan="3"> <button type="submit" name="add" class="btn btn-outline-warning" style="margin: 10px;width:90%" data-toggle="modal" >အကောင့်ဖွင့်ရန်</button></td>
                        </tr>

                        <tr>
                        <td colspan="3"> <button type="submit" name="refresh" class="btn btn-outline-success" style="margin: 10px;width:90%" data-toggle="modal" data-target="#infoModal" onclick="refreshPage()">Refresh</button></td>
                        </tr>

                        

                    </table>
                        <!-- <button type="submit" name="add" class="btn btn-outline-warning" style="margin: 10px;">Print</button>-->
                        <!-- <button type="button" class="btn btn-outline-danger" style="margin: 10px;" data-toggle="modal" data-target="#infoModal">ပုံပြောင်းရန်</button> -->
                    </div>

                    </form>


                    </div>
                
                <!-- Table Element -->
                <div class="col-sm-8">

                <div class="card-header gx-5">
                    <form class="d-flex flex-row-reverse ">
                    <div class="col-auto" style="margin-left:10px">
                        <input type="text" class="form-control" id="searchInput" placeholder="Search">
                    </div>
                    <div class="col-auto">
                        <button type="submit" class="btn btn-primary mb-3"><i class="fa-solid fa-magnifying-glass"></i></button>
                    </div>
                    </form> 
                    </div>

                    <div class="scrollable-table" style="height:60vh;">
                        <table class="table table-bordered table-hover" style="color:white;font-size:18px;"  id="dataTable">
                        <thead style="background-color:#19242e" class="text-center align-middle">
                        <tr>
                        <th scope="col">အမှတ်စဉ်</th>
                        <th scope="col">ဘဏ်အမည်</th>
                        <th scope="col">ငွေအမျိုးစား</th>
                        <th scope="col">ငွေသွင်း</th>
                        <th scope="col">ရောင်းရငွေ</th>
                        <th scope="col">အသုံးစရိတ်</th>
                        <th scope="col">ပစ္စည်းဖိုးငွေချေ</th>
                        <th scope="col">လက်ကျန်ငွေ</th>
                        <th scope="col">ဖျက်ရန်</th>
                        </tr>
                        </thead>
                            <tbody>


                                <?php 
                                
                                $b_id = $browserId;
                            
                                $sql = "SELECT * FROM ".$user_database." WHERE browser_id='$b_id'";
                                $result = $connection->query($sql);
                                if ($result && $result->num_rows > 0) {
                                  while ($row = $result->fetch_assoc()) {
                             
                                    $seller = $row['user_name_lk'];    

                                    $sql = "Select * from ".$banking."";
                                    $result = mysqli_query($connection, $sql);
                                    if ($result) {
                                        while ($row = mysqli_fetch_assoc($result)) {
                                            echo '<tr>
                                            <td>' . $row['id'] . '</td>
                                            <th scope="row">' . $row['type']. '</th>
                                            <td>' . $row['currency'] . '</td>
                                            <td>' . number_format($row['cash_in']). '</td>
                                            <td>' . number_format($row['sell']) . '</td>
                                            <td>' . number_format($row['expense']) . '</td>
                                            <td>' . number_format($row['pay_now'] + $row['pay_after'] ) . '</td>
                                            <td>' . number_format($row['remain']) . '</td>                                                                                        
                                            <td><button type="submit" class="btn btn-danger" data-action="delete">Delete</button></td>                                                       
                                            </tr>';

                                    }
                                }
                            }
                            
                            // $query = "SELECT sum(cash_in) as total_cash_in,
                            // sum(sell) as total_sell,
                            // sum(pay_after) as total_pay_after, 
                            // sum(pay_now) as total_pay_now,
                            // sum(expense) as total_expense,
                            // sum(remain) as total_remain
                            // FROM `$banking`";
                            // $result = $connection->query($query);
                            // if ($result->num_rows > 0) {
                            //     $row = $result->fetch_assoc();
                            //     echo'
                            //     <tr>
                            //     <td colspan=3 style="text-align:center;">Total</td>
                            //     <td><b>'.number_format($row["total_cash_in"]).'</br></td>
                            //     <td><b>'.number_format($row["total_sell"]).'</br></td>
                            //     <td><b>'.number_format($row["total_expense"]).'</br></td>
                            //     <td><b>'.number_format($row["total_pay_now"]) + $row["total_pay_after"].'</br></td>
                            //     <td><b>'.number_format($row["total_remain"]).'</br></td>
                            //     </tr>
                            //     ';
                            // }
                        }

                  
                                    mysqli_free_result($result);
                                
                                ?>
                            </tbody>
                        </table>

                            <form id="actionForm" method="POST" action="banking.php" style="display:none;">
                                <input type="hidden" name="id" id="formId">
                                <input type="hidden" name="action" id="formAction">
                            </form>

                            <!-- Button on Table -->
                            <script>
                            document.addEventListener('DOMContentLoaded', function() {
                                document.getElementById('dataTable').addEventListener('click', function(event) {
                                    if (event.target.tagName === 'BUTTON') {
                                        const action = event.target.getAttribute('data-action');
                                        const row = event.target.closest('tr');
                                        const id = row.cells[0].innerText;

                                        // Create a FormData object and append the necessary data
                                        const formData = new FormData();
                                        formData.append('id', id);
                                        formData.append('action', action);

                                        // Send the form data using Fetch API
                                        fetch('banking.php', {
                                            method: 'POST',
                                            body: formData
                                        })
                                        .then(response => response.text())
                                        .then(data => {
                                            if (action === 'delete') {
                                                // Refresh the page if the delete action is performed
                                                location.reload();
                                            } else {
                                                // Insert the returned HTML into a container element
                                                const modalContainer = document.createElement('div');
                                                modalContainer.innerHTML = data;
                                                document.body.appendChild(modalContainer);

                                                // Display the modal
                                                const modal = new bootstrap.Modal(modalContainer.querySelector('.modal'));
                                                modal.show();

                                                // Add event listener to refresh the page when the modal is hidden
                                                modalContainer.querySelector('.modal').addEventListener('hidden.bs.modal', function () {
                                                    location.reload();
                                                });
                                            }
                                        })
                                        .catch(error => {
                                            console.error('Error:', error);
                                        });
                                    }
                                });
                            });
                            </script>

          
                        <!-- Search for js code -->
                        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

                    </div>
                </div>


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


        <a href="#" class="theme-toggle">
            <i class="fa-regular fa-moon"></i>
            <i class="fa-regular fa-sun"></i>
        </a>
        <footer class="footer">
            <div class="container-fluid">
                <div class="row text-muted">
                    <div class="col-6 text-start">
                        <p class="mb-0">
                            <a href="#" class="text-muted">
                                <?php 
                                    include "version.php";
                                ?>
                            </a>
                        </p>
                    </div>
                    <div class="col-6 text-end">
                        <ul class="list-inline">
                            <li class="list-inline-item">
                                <a href="#" class="text-muted">Contact</a>
                            </li>
                            <li class="list-inline-item">
                                <a href="#" class="text-muted">About Us</a>
                            </li>
                            <li class="list-inline-item">
                                <a href="#" class="text-muted">Terms</a>
                            </li>
                            <li class="list-inline-item">
                                <a href="#" class="text-muted">Booking</a>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </footer>
    </div>
</div>

<!-- Number Format -->
<script>
    function formatNumber() {
        const inputField = document.getElementById('package_price');
        let value = inputField.value;

        // Remove any non-numeric characters (except for decimal points)
        value = value.replace(/[^0-9.]/g, '');

        // Format the number
        const formattedValue = new Intl.NumberFormat().format(value);

        // Set the formatted value back to the input field
        inputField.value = formattedValue;
    }
</script>




<?php



echo json_encode($response);

function generateUniqueBrowserId()
{
    $randomString = bin2hex(random_bytes(16));
    $timestamp = time();

    return $randomString . $timestamp;
}
?>





    


 
<script src="js/script.js"></script>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.4/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>

</html>
