<?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'])) {
    $pr_Name = mysqli_real_escape_string($conn, $_POST['pr_Name']);
    $supplier_id = mysqli_real_escape_string($conn, $_POST['supplier_id']);
    $quantity_purchased = intval($_POST['quantity_purchased']);
    $pr_Cost = floatval(str_replace(',', '', $_POST['pr_Cost']));
    $payment_method = mysqli_real_escape_string($conn, $_POST['payment_method']);
    
    $total_amount = $quantity_purchased * $pr_Cost;
    
    // Check if product exists
    $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'] >= 0) {
        $product_number = $row['product_number']; // Fetch product_number
        $new_qty_Onhand = $row['qty_Onhand'] + $quantity_purchased;
        $update_query = "UPDATE products_table SET qty_Onhand = '$new_qty_Onhand' WHERE pr_Name = '$pr_Name'";
        mysqli_query($conn, $update_query);

        // Insert into purchase table
        $insert_query = "INSERT INTO purchase_table (product_number, sup_id, pr_Name, quantity_purchased, total_amount, payment_method)
                         VALUES ('$product_number', '$supplier_id', '$pr_Name', '$quantity_purchased', '$total_amount', '$payment_method')";
        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>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="fontawesome/css/all.min.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <h1>Product Purchase 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="supplier_id">Supplier:</label></td>
                    <td>
                        <select name="supplier_id" id="supplier_id" required>
                            <option value="">Select Supplier</option>
                            <?php while ($row = mysqli_fetch_assoc($supplierResult)): ?>
                                <option value="<?php echo $row['sup_id']; ?>">
                                    <?php echo $row['sup_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="pr_Cost">Cost:</label></td>
                    <td><input type="text" name="pr_Cost" id="pr_Cost" onchange="updateTotal()"></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="purchase">Purchase</button></td>
                </tr>
            </form>
        </table>
    </div>
</body>
</html>
