<?php
include 'includes/config.php';
session_start();

if (!$_SESSION['email']) {
    header('location:login.php');
}
?>
<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Add Stock Transfer</title>
    <!-- Favicon -->
    <link rel="shortcut icon" href="images/favicon.ico" />
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <!-- Typography CSS -->
    <link rel="stylesheet" href="css/typography.css">
    <!-- Style CSS -->
    <link rel="stylesheet" href="css/style.css">
    <!-- Responsive CSS -->
    <link rel="stylesheet" href="css/responsive.css">
    <style>
        ion-icon {
            font-size: 20px;
            margin-bottom: -5px;
        }
    </style>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

</head>

<body>
    <!-- loader Start -->
    <div id="loading">
        <div id="loading-center">
        </div>
    </div>
    <!-- loader END -->
    <!-- Wrapper Start -->
    <div class="wrapper">
        <!-- Sidebar  -->
        <?php
        include 'includes/sidebar.php';
        ?>
        <!-- TOP Nav Bar -->
        <?php include 'includes/header.php'; ?>
        <!-- TOP Nav Bar END -->
        <!-- Page Content  -->
        <div id="content-page" class="content-page">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-sm-12">
                        <div class="iq-card">
                            <div class="iq-card-header d-flex justify-content-between row">
                                <div class="iq-header-title col-lg-6">
                                    <h4 class="card-title"><a href="list_stock_transfer.php">Stock Transfer</a> > Add Stock Transfer
                                    </h4>
                                </div>
                            </div>
                            <div class="iq-card-body" style="overflow:auto;">
                                <form id="searchForm" enctype="multipart/form-data">
                                    <div class="row">
                                        <div class="col-lg-3">
                                            <div class="form-group">
                                                <label style="display: block;" for="" class="label-control">Reference No:</label>
                                                <input type="text" name="ref_no" class="form-control" id="" placeholder="Reference No">
                                            </div>
                                        </div>
                                        <div class="col-lg-3">
                                            <div class="form-group">
                                                <label for="" class="label-control" style="display: block;">Location (From):*</label>
                                                <select style="width: 90%;display:inline;" name="FromBranch" class="form-control" id="">
                                                    <option value="">Please Select</option>
                                                    <option>Fatima Lace Nashtar</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-lg-3">
                                            <div class="form-group">
                                                <label for="" class="label-control" style="display: block;">Location (to):*</label>
                                                <select style="width: 90%;display:inline;" name="ToBranch" class="form-control" id="">
                                                    <option value="">Please Select</option>
                                                    <option>Fatima Lace Emporium</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-lg-3">
                                            <div class="form-group">
                                                <label for="" class="label-control">Stock Transfer Date:</label>
                                                <input type="date" class="form-control" name="TransferDate"
                                                    placeholder="Business Name" id="">
                                            </div>
                                        </div>
                                    </div>

                            </div>
                        </div>
                    </div> <?php

                            $product_id = isset($_GET['product_id']) ? intval($_GET['product_id']) : 0;
                            $product_name = '';

                            if ($product_id > 0) {
                                try {
                                    // Prepare the SQL query
                                    $stmt = $conn->prepare("SELECT `name` FROM `products` WHERE `id` = :product_id");
                                    // Bind the parameter
                                    $stmt->bindParam(':product_id', $product_id, PDO::PARAM_INT);
                                    // Execute the statement
                                    $stmt->execute();
                                    // Fetch the result
                                    $product_name = $stmt->fetchColumn();
                                } catch (PDOException $e) {
                                    // Handle the error (e.g., log it, display a message)
                                    echo 'Query failed: ' . $e->getMessage();
                                    exit;
                                }
                            }
                            ?>

                    <div class="col-sm-12 iq-card">
                        <div class="">
                            <div class="iq-card-body">

                                <div class="col-lg-5 mx-auto position-relative">
                                    <div class="input-group">
                                        <div class="input-group-prepend">
                                            <span class="input-group-text" style="border: 1px solid gray;">
                                                <ion-icon name="search-outline"></ion-icon>
                                            </span>
                                        </div>
                                        <input type="search" id="product-search" class="form-control" placeholder="Enter Product name / SKU" value="<?php echo htmlspecialchars($product_name); ?>">
                                    </div>
                                    <div id="product-list" class="dropdown-menu w-100" style="max-height: 200px; overflow-y: auto; display: none; position: absolute; top: 100%; margin-top: 3.5em; left: 0;">
                                        <!-- Dropdown items will be injected here -->
                                    </div>
                                </div>

                            </div>
                            <div class="iq-card-body" style="overflow:auto;">
                                <table class="table table-hover table-bordered mt-3" id="product-table">
                                    <thead>
                                        <tr>
                                            <th style="width: 3%;">#</th>
                                            <th style="width: 11%;">Product <br> Name</th>
                                            <th style="width: 20%;">Quantity</th>
                                            <!-- <th style="width: 8%;">Unit Cost<br>(Before Discount)</th> -->
                                            <!-- <th style="width: 8%;">Discount<br>Percent</th> -->
                                            <th style="width: 12%;">Unit Cost</th>
                                            <!-- <th style="width: 8%;">Line<br>Total</th>
                                                <th style="width: 12%;">Profit <br>Margin %</th>
                                                <th style="width: 12%;">Unit Selling <br> Price (Inc. tax)</th> -->
                                            <th style="width: 4%;"><ion-icon name="trash-outline"></ion-icon>
                                            </th>
                                        </tr>
                                    </thead>
                                    <tbody></tbody>
                                </table>

                            </div>
                        </div>
                    </div>
                    <div class="col-sm-12 iq-card">
                        <div class="">
                            <div class="iq-card-body">

                                <div class="row">
                                    <div class="col-lg-6">
                                        <label for="" class="control-label">Additional Shipping charges:</label>
                                        <input type="text" name="shipping_charges" class="form-control" placeholder="0.00" id="shipping_charges">
                                    </div>
                                    <div class="col-lg-6">
                                        <label for="" class="control-label">Sell Note</label>
                                        <textarea name="sell_note" class="form-control" id="sell_note"></textarea>
                                    </div>
                                    <div class="col-lg-12">
                                        <button class="btn btn-primary">Save</button>
                                    </div>
                                </div>

                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    </form>
    </div>
    </div>
    </div>
    <!-- add new Customer -->
    <!-- Wrapper END -->
    <script>
        $(document).ready(function() {
            // Function to perform the search
            function performSearch(search) {
                $.ajax({
                    type: 'POST',
                    url: 'search_products.php',
                    data: {
                        search: search
                    },
                    success: function(response) {
                        console.log('Search response:', response); // Debugging line
                        if (response.includes('Product not found') || response.trim().length === 0) {
                            $('#product-list').hide();
                        } else {
                            var $productList = $(response);
                            if ($productList.length === 1 && $productList.hasClass('product-item')) {
                                var productId = $productList.data('id');
                                console.log('Selected product ID:', productId); // Debugging line
                                $.ajax({
                                    type: 'POST',
                                    url: 'get_product_stock_transfer.php',
                                    data: {
                                        id: productId
                                    },
                                    success: function(response) {
                                        console.log('Get product response:', response); // Debugging line
                                        $('#product-table tbody').append(response);
                                        $('#product-search').val('').trigger('change');
                                        $('#product-list').hide();
                                        updateTotals(); // Update totals after adding a product

                                        // Now, check the stock for the selected product
                                        checkStock(productId);
                                    }
                                });
                            } else {
                                $('#product-list').html(response).show();
                            }
                        }
                    }
                });
            }

            // Function to check the stock of a product
            function checkStock(productId) {
                $.ajax({
                    type: 'POST',
                    url: 'check_stock.php',
                    data: {
                        product_id: productId
                    },
                    success: function(response) {
                        console.log('Response from check_stock:', response); // Log the raw response

                        // Check for error in response
                        if (response.error) {
                            console.error(response.error); // Handle error appropriately
                        } else {
                            var stockQuantity = response.stock_quantity; // Get stock quantity
                            var currentStockQty = response.current_stock_qty; // Get current stock quantity
                            console.log('Stock Quantity:', stockQuantity); // Debugging line
                            console.log('Current Stock Quantity:', currentStockQty); // Debugging line

                            // Update quantity inputs with stock quantity data attributes
                            $('#product-table .quantity').each(function() {
                                $(this).data('stock-quantity', stockQuantity);
                                $(this).data('current-stock-quantity', currentStockQty); // Add current stock quantity
                            });

                            // Display the stock quantity in your UI as needed
                            // alert('Stock Quantity: ' + stockQuantity);
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('AJAX error:', status, error);
                    }
                });
            }

            // Validate quantity input on change
            $(document).on('input', '.quantity', function() {
                var enteredQuantity = parseFloat($(this).val());
                var currentStockQty = parseFloat($(this).data('current-stock-quantity')); // Get current stock quantity from data attribute

                if (enteredQuantity > currentStockQty) {
                    alert('Quantity cannot exceed current stock: ' + currentStockQty);
                    $(this).val(currentStockQty); // Reset to max current stock quantity
                }
            });

            // Handle product search input
            $('#product-search').on('keyup', function() {
                var search = $(this).val().trim();
                console.log('Searching for:', search); // Debugging line
                if (search.length > 0) {
                    performSearch(search);
                } else {
                    $('#product-list').hide();
                }
            });

            // Auto-trigger search if a value is pre-filled in the search input
            var initialSearch = $('#product-search').val().trim();
            if (initialSearch.length > 0) {
                performSearch(initialSearch);
            }

            // Handle product selection from the dropdown
            $(document).on('click', '.product-item', function() {
                var productId = $(this).data('id');
                console.log('Selected product ID from dropdown:', productId); // Debugging line
                $.ajax({
                    type: 'POST',
                    url: 'get_product_stock_transfer.php',
                    data: {
                        id: productId
                    },
                    success: function(response) {
                        console.log('Get product response from dropdown:', response); // Debugging line
                        $('#product-table tbody').append(response);
                        $('#product-list').hide();
                        $('#product-search').val('').trigger('change');
                        updateTotals(); // Update totals after selecting a product

                        // Now, check the stock for the selected product
                        checkStock(productId);
                    }
                });
            });


            // Update calculations when input values change
            $('#product-table').on('input', '.quantity, .discount, .profit-margin', function() {
                updateRow($(this).closest('tr'));
                updateTotals(); // Update totals after changing product details
            });

            function updateRow(row) {
                var purchasePrice = parseFloat(row.find('.purchase-price').val()) || 0;
                var quantity = parseFloat(row.find('.quantity').val()) || 1;
                var discountPercent = parseFloat(row.find('.discount').val()) || 0;
                var userProfitMarginPercent = parseFloat(row.find('.profit-margin').val()) || 0;

                var unitCostBeforeDiscount = purchasePrice;
                var unitCostBeforeTax = unitCostBeforeDiscount * (1 - discountPercent / 100);
                var lineTotal = unitCostBeforeTax * quantity;

                // Calculate profit margin percentage
                var calculatedProfitMarginPercent = ((unitCostBeforeDiscount - unitCostBeforeTax) / unitCostBeforeTax) * 100;

                // Final profit margin percentage is the max between calculated and user input
                var finalProfitMarginPercent = Math.max(userProfitMarginPercent, calculatedProfitMarginPercent);

                // Calculate unit selling price including the tax
                var unitSellingPrice = unitCostBeforeTax * (1 + finalProfitMarginPercent / 100);

                row.find('.unit-cost-before-discount').val(unitCostBeforeDiscount.toFixed(2));
                row.find('.unit-cost-before-tax').val(unitCostBeforeTax.toFixed(2));
                row.find('.line-total').text(lineTotal.toFixed(2));
                row.find('.profit-margin').val(finalProfitMarginPercent.toFixed(2));
                row.find('.unit-selling-price').val(unitSellingPrice.toFixed(2));
            }

            function updateTotals() {
                var totalItems = 0;
                var netTotalAmount = 0; // Actual total before any discounts or shipping
                var discountAmount = parseFloat($('#discount-amount').val()) || 0;
                var discountType = $('#discount-type').val();
                var shippingCharges = parseFloat($('#shipping-charges').val()) || 0;
                var appliedDiscount = 0;
                var purchaseTotal = 0; // Total after applying discounts and shipping
                var paymentAmount = parseFloat($('#payment-amount').val()) || 0; // Payment entered by user
                var paymentDue = 0; // Remaining amount after payment

                $('#product-table tbody tr').each(function() {
                    var quantity = parseFloat($(this).find('.quantity').val()) || 1;
                    var lineTotal = parseFloat($(this).find('.line-total').text()) || 0;

                    totalItems += quantity;
                    netTotalAmount += lineTotal; // Accumulate the actual total
                });

                purchaseTotal = netTotalAmount; // Start with the actual total

                // Calculate and apply discount to the purchase total only
                if (discountType === 'Fixed') {
                    appliedDiscount = discountAmount;
                    purchaseTotal -= appliedDiscount;
                } else if (discountType === 'Percentage') {
                    appliedDiscount = (purchaseTotal * (discountAmount / 100));
                    purchaseTotal -= appliedDiscount;
                }

                // Add shipping charges to the purchase total only
                purchaseTotal += shippingCharges;

                // Calculate payment due after subtracting payment amount
                paymentDue = purchaseTotal - paymentAmount;

                // Update the UI
                $('#total-items').text(totalItems);
                $('#net-total-amount').text(netTotalAmount.toFixed(2) + ' ₨'); // Shows the actual price before discounts
                $('#applied-discount').text(appliedDiscount.toFixed(2) + ' Rs');
                $('#purchase-total').text(purchaseTotal.toFixed(2) + ' ₨'); // Shows the final price after discounts and shipping
                $('#payment-due').text(paymentDue.toFixed(2) + ' Rs'); // Shows the remaining payment due
            }

            // Handle row removal
            $('#product-table').on('click', 'ion-icon[name="trash-outline"]', function() {
                $(this).closest('tr').remove();
                updateTotals(); // Update totals after removing a product
            });

            // Update totals when discount, shipping, or payment amount changes
            $('#discount-type, #discount-amount, #shipping-charges, #payment-amount').on('input change', function() {
                updateTotals();
            });

            // Initial call to update totals on page load
            updateTotals();
        });
        $(document).ready(function() {
            $('#searchForm').on('submit', function(event) {
                event.preventDefault(); // Prevent the default form submission

                var formData = new FormData(this);
                var productRows = $('#product-table tbody tr');

                // Collect product data
                var productData = {
                    product_id: [],
                    QuantityTransferred: [],
                    purchase_price: []
                };

                productRows.each(function() {
                    var row = $(this);
                    productData.product_id.push(row.find('input[name="product_id[]"]').val());
                    productData.QuantityTransferred.push(row.find('input[name="quantity[]"]').val());
                    productData.purchase_price.push(row.find('input[name="purchase_price[]"]').val());
                });

                // Validate product data arrays
                if (productData.product_id.length === 0 ||
                    productData.QuantityTransferred.length === 0 ||
                    productData.purchase_price.length === 0) {
                    alert('Please add at least one product to the list.');
                    return; // Exit the function if validation fails
                }

                // Append product data arrays to formData
                formData.append('product_id', JSON.stringify(productData.product_id));
                formData.append('QuantityTransferred', JSON.stringify(productData.QuantityTransferred));
                formData.append('purchase_price', JSON.stringify(productData.purchase_price));

                // Validate required fields before appending
                var refNo = $('input[name="ref_no"]').val();
                var fromBranch = $('select[name="FromBranch"]').val();
                var toBranch = $('select[name="ToBranch"]').val();
                var transferDate = $('input[name="TransferDate"]').val();

                // Collect error messages
                var errorMessages = [];

                if (!refNo) {
                    errorMessages.push('Ref No is required.');
                }
                if (!fromBranch) {
                    errorMessages.push('From Branch is required.');
                }
                if (!toBranch) {
                    errorMessages.push('To Branch is required.');
                }
                if (!transferDate) {
                    errorMessages.push('Transfer Date is required.');
                }

                // Show alert if there are errors
                if (errorMessages.length > 0) {
                    alert(errorMessages.join('\n'));
                    return; // Exit the function if validation fails
                }

                // Append additional stock transfer fields
                formData.append('ref_no', refNo);
                formData.append('FromBranch', fromBranch);
                formData.append('ToBranch', toBranch);
                formData.append('TransferDate', transferDate);
                formData.append('shipping_charges', $('input[name="shipping_charges"]').val());
                formData.append('sell_note', $('textarea[name="sell_note"]').val());

                $.ajax({
                    type: 'POST',
                    url: 'submit_purchase_stock_transfer.php',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(response) {
                        try {
                            var result = JSON.parse(response);
                            if (result.status === 'success') {
                                alert(result.message);
                                setTimeout(function() {
                                    window.location.href = 'add_stock_transfer.php';
                                }, 700);
                            } else {
                                alert('Error: ' + result.message);
                            }
                        } catch (e) {
                            console.error("Parsing error:", e);
                            alert('Unexpected response from server: ' + response);
                        }
                    },
                    error: function(jqXHR, textStatus, errorThrown) {
                        console.error("AJAX error:", textStatus, errorThrown);
                        alert('An error occurred while processing your request: ' + textStatus);
                    }
                });
            });
        });
    </script>
    <!-- Footer -->
    <?php include 'includes/footer.php'; ?>
    <nav class="iq-float-menu">
        <input type="checkbox" href="#" class="iq-float-menu-open" name="menu-open" id="menu-open" />
        <label class="iq-float-menu-open-button" for="menu-open">
            <span class="lines line-1"></span>
            <span class="lines line-2"></span>
            <span class="lines line-3"></span>
        </label>
        <button class="iq-float-menu-item bg-info" data-toggle="tooltip" data-placement="top" title="Direction Mode"
            data-mode="rtl"><i class="ri-text-direction-r"></i></button>
        <button class="iq-float-menu-item bg-danger" data-toggle="tooltip" data-placement="top" title="Color Mode"
            id="dark-mode" data-active="true"><i class="ri-sun-line"></i></button>
        <button class="iq-float-menu-item bg-warning" data-toggle="tooltip" data-placement="top" title="Comming Soon"><i
                class="ri-palette-line"></i></button>
    </nav>
    <!-- Footer END -->
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="js/jquery.min.js"></script>
    <!-- Rtl and Darkmode -->
    <script src="js/rtl.js"></script>
    <script src="js/customizer.js"></script>
    <script src="js/popper.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <!-- Appear JavaScript -->
    <script src="js/jquery.appear.js"></script>
    <!-- Countdown JavaScript -->
    <script src="js/countdown.min.js"></script>
    <!-- Counterup JavaScript -->
    <script src="js/waypoints.min.js"></script>
    <script src="js/jquery.counterup.min.js"></script>
    <!-- Wow JavaScript -->
    <script src="js/wow.min.js"></script>
    <!-- Apexcharts JavaScript -->
    <script src="js/apexcharts.js"></script>
    <!-- Slick JavaScript -->
    <script src="js/slick.min.js"></script>
    <!-- Select2 JavaScript -->
    <script src="js/select2.min.js"></script>
    <!-- Owl Carousel JavaScript -->
    <script src="js/owl.carousel.min.js"></script>
    <!-- Magnific Popup JavaScript -->
    <script src="js/jquery.magnific-popup.min.js"></script>
    <!-- Smooth Scrollbar JavaScript -->
    <script src="js/smooth-scrollbar.js"></script>
    <!-- lottie JavaScript -->
    <script src="js/lottie.js"></script>
    <!-- Chart Custom JavaScript -->
    <script src="js/chart-custom.js"></script>
    <!-- Custom JavaScript -->
    <script src="js/custom.js"></script>
</body>

</html>