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

error_reporting(E_ALL);
ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// Set the correct timezone
date_default_timezone_set('Africa/Dar_es_Salaam');

include 'connect.php';

// Fetch supplier data
$supplierQuery = "SELECT sup_name FROM supplier_table";
$supplierResult = mysqli_query($conn, $supplierQuery);

if (isset($_POST['purchase'])) {
    $pr_Name = mysqli_real_escape_string($conn, $_POST['pr_Name']);
    $sup_name = mysqli_real_escape_string($conn, $_POST['sup_name']);
    $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;
    $purchase_time = date("Y-m-d H:i:s"); // Get current timestamp

    // Fetch product details
    $query = "SELECT * FROM products_table WHERE pr_Name = '$pr_Name'";
    $result = mysqli_query($conn, $query);
    $row = mysqli_fetch_assoc($result);

    if ($row) {
        $product_number = $row['product_number'];
        $new_qty_Onhand = $row['qty_Onhand'] + $quantity_purchased;
        
        // Update product stock
        mysqli_query($conn, "UPDATE products_table SET qty_Onhand = '$new_qty_Onhand' WHERE pr_Name = '$pr_Name'");

        // Insert purchase record
       $insert_query = "INSERT INTO purchase_table (product_number, sup_name, pr_Name, quantity_purchased, total_amount, payment_method, purchase_time)
        VALUES ('$product_number', '$sup_name', '$pr_Name', $quantity_purchased, $total_amount, '$payment_method', '$purchase_time')";

        if (mysqli_query($conn, $insert_query)) {
            echo "<script>alert('Product Purchased successfully!');</script>";
        } else {
            echo "<script>alert('Error: " . mysqli_error($conn) . "');</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">
    <script src="js/jquery-3.6.0.min.js"></script>
    <style>
        .form-container { max-width: 500px; margin: auto; }
    </style>
</head>
<body>
    <div class="container my-3">
        <h2 class="text-center">Product Purchase</h2>
        <form action="" method="POST" class="form-container p-3 border rounded">
            <div class="mb-2">
                <label for="sup_name" class="form-label">Supplier:</label>
                <select name="sup_name" id="sup_name" class="form-select" required>
                    <option value="">Select Supplier</option>
                    <?php while ($row = mysqli_fetch_assoc($supplierResult)): ?>
                        <option value="<?php echo $row['sup_name']; ?>"><?php echo $row['sup_name']; ?></option>
                    <?php endwhile; ?>
                </select>
            </div>
            <div class="mb-2">
                <label for="product_search" class="form-label">Product Name:</label>
                <input type="text" name="product_search" id="product_search" class="form-control" autocomplete="off">
                <div id="product_list"></div>
            </div>
            <div class="mb-2">
                <label for="pr_Name" class="form-label">Selected Product:</label>
                <input type="text" name="pr_Name" id="pr_Name" class="form-control" readonly>
            </div>
            <div class="mb-2">
                <label for="pr_Cost" class="form-label">Cost:</label>
                <input type="text" name="pr_Cost" id="pr_Cost" class="form-control" onchange="updateTotal()">
            </div>
            <div class="mb-2">
                <label for="quantity_purchased" class="form-label">Quantity:</label>
                <input type="number" name="quantity_purchased" id="quantity_purchased" class="form-control" value="1" min="1" onchange="updateTotal()">
            </div>
            <div class="mb-2">
                <label for="total_amount" class="form-label">Total Amount:</label>
                <input type="text" name="total_amount" id="total_amount" class="form-control" readonly>
            </div>
            <div class="mb-2">
                <label for="payment_method" class="form-label">Payment Method:</label>
                <select name="payment_method" id="payment_method" class="form-select" required>
                    <option value="Cash">Cash</option>
                    <option value="Credit">Credit</option>
                </select>
            </div>
            <button type="submit" name="purchase" class="btn btn-primary w-100" onclick="return confirmPurchase();">Purchase</button>
        </form>
    </div>

    <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 });
        }

        function confirmPurchase() {
            var product = document.getElementById("pr_Name").value;
            var qty = document.getElementById("quantity_purchased").value;
            var total = document.getElementById("total_amount").value;

            if (!product || qty <= 0 || !total) {
                alert("Please make sure product, quantity, and cost are set before purchasing.");
                return false;
            }

            return confirm("Are you sure you want to purchase " + qty + 
                           " unit(s) of " + product + 
                           " for TShs " + total + "?");
        }

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