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



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


      // Perform a database query to check if the browser ID exists in the user_database table
      $sql = "SELECT * FROM ".$user_database." WHERE browser_id='$b_id'";
      $result = mysqli_query($connection, $sql);
      if ($result) {
            while ($row = mysqli_fetch_assoc($result)) {
            $account = $_POST['account'];
            $voucher = $_POST['voucher'];
            $product_name = $_POST['product_name'];
            $amount = $_POST['amount'];
            $banking_data = $_POST['banking'];
            $price = $_POST['price'];
            $date = $_POST['date'];
            $note = $_POST['note'];
            $total = $amount * $price;
            $user = $row['user_name'];

            $sql = "SELECT * FROM ".$banking." WHERE type='$banking_data'";
            $result = mysqli_query($connection, $sql);
            if ($result) {
                    while ($row = mysqli_fetch_assoc($result)) {
                    $remain = $row['remain'];
                    if ($remain > $total){ 
                        $sql = "INSERT INTO ".$expense."(account, voucher, product_name, amount,price,total,user,banking,note,date)
                        VALUES ('$account','$voucher','$product_name','$amount','$price','$total','$user','$banking_data','$note','$date')";
                        if (mysqli_query($connection, $sql)) {
                            header('location:expense_daily.php');
                            echo '<script>alert("Add Expense Success") ;</script>';
                            // echo "Insert successful";
                        } else {
                            echo "Error: " . $sql . " " . mysqli_error($connection);
                        }
                    } else{ 
                        echo "
                        <script>
                        alert('".$banking_data." is not enough!')
                        </script>";
                        header('location:expense_daily.php');
                       
                        
                    }
       
                    }
                }

        }
      }

        }
    


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 `$expense` 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="expense_daily.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">Account:</label></th>
                            <th>
                                <select name="account"  class="form-control">
                                    <?php
                                    // $sql = "SELECT * FROM ".$account."";
                                    // $result = $connection->query($sql);
                                    // if ($result && $result->num_rows > 0) {
                                    //     while ($row = $result->fetch_assoc()){
                                    //         $account = $row['account']; // Database
                                    //         echo '
                                    //         <option value="' . $account . '">' . $account . '</option>
                                    //         ';
                                    //     }
                                    // }
                                    ?>
                                </select>
                            </th>
                        </tr> -->

                        <tr style="height: 50px;">
                            <th> <label for="pwd">Account:</label></th>
                            <th>
                                <select name="account" class="form-control">
                                    <?php
                                    $sql = "SELECT * FROM ".$account."";
                                    $result = $connection->query($sql);
                                    if ($result && $result->num_rows > 0) {
                                        while ($row = $result->fetch_assoc()){
                                            $name = $row['account']; // Database
                                            echo '
                                            <option value="' . $name . '">' . $name . '</option>
                                            ';
                                        }
                                    }
                                    ?>
                                </select>
                            </th>
                        </tr>

                        <tr style="height: 50px;">
                            <th> <label for="pwd">banking:</label></th>
                            <th>
                                <select name="banking" class="form-control">
                                    <?php
                                    $sql = "SELECT * FROM ".$banking."";
                                    $result = $connection->query($sql);
                                    if ($result && $result->num_rows > 0) {
                                        while ($row = $result->fetch_assoc()){
                                            $name = $row['type']; // Database
                                            echo '
                                            <option value="' . $name . '">' . $name . '</option>
                                            ';
                                        }
                                    }
                                    ?>
                                </select>
                            </th>
                        </tr>

                        <tr style="height: 50px;">
                            <th> <label for="pwd" alt="hi"> Voucher:</label></th>
                            <th><input type="text" class="form-control"  name="voucher" placeholder=""></th>
                        </tr>

                        <tr style="height: 50px;">
                            <th> <label for="pwd" alt="hi"> ပစ္စည်းအမည်:</label></th>
                            <th><input type="text" class="form-control"  name="product_name" placeholder=""></th>
                        </tr>

                        <tr style="height: 50px;">
                            <th> <label for="pwd" alt="hi"> အရေအတွက်:</label></th>
                            <th><input type="text" class="form-control"  name="amount" placeholder=""></th>
                        </tr>

                        <tr style="height: 50px;">
                            <th> <label for="pwd" alt="hi"> တစ်ခုလိုက်ဈေးနှုန်း:</label></th>
                            <th><input type="text" class="form-control"  name="price" placeholder=""></th>
                        </tr>

                        <tr style="height: 50px;">
                            <th> <label for="pwd" alt="hi"> မှတ်စု:</label></th>
                            <th><input type="text" class="form-control"  name="note" placeholder=""></th>
                        </tr>

                        <?php
                        $today = date("Y-m-d");

                        echo '<tr style="height: 50px;">
                            <th> <label for="pwd" alt="hi"> ရက်စွဲ:</label></th>
                            <th><input type="text" class="form-control"  name="date" value='.$today.'></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">Voucher</th>
                            <th scope="col">Product Name</th>
                            <th scope="col">Amount</th>
                            <th scope="col">Price</th>
                            <th scope="col">Total</th>
                            <th scope="col">စာရင်းသွင်းသူ</th>
                            <th scope="col">ငွေချေသည့်ဘဏ်</th>
                            <th scope="col">မှတ်စု</th>
                            <th scope="col">Date</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 ".$expense."";
                                    $result = mysqli_query($connection, $sql);
                                    if ($result) {
                                        while ($row = mysqli_fetch_assoc($result)) {
                                            echo '<tr>
                                            <td>' . $row["id"] . '</td>
                                            <th scope="row">' . $row["account"]. '</th>
                                            <td>' . $row["voucher"] . '</td>
                                            <td>' . $row["product_name"] . '</td>
                                            <td>' . $row["amount"] . '</td>
                                            <td>' . $row["price"] . '</td>
                                            <td>' . $row["total"] . '</td>
                                            <td>' . $row["user"] . '</td>
                                            <td>' . $row["banking"] . '</td>
                                            <td>' . $row["note"] . '</td>
                                            <td>' . $row["date"] . '</td>                                                                                       
                                            <td><button type="submit" class="btn btn-danger" data-action="delete">Delete</button></td>                                                       
                                            </tr>';

                                    }
                                }
                            }
                            $query = "SELECT    
                            sum(total) as total_expense
                            FROM `$expense`";

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

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

                            <form id="actionForm" method="POST" action="expense_daily.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_daily.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_daily.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





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>
