<?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 suppliers for dropdown
$supplierQuery = "SELECT sup_id, sup_name FROM supplier_table";
$supplierResult = mysqli_query($conn, $supplierQuery);

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

if (isset($_POST['purchase'])) {
    $sup_id = mysqli_real_escape_string($conn, $_POST['sup_id']);
    $product_number = mysqli_real_escape_string($conn, $_POST['product_number']);
    $pr_Name = mysqli_real_escape_string($conn, $_POST['pr_Name']);
    $quantity_purchased = intval($_POST['quantity_purchased']);
    $pr_Cost = floatval($_POST['pr_Cost']);
    $payment_method = mysqli_real_escape_string($conn, $_POST['payment_method']);
    $paid_amount = floatval($_POST['paid_amount']);
    
    $total_amount = $quantity_purchased * $pr_Cost;
    
    // Check if product exists
    $query = "SELECT * FROM products_table WHERE product_number = '$product_number'";
    $result = mysqli_query($conn, $query);
    $row = mysqli_fetch_assoc($result);
    
    if ($row) {
        // Update product quantity
        $new_qty_Onhand = $row['qty_Onhand'] + $quantity_purchased;
        $update_query = "UPDATE products_table SET qty_Onhand = '$new_qty_Onhand' WHERE product_number = '$product_number'";
        mysqli_query($conn, $update_query);
        
        // Insert into purchase table
        $insert_query = "INSERT INTO purchase_table (sup_id, product_number, pr_Name, quantity_purchased, total_amount, payment_method, paid_amount, purchase_time) 
                         VALUES ('$sup_id', '$product_number', '$pr_Name', '$quantity_purchased', '$total_amount', '$payment_method', '$paid_amount', NOW())";
        mysqli_query($conn, $insert_query);
        
        echo "<script>alert('Product purchased successfully!');</script>";
    } else {
        echo "<script>alert('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 Purchase</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <h1>Product Purchase Form</h1>
    <form action="" method="POST">
        <label for="sup_id">Supplier:</label>
        <select name="sup_id" id="sup_id" required>
            <?php while ($row = mysqli_fetch_assoc($supplierResult)): ?>
                <option value="<?php echo $row['sup_id']; ?>">
                    <?php echo $row['sup_name']; ?>
                </option>
            <?php endwhile; ?>
        </select><br><br>

        <label for="product_search">Product Name:</label>
        <input type="text" name="product_search" id="product_search" autocomplete="off">
        <div id="product_list"></div>
        <br><br>

        <label for="pr_Name">Selected Product:</label>
        <input type="text" name="pr_Name" id="pr_Name" readonly>
        <br><br>

        <label for="product_number">Product Number:</label>
        <input type="text" name="product_number" id="product_number" readonly>
        <br><br>

        <label for="pr_Cost">Price:</label>
        <input type="text" name="pr_Cost" id="pr_Cost">
        <br><br>

        <label for="quantity_purchased">Quantity:</label>
        <input type="number" name="quantity_purchased" id="quantity_purchased" value="1" min="1" onchange="updateTotal()">
        <br><br>

        <label for="total_amount">Total Amount:</label>
        <input type="text" name="total_amount" id="total_amount" readonly>
        <br><br>

        <label for="payment_method">Payment Method:</label>
        <select name="payment_method" id="payment_method" required>
            <option value="Cash">Cash</option>
            <option value="Credit">Credit</option>
        </select>
        <br><br>

        <label for="paid_amount">Paid Amount:</label>
        <input type="text" name="paid_amount" id="paid_amount" required>
        <br><br>

        <button type="submit" name="purchase">Purchase</button>
    </form>

    <script>
        function updateTotal() {
            var pr_Cost = parseFloat(document.getElementById('pr_Cost').value.replace(/,/g, '')) || 0;
            var quantity = parseInt(document.getElementById('quantity_purchased').value) || 0;
            var total = pr_Cost * 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_Cost').val(parseFloat(price).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }));
                $('#product_number').val(productNumber);
                $('#product_list').fadeOut();
                updateTotal();
            });
        });
    </script>
</body>
</html>
