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

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

include 'connect.php';

// Fetch customer list
$customerQuery = "SELECT customer_id, cust_name FROM customer_table";
$customerResult = mysqli_query($conn, $customerQuery);

$message = "";

if (isset($_POST['sell'])) {
    $product_number = mysqli_real_escape_string($conn, $_POST['product_number']);
    $customer_id = mysqli_real_escape_string($conn, $_POST['customer_id']);
    $quantity_sold = intval($_POST['quantity_sold']);
    $pr_Price = floatval(str_replace(',', '', $_POST['pr_Price']));
    $payment_method = mysqli_real_escape_string($conn, $_POST['payment_method']);

    $total_amount = $quantity_sold * $pr_Price;
    $sale_date = date("Y-m-d H:i:s");

    $query = "SELECT * FROM products_table WHERE product_number = '$product_number'";
    $result = mysqli_query($conn, $query);
    $row = mysqli_fetch_assoc($result);

    if ($row && $row['qty_Onhand'] >= $quantity_sold) {
        $pr_Name = $row['pr_Name'];
        $new_qty_Onhand = $row['qty_Onhand'] - $quantity_sold;

        mysqli_query($conn, "UPDATE products_table SET qty_Onhand = '$new_qty_Onhand' WHERE product_number = '$product_number'");

        mysqli_query($conn, "INSERT INTO sell (product_number, cust_name, pr_Name, quantity_sold, total_amount, payment_method, sell_time) 
                     VALUES ('$product_number', '$customer_id', '$pr_Name', '$quantity_sold', '$total_amount', '$payment_method', '$sale_date')");

        $message = '<div class="alert alert-success"><i class="bi bi-check-circle"></i> Product sold successfully!</div>';
    } else {
        $message = '<div class="alert alert-danger"><i class="bi bi-x-circle"></i> Insufficient quantity available or product not found!</div>';
    }
}
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="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css">
    <script src="js/jquery-3.6.0.min.js"></script>
</head>
<body class="container mt-3">
    <h4 class="text-center">Product Sale Form</h4>
    <?php echo $message; ?>
    <form action="" method="POST" class="border p-3 rounded shadow-sm" style="max-width: 400px; margin: auto;" onsubmit="return confirmSale()">
        <div class="mb-2">
            <label class="form-label">Customer:</label>
            <select name="customer_id" class="form-select" 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>
        </div>
        <div class="mb-2">
            <label class="form-label">Product Number:</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">
            <input type="text" name="product_number" id="product_number" class="form-control" readonly>
        </div>
        <div class="mb-2">
            <label class="form-label">Price:</label>
            <input type="text" name="pr_Price" id="pr_Price" class="form-control" onchange="updateTotal()">
        </div>
        <div class="mb-2">
            <label class="form-label">Quantity:</label>
            <input type="number" name="quantity_sold" id="quantity_sold" class="form-control" value="1" min="1" onchange="updateTotal()">
        </div>
        <div class="mb-2">
            <label 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 class="form-label">Payment Method:</label>
            <select name="payment_method" class="form-select" required>
                <option value="Cash">Cash</option>
                <option value="Credit">Credit</option>
            </select>
        </div>
        <div class="text-center">
            <button type="submit" name="sell" class="btn btn-primary">Sell</button>
        </div>
    </form>

    <script>
        function confirmSale() {
            return confirm('Are you sure you want to sell this item?');
        }

        function updateTotal() {
            var pr_Price = parseFloat(document.getElementById('pr_Price').value.replace(/,/g, '')) || 0;
            var quantity = parseInt(document.getElementById('quantity_sold').value) || 0;
            document.getElementById('total_amount').value = (pr_Price * quantity).toFixed(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().html(data);
                        }
                    });
                } else {
                    $('#product_list').fadeOut();
                }
            });
            $(document).on('click', '.product-item', function(){
                $('#product_number').val($(this).data('product_number'));
                $('#pr_Price').val(parseFloat($(this).data('price')).toFixed(2));
                $('#product_list').fadeOut();
                updateTotal();
            });
        });
    </script>
</body>
</html>
