<!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>Account အသစ်ဖွင့်ရန်</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_expense.php";



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


    $sql = "SELECT * FROM ".$user_database." WHERE browser_id='$b_id'";
    $result = mysqli_query($connection, $sql);
    if ($result) {
        while ($row = mysqli_fetch_assoc($result)) {
        $account_data = $_POST['account'];

            $sql = "INSERT INTO ".$account."(account, amount) VALUES ('$account_data','0')";
            if (mysqli_query($connection, $sql)) {
                header('location:expense_account.php');
                echo '<script>alert("Add Expense Success") ;</script>';

            } 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 `$account` 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">Account အသစ်ဖွင့်ရန်</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="expense_account.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"> Account:</label></th>
                            <th><input type="text" class="form-control"  name="account" placeholder=""></th>
                        </tr>

                                     
                        </tr>



                    </table>

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

                    <table class="table table-borderless">

                        <tr>
                        <td scope="col" colspan="3"> <button type="submit" name="add" class="btn btn-outline-warning" style="margin: 10px;width:90%" data-toggle="modal" >ပေါင်းထည့်ရန်</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">Account</th>
                            <th scope="col">Amount (MMK)</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 ".$account."";
                                    $result = mysqli_query($connection, $sql);
                                    if ($result) {
                                        while ($row = mysqli_fetch_assoc($result)) {
                                            echo '<tr>
                                            <td>' . $row["id"] . '</td>   
                                            <td>' . $row["account"] . '</td>
                                            <td>' . $row["amount"]. '</td>                                                                      
                                            <td><button type="submit" class="btn btn-danger" data-action="delete">Delete</button></td>                                                       
                                            </tr>';

                                    }
                                }
                            }
                            $query = "SELECT    
                            sum(amount) as total_amount
                            FROM `$account`";

                            $result = $connection->query($query);
                            if ($result->num_rows > 0) {
                                $row = $result->fetch_assoc();
                                echo'
                                <tr>
                                <td colspan=2 style="text-align:center;">Total</td>
                                <td colspan=2><b>'.$row["total_amount"].'</br></td>
                                </tr>
                                ';
                            }
                        }

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

                            <form id="actionForm" method="POST" action="expense_account.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('expense_account.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>


<!-- <script src="sell_lat_kar.js"></script> -->
<!-- get data auto from input barcode/banking -->
<script>
document.addEventListener('DOMContentLoaded', (event) => {
    const barcodeInput = document.getElementById('barcodeInput');
    const bankingInput = document.getElementById('bankingInput');
    const outputDiv = document.getElementById('output');

    barcodeInput.addEventListener('input', handleBarcodeInput);

    let barcode = '';
    let timeout;

    function handleBarcodeInput(event) {
        clearTimeout(timeout);

        barcode += event.data || event.target.value; 

        event.target.value = '';

        timeout = setTimeout(() => {
            processBarcode(barcode);
            barcode = '';
        }, 100); 
    }

    async function processBarcode(barcode) {
        const bankingData = bankingInput.value;

        outputDiv.innerHTML = `Processed Barcode: ${barcode} <br> Banking Data: ${bankingData}`;
        console.log(`Processed Barcode: ${barcode}`);
        console.log(`Banking Data: ${bankingData}`);

        try {
            const response = await fetch('expense_account.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ 
                    barcode: barcode,
                    bankingData: bankingData
                })
            });

            location.reload();
            const textResponse = await response.text();
            console.log('Raw server response:', textResponse);

            try {
                const responseData = JSON.parse(textResponse);
                console.log('Parsed server response:', responseData);

                if (responseData.status !== 'success') {
                    console.error('Server error:', responseData.message);
                    
                }
            } catch (jsonError) {
                console.error('Error parsing JSON response:', jsonError);
            }
        } catch (error) {
            console.error('Error sending data:', error);
        }
    }
});

</script>
<div id="output"></div>


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