<?php
session_start();
if (!isset($_SESSION['username'])) {
    echo "<script>window.top.location.href='index.php';</script>"; // Redirect parent window to login page
    exit();
}

// Database connection
include 'connect.php';

// Fetch customers for dropdown
$customerQuery = "SELECT customer_id, cust_name FROM customer_table";
$customerResult = mysqli_query($conn, $customerQuery);

$pr_Name = $pr_Price = $product_number = $qty_Onhand = $total_amount = '';
$message = '';

if (isset($_POST['sell'])) {
    $pr_Name = mysqli_real_escape_string($conn, $_POST['pr_Name']);
    $customer_id = mysqli_real_escape_string($conn, $_POST['customer_id']);
    $quantity_sold = intval($_POST['quantity_sold']);
    $pr_Price = floatval(str_replace(',', '', $_POST['pr_Price'])); // Allow price modification
    $payment_method = mysqli_real_escape_string($conn, $_POST['payment_method']);
    
    $total_amount = $quantity_sold * $pr_Price;
    
    // Check if quantity is available
    $query = "SELECT * FROM products_table WHERE pr_Name = '$pr_Name'";
    $result = mysqli_query($conn, $query);
    $row = mysqli_fetch_assoc($result);
    
    if ($row && $row['qty_Onhand'] >= $quantity_sold) {
        $product_number = $row['product_number']; // Fetch product_number
        $new_qty_Onhand = $row['qty_Onhand'] - $quantity_sold;
        $update_query = "UPDATE products_table SET qty_Onhand = '$new_qty_Onhand' WHERE pr_Name = '$pr_Name'";
        mysqli_query($conn, $update_query);

        // Insert into sell table
        $insert_query = "INSERT INTO sell (product_number, cust_name, pr_Name, quantity_sold, total_amount, payment_method)
                         VALUES ('$product_number', '$customer_id', '$pr_Name', '$quantity_sold', '$total_amount', '$payment_method')";
        mysqli_query($conn, $insert_query);

        echo "<script>alert('Product sold successfully!');</script>";
    } else {
        echo "<script>alert('Insufficient quantity available or product not found!');</script>";
    }
}

mysqli_close($conn);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Product Sale</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="fontawesome/css/all.min.css">
    <script src="js/jquery-3.6.0.min.js"></script>
</head>
<body>
    <h1>Product Sale Form</h1>
    <div class="container my-5">
            <table class="table table-hover" border="2" style="width:70%">
                    <form action="" method="POST">
                        <tr>
                            <td><label for="customer_id">Customer:</label></td>
                            <td><select name="customer_id" id="customer_id" required>
                                <option value="MTEJA">MTEJA</option>
                                <?php while ($row = mysqli_fetch_assoc($customerResult)): ?>
                                    <option value="<?php echo $row['cust_name']; ?>">
                                        <?php echo $row['cust_name']; ?>
                                    </option>
                                <?php endwhile; ?>
                            </select></td>
                        </tr>
                        
                        <tr>
                                <td><label for="product_search">Product Name:</label></td>
                                <td><input type="text" name="product_search" id="product_search" autocomplete="off">
                                <div id="product_list"></div></td>
                        </tr>
                        <tr>
                                <td><label for="pr_Name">Selected Product:</label></td>
                                <td><input type="text" name="pr_Name" id="pr_Name" readonly></td>
                        </tr>
                        <tr>
                                <td><label for="product_number">Product Number:</label></td>
                                <td><input type="text" name="product_number" id="product_number" readonly></td>
                        </tr>
                        <tr>
                                <td><label for="pr_Price">Price:</label></td>
                                <td><input type="text" name="pr_Price" id="pr_Price" onchange="updateTotal()"></td>
                        </tr>
                        <tr>
                                <td><label for="quantity_sold">Quantity:</label></td>
                                <td><input type="number" name="quantity_sold" id="quantity_sold" value="1" min="1" onchange="updateTotal()"></td>
                        </tr>
                        <tr>
                                <td><label for="total_amount">Total Amount:</label></td>
                                <td><input type="text" name="total_amount" id="total_amount" readonly></td>
                        </tr>
                        <tr>
                                <td><label for="payment_method">Payment Method:</label></td>
                                <td><select name="payment_method" id="payment_method" required>
                                    <option value="Cash">Cash</option>
                                    <option value="Credit">Credit</option>
                                </select></td>
                        </tr>
                        <tr>
                                <td></td><td><button type="submit" name="sell">Sell</button></td>
                        </tr>
                    </form>
            </table>
    </div>

    <script>
        function updateTotal() {
            var pr_Price = parseFloat(document.getElementById('pr_Price').value.replace(/,/g, '')) || 0;
            var quantity = parseInt(document.getElementById('quantity_sold').value) || 0;
            var total = pr_Price * quantity;
            document.getElementById('total_amount').value = total.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        }

        $(document).ready(function(){
            $('#product_search').keyup(function(){
                var query = $(this).val();
                if (query != '') {
                    $.ajax({
                        url: "search_product.php",
                        method: "POST",
                        data: {query: query},
                        success: function(data) {
                            $('#product_list').fadeIn();
                            $('#product_list').html(data);
                        }
                    });
                } else {
                    $('#product_list').fadeOut();
                }
            });
            
            $(document).on('click', '.product-item', function(){
                var productName = $(this).text();
                var price = $(this).data('price');
                var productNumber = $(this).data('product_number');
                $('#pr_Name').val(productName);
                $('#pr_Price').val(parseFloat(price).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }));
                $('#product_number').val(productNumber);
                $('#product_list').fadeOut();
                updateTotal();
            });
        });
    </script>
</body>
</html>
