<?php
include("../db/cn.php");
/*session_start();*/

if(isset($_SESSION['user_name']) && isset($_SESSION['user_role']) && isset($_SESSION['outlet_name']) && isset($_SESSION['outlet_address'])) {
    $userName = $_SESSION['user_name'];
    $userRole = $_SESSION['user_role'];
    $outlet_address = $_SESSION['outlet_address'];
    $outlet_name = $_SESSION['outlet_name'];
}

// Check if order ID is provided
if (!isset($_GET["order_id"])) {
    exit("Order ID is missing.");
}

$order_id = mysqli_real_escape_string($connection, $_GET["order_id"]);
$products_query = mysqli_query($connection, "SELECT * FROM log_user_sales WHERE order_id = '$order_id'");



if ($_POST) {
    // Extract order details from the HTML form inputs
    $totalAmount = mysqli_real_escape_string($connection, $_POST['total_input']);
    $discounted = mysqli_real_escape_string($connection, $_POST['discounted']);
    $discountAmount = mysqli_real_escape_string($connection, $_POST['result']);
    $discountPercentage = mysqli_real_escape_string($connection, $_POST['discount_percentage']);
    $cashAmount = mysqli_real_escape_string($connection, $_POST['cash_amount']);
    $changeAmount = mysqli_real_escape_string($connection, $_POST['change_amount']);
    $taxAmount = mysqli_real_escape_string($connection, $_POST['tax_amount']);
    $customerName = mysqli_real_escape_string($connection, $_POST['customer_name']);
    $customerPhone = mysqli_real_escape_string($connection, $_POST['customer_phone']);
    $paidBy = mysqli_real_escape_string($connection, $_POST['paid_by']);

    // Construct the INSERT query
    $insertQuery = "INSERT INTO `m_order` (product_id, supplier_name, company, company_category, product_name, product_price, product_quantity, product_total, tax_amount, total_amount, paid_by, customer_name, customer_phone, discount_amount, discounted, discount_per, cash_amount, change_amount, order_id, outlet_name, login_user, user_role, outlet_address, date_time) VALUES ";

    // Additional details (assuming these are constants or fetched from somewhere else)
    $dateTime = date("Y-m-d");

    // Extract product details from the table rows
    $productData = array();
    if (isset($_POST['product']) && is_array($_POST['product'])) {
        foreach ($_POST['product'] as $row) {
            $productId = mysqli_real_escape_string($connection, $row['product_id']);
            $supplierName = mysqli_real_escape_string($connection, $row['supplier_name']);
            $company = mysqli_real_escape_string($connection, $row['company']);
            $companyCategory = mysqli_real_escape_string($connection, $row['company_category']);
            $productName = mysqli_real_escape_string($connection, $row['product_name']);
            $productPrice = mysqli_real_escape_string($connection, $row['product_price']);
            $productQuantity = mysqli_real_escape_string($connection, $row['product_quantity']);
            $productTotal = mysqli_real_escape_string($connection, $row['product_total']);
            $productData[] = "('$productId', '$supplierName', '$company', '$companyCategory', '$productName', '$productPrice', '$productQuantity', '$productTotal', '$taxAmount', '$totalAmount', '$paidBy', '$customerName', '$customerPhone', '$discountAmount', '$discounted', '$discountPercentage', '$cashAmount', '$changeAmount', '$order_id', '$outlet_name', '$userName', '$userRole', '$outlet_address', '$dateTime')";
        }

        // Construct the INSERT query
        $insertQuery .= implode(", ", $productData);

        // Execute the query
        if (mysqli_query($connection, $insertQuery)) {
            echo "Records inserted successfully.";
        } else {
            echo "Error: " . $insertQuery . "<br>" . mysqli_error($connection);
        }
    } else {
        echo "No products found.";
    }
}



// Check if product name is requested via AJAX
if (isset($_POST['product_name'])) {
    $productName = mysqli_real_escape_string($connection, $_POST['product_name']);
    echo "Product name: $productName\n";

    $product_query = mysqli_query($connection, "SELECT * FROM products WHERE name = '$productName'");

    if ($product_query && mysqli_num_rows($product_query) > 0) {
        $product = mysqli_fetch_assoc($product_query);
        echo "Product found: ". json_encode($product). "\n";
        echo json_encode($product);
    } else {
        echo "Error: Product not found\n";
        echo json_encode(["error" => "Product not found"]);
    }

}

// Fetch product names
$products_query1 = mysqli_query($connection, "SELECT name FROM products");
$products = array();
while ($row = mysqli_fetch_assoc($products_query1)) {
    $products[] = $row["name"];
}
?>



<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pharmacy POS</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
        html, body {
            height: 100%;
            margin: 0;
            padding: 0;
            font-family: Arial, sans-serif;
            background-image: url(img/bg.jpg);
            background-size: cover;
            background-position: center;
            background-attachment: fixed;
        }

        .wrapper {
            display: flex;
            flex-direction: column;
            height: 100%;
        }

        .header,
        .footer {
            width: 100%;
            height: 70px;
            background-color: #060606;
            color: #fff;
            text-align: ;
        }

        .content {
            flex: 1;
            overflow-y: auto;
            padding: 10px;
        }

        #product-container-wrapper {
            max-height: 300px;
            overflow-y: auto;
        }

        .dropdown-options {
            display: none;
            position: absolute;
            z-index: 1000;
            width: calc(89% - 2px);
            max-height: 200px;
            overflow-y: auto;
            border: 1px solid #ccc;
            background-color: #fff;
        }

        .option {
            padding: 5px 10px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .option:hover,
        .option.highlight {
            background-color: #353535;
            color: #fff;
        }

        @keyframes blink {
            0% {
                opacity: 1;
            }

            50% {
                opacity: 0;
            }

            100% {
                opacity: 1;
            }
        }

        #total-amount {
            font-size: 46px;
            font-weight: 700;
            color: #0A5064;
            animation: blink 1s step-start infinite;
        }

        label {
            font-weight: 600;
        }

        .in_c {
            border: 1.5px solid #0A5064;
        }
        img.pulse {
            width: 60px;
            height: 60px;
            animation: pulse 2s infinite;
        }
        @keyframes pulse {
            0% {
                transform: scale(1);
            }
            50% {
                transform: scale(1.2);
            }
            100% {
                transform: scale(1);
            }
        }
        .btn-success {
            background: #0A5064;
            color: #fff;
            border: 1px solid #353535;
        }
    </style>
</head>

<body>
    <div class="wrapper">
        <div class="header row">
            <div class="col-sm-3">
                <a href="addproduct.php"><img class="pulse" src="img/logo_1.png" width="60" height="60"></a>
            </div>
            <div class="col-sm-6">
                <h3 style="color:#fff; text-align:center;line-height:70px; font-weight:600;">HASSAN PHARMACY</h3>
            </div>    
            <div class="col-sm-3"></div>
        </div>

        <div class="content">
            <div class="container">
                <form id="orderForm" action="ordermodify2.php?order_id=<?php echo $order_id; ?>" method="post" enctype="multipart/form-data">
                    <div class="container">
                        <div class="row" style="border:1px solid #0A5064; border-radius:7px; background:#FFF;padding:10px;">
                            <div class="col-sm-5">
                                <br>
                                <div class="form-group" style="border:1px solid #ccc; border-radius:7px; background:#EFEFE5;padding:10px;">
                                    <input type="text" id="searchInput" class="search-input form-control in_c" />
                                    <div id="filteredOptions" class="dropdown-options"></div>
                                </div>
                            </div>
                            <div class="col-sm-4"></div>
                            <div class="col-sm-3" style="background:#353535; text-align:center; padding:15px;border-radius:10px;border:1px solid #0A5064;">
                                <span style="font-size:46px; font-weight:700; color:#0A5064;" id="total-amount">0.00</span>
                            </div>
                        </div>
                        <br>
                        <div class="row">
                            <div class="col-sm-12" id="product-container-wrapper" style="height:320px; border:1px solid #0A5064; border-radius:7px; background:#F5F5F5;padding:10px;">
                                <table id="cart-table" class="table table-striped table-sm text-center">
                                    <thead>
                                        <tr class="bg-dark text-white" style="border-radius:10px;">
                                            <th>Total.Qty</th>
                                            <th>Item Code</th>
                                            <th>Description</th>
                                            <th>Modify.Qty</th>
                                            <th>Unit Price</th>
                                            <th>Amount</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php while($row = mysqli_fetch_array($products_query)) { ?>
                                            <tr>
                                                <td style="color:#0A5064; font-weight:600;"><?php echo $row["product_quantity"]; ?></td>
                                                <td style="color:#0A5064; font-weight:600;"><?php echo $row["product_id"]; ?></td>
                                                <td style="color:#353535; font-weight:600;"><?php echo $row["product_name"]; ?></td>
                                                <td><center><input type="number" class="form-control" value="<?php echo $row["product_quantity"]; ?>" style="width:41%; border:1px solid #0A5064;" /></center></td>
                                                <td><?php echo $row["product_price"]; ?></td>
                                                <td style="color:#353535; font-weight:600;"><?php echo $row["product_total"]; ?></td>
                                            </tr>
                                        <?php } ?>
                                    </tbody>
                                </table>
                                <div id="hidden-fields-container"></div>
                            </div>
                        </div>
                        <div class="row" style="margin-top:30px;">
                            <div class="col-sm-12" style="background:#F5F5F5; padding:18px; border:1px solid #0A5064; border-radius:7px;">
                                <div class="row">
                                    <div class="col-sm-2">
                                        <div class="form-group">
                                            <label>Total</label>
                                            <input type="number" id="total-input" name="total_input" class="form-control in_c" readonly />
                                        </div>
                                    </div>
                                    <div class="col-sm-2">
                                        <div class="form-group">
                                            <label>Bill Amount</label>
                                            <input type="number" id="discount-input" name="discounted" class="form-control in_c" oninput="calculateResult()" />
                                        </div>
                                    </div>
                                    <div class="col-sm-2">
                                        <div class="form-group">
                                            <label>Discount Amount</label>
                                            <input type="number" id="result-input" name="result" class="form-control in_c" readonly />
                                        </div>
                                    </div>
                                    <div class="col-sm-2">
                                        <div class="form-group">
                                            <label>Discount %</label>
                                            <input type="number" id="percentage-display" name="discount_percentage" class="form-control in_c" readonly />
                                        </div>
                                    </div>
                                    <div class="col-sm-2">
                                        <div class="form-group">
                                            <label>Cash Received</label>
                                            <input type="number" id="cash-input" name="cash_amount" class="form-control in_c" />
                                        </div>
                                    </div>
                                    <div class="col-sm-2">
                                        <div class="form-group">
                                            <label>Cash Return</label>
                                            <input type="number" id="balance-input" name="change_amount" class="form-control in_c" readonly />
                                        </div>
                                    </div>
                                </div>
                                <br>
                                <div class="row">
                                    <div class="col-sm-2">
                                        <div class="form-group">
                                            <label>S.Tax(0%)</label>
                                            <input type="text" class="form-control in_c" name="tax_amount" />
                                        </div>
                                    </div>
                                    <div class="col-sm-2">
                                        <div class="form-group">
                                            <label>Customer Name</label>
                                            <input type="text" class="form-control in_c" name="customer_name" />
                                        </div>
                                    </div>
                                    <div class="col-sm-2">
                                        <div class="form-group">
                                            <label>Phone</label>
                                            <input type="text" class="form-control in_c" name="customer_phone" />
                                        </div>
                                    </div>
                                    <div class="col-sm-2">
                                        <div class="form-group">
                                            <label>Method</label>
                                            <select name="paid_by" class="form-control">
                                                <option value="cash">Cash</option>
                                                <option value="credit">Credit</option>
                                                <option value="other">Other</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-sm-3">
                                        <br>
                                        <button id="bill-button" class="btn btn-success form-control" type="submit" name="submit">Update / Modify</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <br>
                        <div class="row">
                            <div class="col-sm-5"></div>
                            <div class="col-sm-2"></div>
                            <div class="col-sm-5"></div>
                        </div>
                        <div class="row">
                            <div class="col-sm-12 text-left"></div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
$(document).ready(function() {
    var products = <?php echo json_encode($products); ?>;
    var searchInput = document.getElementById('searchInput');
    var filteredOptions = document.getElementById('filteredOptions');
    var cartTableBody = document.getElementById('cart-table').getElementsByTagName('tbody')[0];

   // Function to add product to table and form
function addProductToTable(productName, productId, productPrice) {
    // Add product to table
    var newRow = document.createElement('tr');
    newRow.innerHTML = `
        <td style="color:#0A5064; font-weight:600;">1</td>
        <td style="color:#0A5064; font-weight:600;">${productId}</td>
        <td style="color:#353535; font-weight:600;">${productName}</td>
        <td><center><input type="number" name="product[${productId}][quantity]" value="1" class="form-control" style="width:41%; border:1px solid #0A5064;" /></center></td>
        <td>${productPrice}</td>
        <td style="color:#353535; font-weight:600;">${productPrice}</td>
    `;
    cartTableBody.appendChild(newRow);

    // Calculate total amount and update display
    calculateAmountAndTotal();
}
function addProductToTable(productName) {
    // You can add an AJAX request here to send data to PHP for database insertion
    $.ajax({
        url: 'ordermodify2.php?order_id=<?php echo $order_id;?>', // PHP script to handle database insertion
        type: 'POST',
        data: { productName: productName }, // Data to be sent
        success: function(response) {
            console.log('Data inserted into database:', response);
        },
        error: function(xhr, status, error) {
            console.error('Error inserting data into database:', error);
        }
    });

    // Add product to table
    var newRow = document.createElement('tr');
    newRow.innerHTML = `
        <td style="color:#0A5064; font-weight:600;">1</td>
        <td style="color:#0A5064; font-weight:600;">001</td>
        <td style="color:#353535; font-weight:600;">${productName}</td>
        <td><center><input type="number" class="form-control" value="1" style="width:41%; border:1px solid #0A5064;" oninput="calculateAmountAndTotal()" /></center></td>
        <td>${productPrice}</td>
        <td style="color:#353535; font-weight:600;">${productPrice}</td>
    `;
    console.log('New row created:', newRow);
    console.log('Cart table body:', cartTableBody);
    cartTableBody.appendChild(newRow);

    // Calculate total amount and update display
    calculateAmountAndTotal();
}
       // Function to calculate total amount
    function calculateAmountAndTotal() {
        var totalAmount = 0;
        var rows = cartTableBody.getElementsByTagName('tr');
        for (var i = 0; i < rows.length; i++) {
            var quantity = parseInt(rows[i].getElementsByTagName('input')[0].value);
            var price = parseFloat(rows[i].getElementsByTagName('td')[4].textContent);
            var amount = quantity * price;
            totalAmount += amount;
            rows[i].getElementsByTagName('td')[5].textContent = amount.toFixed(2);
        }
        document.getElementById('total-amount').textContent = totalAmount.toFixed(2);
        document.getElementById('total-input').value = totalAmount.toFixed(2);
        calculateResult();
        calculateCashReturn();
    }
// Function to handle form submission
document.getElementById('orderForm').addEventListener('submit', function(event) {
    var formData = new FormData(this);
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'ordermodify2.php?order_id=<?php echo $order_id;?>', true);
    xhr.onload = function() {
        if (xhr.status === 200) {
            console.log('Data inserted into database:', xhr.responseText);
        } else {
            console.error('Error inserting data into database:', xhr.statusText);
        }
    };
    xhr.send(formData);
});
        // Rest of the existing code for search and adding product...
        searchInput.addEventListener('input', function() {
            var value = searchInput.value.toLowerCase();
            var html = '';
            products.forEach(function(product) {
                if (product.toLowerCase().includes(value)) {
                    html += '<div class="option" data-value="' + product + '">' + product + '</div>';
                }
            });
            filteredOptions.innerHTML = html;
            if (value.length > 0) {
                filteredOptions.style.display = 'block';
            } else {
                filteredOptions.style.display = 'none';
            }
        });

    searchInput.addEventListener('keydown', function(e) {
        var options = filteredOptions.getElementsByClassName('option');
        var currentIndex = -1;
        for (var i = 0; i < options.length; i++) {
            if (options[i].classList.contains('highlight')) {
                currentIndex = i;
                break;
            }
        }
        if (e.key === 'ArrowDown') {
            e.preventDefault();
            if (currentIndex === -1 || currentIndex === options.length - 1) {
                if (options.length > 0) options[0].classList.add('highlight');
            } else {
                options[currentIndex].classList.remove('highlight');
                options[currentIndex + 1].classList.add('highlight');
            }
        } else if (e.key === 'ArrowUp') {
            e.preventDefault();
            if (currentIndex > 0) {
                options[currentIndex].classList.remove('highlight');
                options[currentIndex - 1].classList.add('highlight');
            }
        } else if (e.key === 'Enter') {
            if (currentIndex !== -1) {
                var selectedProduct = options[currentIndex].dataset.value;
                searchInput.value = selectedProduct;
                filteredOptions.style.display = 'none';
                addProductToTable(selectedProduct);
                e.preventDefault();
            }
        }
    });

    filteredOptions.addEventListener('click', function(e) {
        if (e.target.classList.contains('option')) {
            var selectedProduct = e.target.dataset.value;
            searchInput.value = selectedProduct;
            filteredOptions.style.display = 'none';
            addProductToTable(selectedProduct);
        }
    });

    function addProductToTable(productName) {
        var rows = cartTableBody.getElementsByTagName('tr');
        var productExists = false;

        for (var i = 0; i < rows.length; i++) {
            var descriptionCell = rows[i].getElementsByTagName('td')[2];
            if (descriptionCell.textContent === productName) {
                var quantityInput = rows[i].getElementsByTagName('input')[0];
                quantityInput.value = parseInt(quantityInput.value) + 1;
                productExists = true;
                break;
            }
        }

        if (!productExists) {
            var newRow = document.createElement('tr');
            newRow.innerHTML = `
                <td style="color:#0A5064; font-weight:600;">1</td>
                <td style="color:#0A5064; font-weight:600;">${productId}</td>
                <td style="color:#353535; font-weight:600;">${productName}</td>
                <td><center><input type="number" class="form-control" value="1" style="width:41%; border:1px solid #0A5064;" oninput="calculateAmountAndTotal()" /></center></td>
                <td>${productPrice}</td>
                <td style="color:#353535; font-weight:600;">${productPrice}</td>
            `;
            cartTableBody.appendChild(newRow);
        }
        calculateAmountAndTotal();
        searchInput.value = '';
    }


      
    function calculateResult() {
        var totalAmount = parseFloat(document.getElementById('total-input').value);
        var billAmount = parseFloat(document.getElementById('discount-input').value);
        var discountAmount = totalAmount - billAmount;
        document.getElementById('result-input').value = discountAmount.toFixed(2);

        var discountPercentage = (discountAmount / totalAmount) * 100;
        document.getElementById('percentage-display').value = discountPercentage.toFixed(2);
    }
	
	 function calculateCashReturn() {
        var totalAmount = parseFloat(document.getElementById('total-input').value);
        var billAmount = parseFloat(document.getElementById('discount-input').value); // Changed variable name to billAmount
        var cashAmount = parseFloat(document.getElementById('cash-input').value);
        var cashReturn = cashAmount - billAmount; // Subtract billAmount from cashAmount
        document.getElementById('balance-input').value = cashReturn.toFixed(2);
    }

    document.getElementById('discount-input').addEventListener('input', calculateResult);
    document.getElementById('cash-input').addEventListener('input', calculateCashReturn);
    cartTableBody.addEventListener('input', function(e) {
        if (e.target && e.target.type === 'number') {
            calculateAmountAndTotal();
        }
    });
});
    </script>

</html>
</html>
</body>
</html>