<!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>
<style>
    
video {
width: 100%;
height: 200px;

object-fit: cover;
/* Ensures the video fills the container */
display: block;
}

.image-container {
    width: 100px;
    height: 100px;
    border: 1px solid #ccc;
    border-radius: 50%;
    overflow: hidden;

    display: flex;               /* 👈 key */
    justify-content: center;     /* horizontal center */
    align-items: center;         /* vertical center */

    margin: 0 auto;              /* center container itself */
}

.image-container img {
    width: 100%;
    height: 100%;
    object-fit: contain;
}
</style>



<?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 "cal_pro_remain.php";
include "login_check.php";

$sql = "SELECT * FROM " . $rate . "";
$result = mysqli_query($connection, $sql);
if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
        $baht = $row['baht'];
        $yuan = $row['yuan'];
        $dollar = $row['dollar'];

            }
}


if (isset($_POST['delete'])) {
$product_name = $_POST['product_name'];

//Delete Photo
$extensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
// Loop through the extensions to find the existing file
$fileToDelete = '';
foreach ($extensions as $ext) {
$potentialFile = 'uploads/' . $product_name . '.' . $ext;
if (file_exists($potentialFile)) {
$fileToDelete = $potentialFile;
break;
}
}

// Check if a matching file was found
if ($fileToDelete) {
// Attempt to delete the file
if (unlink($fileToDelete)) {
// echo "File deleted successfully: $fileToDelete";
} else {
// echo "Error: Unable to delete the file.";
}
} else {
// echo "Error: File does not exist with any of the expected extensions.";
}

//Update Data



$query = "DELETE FROM " . $product . " WHERE product_name = '$product_name'";
if ($connection->query($query)) {
// echo 'Deleted successfully.';
} else {
// echo 'alert("Update failed!");';
}

}





?>

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


<body>
<div class="wrapper">
<?php
include "sidebar.php";
include "database/database.php";
include "database/data.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">

        <!-- Table Element -->
    <div class="container-fluid">

        <div class="container-fluid" style="margin-bottom: 20px;">

   

       

                <div class="row" style="margin-top:10px;text-align:center">


        
                 

                    <!-- <div class="col " style="margin:5px">
                        <button type="submit" class="btn btn-success mb-3" name="refresh">Refresh</button>
                    </div>

                    <div class="col" style="margin:5px">
                        <button type="button" class="btn btn-success mb-3" onclick="window.location.href='product_view.php';">Table</button>
                    </div>

                    <div class="col" style="margin:5px">
                        <button type="button" class="btn btn-success mb-3" onclick="window.location.href='product_view_photo.php';">Photo</button>
                    </div> -->

                </div>

                <div class="col" style="margin-left:10px;">
      <form class="d-flex flex-row-reverse" method="GET">
            <div class="col-auto" style="margin-left:10px">
                <input type="text" class="form-control" id="searchInput" name="search" value="<?= isset($_GET['search']) ? htmlspecialchars($_GET['search']) : '' ?>" 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>



        <div class="container-fluid">
            <?php
            $sql_rate = "SELECT * FROM ".$rate." LIMIT 1"; // Add LIMIT 1 to ensure only one row is fetched
            $result = $connection->query($sql_rate);
            
            if ($result && $result->num_rows > 0) {
                $row_rate = $result->fetch_assoc();
                $baht = $row_rate['baht']; 
                $yuan = $row_rate['yuan']; 
                $profit_percent = $row_rate['profit']; 
            } else {
                // Handle case where no rows are returned
                $baht = null;
                $yuan = null;
            }

       

            // Calculate pagination
            // $limit = 100; // Rows per page
            // $page = isset($_GET['page']) ? (int)$_GET['page'] : 1; // Current page
            // $start = ($page - 1) * $limit; // Start index

            // // Get total rows
            // $totalQuery = "SELECT COUNT(*) as total FROM $product";
            // $totalResult = mysqli_query($connection, $totalQuery);
            // $totalRow = mysqli_fetch_assoc($totalResult);
            // $totalRecords = $totalRow['total'];
            // $totalPages = ceil($totalRecords / $limit);

            // // Fetch rows for the current page
            // $sql = "SELECT * FROM $product ORDER BY id DESC LIMIT $start, $limit";
            // $result = mysqli_query($connection, $sql);
$limit = 100;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $limit;

$search = isset($_GET['search']) ? mysqli_real_escape_string($connection, $_GET['search']) : '';

// Total Records
$totalQuery = "SELECT COUNT(*) as total FROM $product WHERE delete_d='0'";
if (!empty($search)) {
    $totalQuery .= " AND (product_name LIKE '%$search%' 
                    OR type LIKE '%$search%' 
                    OR barcode LIKE '%$search%' 
                    OR barcode_1 LIKE '%$search%' 
                    OR barcode_2 LIKE '%$search%')";
}

$totalResult = mysqli_query($connection, $totalQuery);

// ✅ Add error checking
if (!$totalResult) {
    die("Query failed: " . mysqli_error($connection));
}

$totalRow = mysqli_fetch_assoc($totalResult);
$totalRecords = $totalRow ? (int)$totalRow['total'] : 0;
$totalPages = ($totalRecords > 0) ? ceil($totalRecords / $limit) : 1;

// Fetch Data with Search and Pagination
$sql = "SELECT * FROM $product WHERE delete_d='0'";
if (!empty($search)) {
    $sql .= " AND (product_name LIKE '%$search%' 
                OR type LIKE '%$search%' 
                OR barcode LIKE '%$search%' 
                OR barcode_1 LIKE '%$search%' 
                OR barcode_2 LIKE '%$search%')";
}
$sql .= " ORDER BY pieces_remain ASC LIMIT $start, $limit";

$result = mysqli_query($connection, $sql);

// ✅ Optional check for data fetch errors
if (!$result) {
    die("Data query failed: " . mysqli_error($connection));
}

            ?>

            <div class="card-view mt-4">

                                    <nav>
            <ul class="pagination justify-content-center mt-3 custom-pagination">
                <?php if ($page > 1): ?>
                    <li class="page-item">
                        <a class="page-link" href="?page=<?= $page - 1 ?>&search=<?= urlencode($search) ?>">Previous</a>
                    </li>
                <?php endif; ?>

                <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                    <li class="page-item <?= ($i == $page) ? 'active' : '' ?>">
                        <a class="page-link" href="?page=<?= $i ?>&search=<?= urlencode($search) ?>"><?= $i ?></a>
                    </li>
                <?php endfor; ?>

                <?php if ($page < $totalPages): ?>
                    <li class="page-item">
                        <a class="page-link" href="?page=<?= $page + 1 ?>&search=<?= urlencode($search) ?>">Next</a>
                    </li>
                <?php endif; ?>
            </ul>
        </nav>

    

                <div id="cardContainer" class="row">
                    <?php if ($result): ?>
                        <?php while ($row = mysqli_fetch_assoc($result)): ?>
                            <div class="col-md-3 mb-3 card-item">
                                <div class="card bg-dark text-white">
                                    


                                    <div class="card-body">

                                        <div style="justify-content: center;">
                                            <div class="image-container">
<?php
$extensions = ['jpg', 'jpeg', 'png', 'gif'];
$imagePath = '';

foreach ($extensions as $ext) {
    $potentialPath = 'uploads/' . $row["product_name"] . '.' . $ext;
    if (file_exists($potentialPath)) {
        $imagePath = $potentialPath;
        break;
    }
}

if ($imagePath) {
    echo '<img src="' . $imagePath . '" alt="Product Image">';
} else {
     echo '<img src="uploads/logo.png" alt="Product Image">';
}
?>
</div>

                                        </div>

                                        <?php 
 $product_name = $row['product_name'];
                            $type = $row['type'];
                            $buy = $row['buy'];
                            $currency_buy = $row['currency_buy'];
                            $unit = $row['unit'];
                            $pieces = $row['pieces'];

                            $trans = $row['trans'];
                            $package_price = $row['package_price'];
                            $unit_price = $row['unit_price'];
                            $pieces_price = $row['pieces_price'];

                            $unit = is_numeric($unit) ? (float)$unit : 0;
                            $pieces = is_numeric($pieces) ? (float)$pieces : 0;

                            if (!function_exists('forkyat')) {
                                function forkyat($number)
                                {
                                    return ceil($number / 100) * 100;
                                }
                            }

                            $product_name_data = $row['product_name'];
                            $barcode_data = $row['barcode'];
                            $barcode_1_data = $row['barcode_1'];
                            $barcode_2_data = $row['barcode_2'];
                            $type_data = $row['type'];
                            $rate_data = $row['rate'];
                            $currency_buy_data = $row['currency_buy'];
                            $trans_data = $row['trans'];
                            $buy_data = $row['buy'];
                            $unit_data = $row['unit'];
                            $pieces_data = $row['pieces'];

                            $package_price_data = $row['package_price'];
                            $unit_price_data = $row['unit_price'];
                            $pieces_price_data = $row['pieces_price'];

                            $package_exist_data = $row['package_exist'];
                            $unit_exist_data = $row['unit_exist'];
                            $pieces_exist_data = $row['pieces_exist'];

                            $profit_percent = 0; // default value in case no category found
                            $sql_cat = "SELECT sell FROM $catagories WHERE type='$type' LIMIT 1";
                            $result_cat = mysqli_query($connection, $sql_cat);

                            if ($result_cat) {
                                $cat = mysqli_fetch_assoc($result_cat);
                                if ($cat) {
                                    $profit_percent = $cat['sell'];
                                }
                            }
                            include "cal_sell_price_ll.php";
                            ?>

                       
                                        <h6 class="card-text" style="margin-top:20px"><strong>ပစ္စည်းအမည်:</strong> <?= htmlspecialchars($product_name) ?></h6>
                                        <h6 class="card-text" style="margin-top:20px"><strong>ဗူး/ခု :</strong> <?= htmlspecialchars($barcode_data) ?></h6>
                                        <h6 class="card-text" style="margin-top:20px"><strong>ကဒ် :</strong> <?= htmlspecialchars($barcode_1_data) ?></h6>
                                        <h6 class="card-text" style="margin-top:20px"><strong>ဖာ :</strong> <?= htmlspecialchars($barcode_2_data) ?></h6>
                                        <h6 class="card-text" style="margin-top:20px"><strong>အမျိုးစား:</strong> <?= htmlspecialchars($type_data) ?></h6>
                                        <h6 class="card-text" style="margin-top:20px"><strong>အမြတ်ရာခိုင်နှုန်း:</strong> <?= htmlspecialchars($profit_percent." %") ?></h6>
                                        <h6 class="card-text" style="margin-top:20px"><strong>ကားခ:</strong> <?= htmlspecialchars($trans_data) ?> ks</h6>                   
                                        <h6 class="card-text" style="margin-top:20px"><strong>ဝယ်ဈေး:</strong> <?= htmlspecialchars($buy_data) ?> <?php echo $currency_buy_data ?></h6>                   
                                        <h6 class="card-text" style="margin-top:20px"><strong>ဖာအတွင်းရှိ (ကဒ်):</strong> <?= htmlspecialchars($unit_data) ?></h6>                   
                                        <h6 class="card-text" style="margin-top:20px"><strong>ကဒ်အတွင်းရှိ (ဗူး):</strong> <?= htmlspecialchars($pieces_data) ?></h6>  <br>                 
                                    
                                        <?php
                                       ?>

                                <table class="table table-bordered"> 
                                
                                <tr>
                                <td colspan="3" style="text-align:center"><?= ($product_name) ?></td>
                                </tr>

                                <tr>
                                <td colspan="3" style="text-align:center">ရောင်းဈေး</td>
                                </tr>

                                <tr>
                                <td style="text-align:center">ဖာ</td>
                                <td style="text-align:center">ကဒ်/ထုပ်</td>
                                <td style="text-align:center">ဗူး/ခု</td>
                                </tr>

                                <tr>
                                    <td style="text-align:right;color:white"><?= ($kyat_package_price) ?> Ks</td>
                                    <td style="text-align:right;color:white"><?= ($kyat_unit_price) ?> Ks</td>
                                    <td style="text-align:right;color:white"><?= ($kyat_pieces_price) ?> Ks</td>
                                </tr>

                                <tr>
                                    <td style="text-align:right;color:white"><?= ($yuan_package_price) ?> ¥</td>
                                    <td style="text-align:right;color:white"><?= ($yuan_unit_price) ?> ¥</td>
                                    <td style="text-align:right;color:white"><?= ($yuan_pieces_price) ?> ¥</td>

                                </tr>
                                   
                                <tr>
                                    <td style="text-align:right;color:white"><?= ($baht_package_price) ?> ฿</td>
                                    <td style="text-align:right;color:white"><?= ($baht_unit_price) ?> ฿</td>
                                    <td style="text-align:right;color:white"><?= ($baht_pieces_price) ?> ฿</td>
                                </tr>
                                
                                
                                </table>



             <?php
                                              echo '
                                              <table class="table table-bordered"> 
                                              <tr>
                                              <td colspan="3" style="text-align:center">PF</td>
                                              </tr>
     
                                              <tr>
                                              <td style="text-align:center">ဖာ</td>
                                              <td style="text-align:center">ကဒ်/ထုပ်</td>
                                              <td style="text-align:center">ဗူး/ခု</td>
                                              </tr>
     
                                              <tr>
                                              <td style="text-align:center;color:white">' . ($package_price_data) . '</td>
                                              <td style="text-align:center;color:white">' . ($unit_price_data) . '</td>
                                              <td style="text-align:center;color:white">' . ($pieces_price_data) . '</td>
                                              </tr>
                                              </table>
                                              ';
                                             
     
                             
                                                 if (!function_exists('forkyat')) {
                                                     function forkyat($number)
                                                     {
                                                         return ceil($number / 100) * 100;
                                                     }
                                                 }
                                             
     
                                                echo '
                                                 <table class="table table-bordered"> 
                                                 <tr>
                                                 <td colspan="3" style="text-align:center">လက်ကျန်</td>
                                                 </tr>
     
                                                 <tr>
                                                 <td style="text-align:center">ဖာ</td>
                                                 <td style="text-align:center">ကဒ်/ထုပ်</td>
                                                 <td style="text-align:center">ဗူး/ခု</td>
                                                 </tr>
     
                                                 <tr>
                                                 <td style="text-align:center; color:' . ($package_exist_data < 5 ? "red" : "white") . ';">
                                                 ' . $package_exist_data . '
                                                 </td>
                                                 <td style="text-align:center; color:' . ($unit_exist_data < 5 ? "red" : "white") . ';">
                                                 ' . $unit_exist_data . '
                                                 </td>
                                                 <td style="text-align:center; color:' . ($pieces_exist_data < 5 ? "red" : "white") . ';">
                                                 ' . $pieces_exist_data . '
                                                 </td>
                                                 </tr>
     
                                                 </table>
                                                 ';

                                            echo '
                                            <table class="table"> 


                                            <tr>
                                            <td>
                                            <form action="product_photo_view.php" method="POST"  target="_blank" style="width:100%">
                                                    <input type="hidden" name="product_name" value="' . htmlspecialchars($product_name_data) . '">
                                                    <input type="hidden" name="action" value="info">
                                                    <button type="submit" class="btn btn-outline-success" name="info_button" style="width:100%">ပြင်ရန်</button>
                                                </form> 
                                            </td>

                                            <td>
    <form action="product_view_photo.php" method="POST" style="margin-left:10px;width:100%" onsubmit="return confirmDelete();">
       <input type="hidden" name="product_name" value="' . htmlspecialchars($product_name_data) . '">

        <input type="hidden" name="action" value="info">
        <button type="submit" class="btn btn-outline-danger" name="delete" style="width:100%">ဖျက်ရန်</button>
    </form> 
</td>

                                            </tr>

                                             <tr>
                                            <td>
                                            <form action="product_add_new_refill.php" method="POST" style="width:100%"  target="_blank">
                                                    <input type="hidden" name="product_name" value="' . htmlspecialchars($product_name_data) . '">
                                                    <input type="hidden" name="action" value="info">
                                                    <button type="submit" class="btn btn-outline-primary" name="info_button" style="width:100%">ဖြည့်ရန်</button>
                                                </form> 
                                            </td>

                                             <td colspan=2>
                                            <form action="print_barcode.php" method="POST"  target="_blank" style="margin-left:10px;width:100%">
                                                    <input type="hidden" name="product_name" value="' . htmlspecialchars($product_name_data) . '">
                                                    <input type="hidden" name="action" value="info">
                                                    <button type="submit" class="btn btn-outline-warning" name="delete" style="width:100%">Print</button>
                                                </form> 
                                            </td>

                                            </tr>

                                            <tr>
                                         

                                            </tr>


                                            </table>
                                            ';

                                        ?>
<script>
function confirmDelete() {
    return confirm('ဖျက်ရန်သေချာပါသလား?'); // "Are you sure you want to delete?"
}
</script>




                                            </div>
                                        </div>
                                    </div>
                                <?php endwhile; ?>
                            <?php endif; ?>
                        </div>
                    </div>


                  
                </div>


            </div>


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

<script> 
                        $(document).ready(function() {
                            $("#searchInput").on("keyup", function() {
                                var value = $(this).val().toLowerCase();
                                
                                $("#dataTable tbody tr").filter(function() {
                                    $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
                                });
                            });
                        });
                        </script>

<script>
    // Call filterTable immediately after the page loads
    window.onload = function() {
        filterTable(); // Automatically filters based on the first option selected
    };
</script>


<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

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>