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

if (!$_SESSION['email']) {
    header('location:login.php');
}
?>

<?php
$sql = "SELECT * FROM contacts WHERE type = 'supplier' AND name != 'Audit Purchase'";
try {
    $query = $conn->prepare($sql);
    $query->execute();
    $space = $query->fetchAll();
} catch (Exception $ex) {
    echo $ex->getMessage();
}
?>

<!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 Purchase</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">
    <!-- Chosen CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.min.css">
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- Chosen JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.min.js"></script>
    <!-- Custom Styles -->
    <script type="module" src="https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.esm.js"></script>
    <script nomodule src="https://unpkg.com/ionicons@7.1.0/dist/ionicons/ionicons.js"></script>

    <style>
        ion-icon {
            font-size: 20px;
            margin-bottom: -5px;
        }

        .chosen-container {
            height: 40px;
            /* Adjust the height of the selected box */
        }

        .chosen-container .chosen-single {
            height: 40px;
            /* Adjust the height of the selected box */
            line-height: 38px;
            /* Align text vertically */
            border-radius: 0px;
        }

        .chosen-container .chosen-drop {
            max-height: 200px;
            /* Adjust the max height of the dropdown */
            overflow-y: auto;
            /* Add scroll if content exceeds max-height */
        }

        .chosen-container .chosen-results {
            padding: 0;
            /* Remove default padding */
        }

        .file-input-wrapper {
            display: flex;
            align-items: center;
        }

        .file-input-wrapper input[type="file"] {
            position: absolute;
            border-radius: 0px;
            width: 100%;
            height: 100%;
            opacity: 0;
            cursor: pointer;
        }

        .file-input-wrapper .form-control {
            margin-right: 0;
            /* Remove margin to align properly */
        }

        .file-input-wrapper .btn-browse {
            margin-left: -1px;
            /* Adjust to align with the input field */
            border-radius: 0;
            height: 2.4em;
            width: 11em;
        }

        input[type="text"],
        input[type="number"],
        input[type="date"] {
            border-radius: 0px;
            height: 2.3em;
        }

        input[type="search"] {
            border-radius: 0px;
            height: 3em;
        }

        table .th {
            font-size: 12px;
            font-weight: bold;

        }

        table .td {
            width: 8em;
            height: 1.7em;
            border: 1px solid #c5c6c7;
        }

        tbody {
            background-color: #fff;
        }

        .input-group-text {
            background: #f8f9fa;
            /* Optional: to match the input background */
            border-right: 1px solid #ced4da;
            /* Optional: to match the input border */
        }

        .table-container {
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
        }

        #product-table {
            min-width: 1000px;
            /* Set this based on your column widths */
        }

        #product-table th,
        #product-table td {
            white-space: nowrap;
            /* Prevents text wrapping */
            text-align: center;
            /* Centers the text */
        }

        #product-table th:nth-child(1),
        #product-table td:nth-child(1) {
            width: 5%;
            /* Adjust width as needed */
        }

        #product-table th:nth-child(2),
        #product-table td:nth-child(2) {
            width: 30%;
            /* Adjust width as needed */
        }

        #product-table th:nth-child(3),
        #product-table td:nth-child(3) {
            width: 17%;
            /* Adjust width as needed */
        }

        #product-table th:nth-child(4),
        #product-table td:nth-child(4) {
            width: 8%;
            /* Adjust width as needed */
        }

        #product-table th:nth-child(5),
        #product-table td:nth-child(5) {
            width: 20%;
            /* Adjust width as needed */
        }

        #product-table th:nth-child(6),
        #product-table td:nth-child(6) {
            width: 20%;
            /* Adjust width as needed */
        }

        #product-table th:nth-child(7),
        #product-table td:nth-child(7) {
            width: 20%;
            /* Adjust width as needed */
        }

        #product-table th:nth-child(8),
        #product-table td:nth-child(8) {
            width: 20%;
            /* Adjust width as needed */
        }

        #product-table th:nth-child(9),
        #product-table td:nth-child(9) {
            width: 20%;
            /* Adjust width as needed */
        }

        #product-table th:nth-child(10),
        #product-table td:nth-child(10) {
            width: 20%;
            /* Adjust width as needed */
        }

        .table-responsive {
            overflow-x: auto;
        }

        .table {
            width: 100%;
        }

        th,
        td {
            text-align: center;
            vertical-align: middle;
            padding: 4px;
            /* Reduced padding to save space */
            font-size: 12px;
            /* Slightly smaller font size */
            text-transform: capitalize;
        }

        th {
            white-space: nowrap;
            /* Prevent header text from wrapping */
        }

        .table th {
            border-color: #dee2e6;
        }

        .table-bordered th,
        .table-bordered td {
            border: 1px solid #dee2e6;
        }

        .table input {
            width: 100%;
            padding: 3px;
            /* Reduced padding in input fields */
            box-sizing: border-box;
            font-size: 0.875rem;
        }

        @media (max-width: 768px) {

            .table th,
            .table td {
                font-size: 0.75rem;
                padding: 3px;
            }
        }
    </style>
    <script>
        $(document).ready(function() {
            $('#supplier').chosen({
                width: '100%', // Adjust width as needed
                placeholder_text_single: 'Select Supplier',
                no_results_text: 'No results matched'
            });
        });
    </script>
    <!-- <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <script>
        $(document).ready(function() {
            $('#file-input').on('change', function() {
                var fileName = $(this).val().split('\\').pop();
                $(this).siblings('input[type="text"]').val(fileName);
            });
        });
    </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_purchase.php">Purchase</a> > Add Purchase
                                    </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 for="" class="label-control">Supplier:*</label>
                                                <select id="supplier" name="supplier_id" class="form-control">
                                                    <option selected disabled>Select Supplier</option>
                                                    <?php foreach ($space as $output) { ?>
                                                        <option value="<?php echo $output["id"]; ?>"><?php echo $output["name"]; ?></option>
                                                    <?php } ?>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-lg-3">
                                            <div class="form-group">
                                                <label for="" class="label-control">Reference No:</label>
 <?php
include 'includes/config.php';

function generateRefNo($conn) {
    do {
        $ref_no = 'REF-' . rand(1000, 9999); 
        $stmt = $conn->prepare("SELECT COUNT(*) FROM purchase_lines WHERE ref_no = ?");
        $stmt->execute([$ref_no]);
        $exists = $stmt->fetchColumn() > 0;
    } while ($exists); 
    return $ref_no;
}

$autoRefNo = generateRefNo($conn);
?>


                                                <!-- HTML Input Field -->
                                                    <input type="text" class="form-control" name="ref_no" id="ref_no" value="<?php echo $autoRefNo; ?>" readonly>
     
                                              <div id="ref_no-message"></div> <!-- This will display the validation message -->
                                            </div>
                                        </div>
                                            <div class="col-lg-3">
                                            <div class="form-group">
                                                <label for="" class="label-control">Voucher No:</label>
                                                <input type="text" class="form-control" name="voucher_no"
                                                    placeholder="voucher_no" id="voucher_no">
                                            </div>
                                        </div>
                                        <div class="col-lg-3">
                                            <div class="form-group">
                                                <label for="" class="label-control">Purchase Date:</label>
                                                <input 
    type="date" 
    class="form-control" 
    name="purchase_date"
    id="purchase_date"
    value="<?php echo date('Y-m-d'); ?>" 
    placeholder="Business Name">

                                            </div>
                                        </div>
                                        <div class="col-lg-3">
                                            <div class="form-group">
                                                <label for="" class="label-control">Purchase Status:*</label>
                                                <select class="form-control" name="purchase_status">
                                                    <option>Received</option>
                                                    <option>Pending</option>
                                                    <option>Ordered</option>
                                                </select>
                                            </div>
                                        </div>


                                        <div class="col-lg-6">
                                            <div class="form-group">
                                                <label for="" class="label-control">Attach Document:</label>
                                                <div class="file-input-wrapper">
                                                    <!-- Hidden file input -->
                                                    <input type="file" id="file-input" name="attach_document">
                                                    <!-- Text input field -->
                                                    <input type="text" class="form-control" readonly placeholder="No file chosen">
                                                    <!-- Custom Browse button -->
                                                    <button type="button" class="btn btn-primary btn-browse" onclick="document.getElementById('file-input').click();"><ion-icon name="folder-open-outline"></ion-icon>&nbsp; Browse...</button>
                                                </div>
                                            </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">
                                <form action="" id="searchForm">
                                    <div class="container mt-5">
                                        <div class="row">
                                            <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 / Barcode" 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>

                            </div>
                            <div class="container mt-5">
                                <div class="table-responsive">
                                    <table class="table table-hover table-bordered mt-3" id="product-table">
                                        <thead>
                                        <tr>
                                                <th style="width: 3%;">#</th>
                                                <th style="width: 30%;">Product <br> Name</th>
                                                 <th style="width: 30%;">Barcode</th>
                                                 <th style="width: 30%; display:none;">Drum</th>
                                          <!-- <th style="width: 20%;">Color</th>-->
                                           <!-- <th style="width: 20%;">Size</th> -->
                                                <th style="width: 20%;">Quantity</th>
                                                <!-- <th style="width: 8%;">Unit Cost<br>(Before Discount)</th> -->
                                                <th style="width: 8%;">Purchase Price</th>
                                                <th style="width: 12%;">Unit Selling <br> Price (Inc. tax)</th>

                                                <!--<th style="width: 8%;">Shipping Cost</th>-->
                                                <!-- <th style="width: 8%;">Discount<br>Percent</th> -->
                                                <!-- <th style="width: 12%;">Unit Cost<br>(Before Tax)</th> -->
                                                <th style="width: 40%;">Total</th>
                                                <!--<th style="width: 12%;">Profit <br>Margin %</th>-->
                                                <th style="width: 4%;"><ion-icon name="trash-outline"></ion-icon>
                                                </th>
                                            </tr>
                                        </thead>
                                        <tbody></tbody>
                                    </table>
                                </div>
                            </div>





                        </div>
                        <hr>
                        <div style="display:inline; float:inline-end; margin-bottom:10px;">
                            <h6><span>Total Items:</span> <span id="total-items">0</span></h6>
                            <h6><span>Net Total Amount:</span> <span id="net-total-amount">0.00 ₨</span></h6>
                        </div>
                    </div>
                </div>
                <div class="col-sm-12 iq-card">
                    <div class="">
                        <div class="iq-card-body" style="display: none;">

                            <div class="row mt-5" style="width:95%;margin:0 auto;">
                                <div class="col-lg-5">
                                    <label for="" class="control-label">Discount Type:</label>
                                    <select name="discount_type" class="form-control" id="discount-type">
                                        <option value="None">None</option>
                                        <option value="Fixed">Fixed</option>
                                        <option value="Percentage">Percentage</option>
                                    </select>
                                </div> 
                                <div class="col-lg-3">
                                    <label for="" class="control-label">Discount Amount:</label>
                                    <input type="text" name="discount_amount" class="form-control" placeholder="0.00" id="discount-amount">
                                </div>
                                <div class="col-lg-4">
                                    <label for="" class="control-label">Details:</label>
                                    <input type="text" name="shipping_detail" class="form-control"
                                        placeholder="Enter Shipping Details" id="">
                                </div>
                                <div class="col-lg-3">
                                    <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-2">
                                    <h6 class="mt-5"><strong>Discount:</strong>(-)<span id="applied-discount">0.00 Rs</span></h6>
                                </div> 
                            </div>
                            
                           <div class="row mt-5" style="width:95%;margin:0 auto;">
                                <div class="col-lg-5">
                                    <label for="" class="control-label">Purchase Tax:</label>
                                    <select name="" class="form-control" id="">
                                        <option value="">None</option>
                                    </select>
                                </div>
                                <div class="col-lg-4">
                                </div>
                                <div class="col-lg-3">
                                    <h6 class="mt-5" style="display:inline;float:inline-end;"><strong>Purchase
                                            Tax:</strong>(-)0.00 Rs</h6>
                                </div>
                            </div> 
                         <div class="row mt-5" style="width:95%;margin:0 auto;">
                                <div class="col-lg-5">
                                    <label for="" class="control-label">Details:</label>
                                    <input type="text" name="shipping_detail" class="form-control"
                                        placeholder="Enter Shipping Details" id="">
                                </div>
                                <div class="col-lg-3">
                                </div>
                                <div class="col-lg-4">
                                    <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>
                            <hr>
                            <div class="row mt-5" style="width:95%;margin:0 auto;">
                                <div class="col-lg-5">
                                </div>
                                <div class="col-lg-4">
                                </div>
                                <div class="col-lg-3">
                                    <h6><strong>Purchase Total:</strong> <span id="purchase-total">0.00 Rs</span></h6>
                                </div>
                            </div>

                            <div class="row mt-5" style="width:95%;margin:0 auto;">
                                <div class="col-lg-12">
                                    <textarea name="" class="form-control" id=""></textarea>
                                </div>
                            </div> 
                        </div>
                    </div>
                </div>
                <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">Pay Amount
                                </h4>
                            </div>
                        </div>
                        <div class="iq-card-body" style="overflow:auto;">
                            <div class="row">

                                <div class="col-lg-3">
                                    <div class="form-group">
                                        <label for="" class="label-control">Debit Account:</label>
                                        <?php
                                        $query = "SELECT id, bank_name FROM banks";
                                        $stmt = $conn->prepare($query);
                                        $stmt->execute();
                                        $banks = $stmt->fetchAll(PDO::FETCH_ASSOC);
                                        ?>
                                        <select name="bank_id" class="form-control" id="bank-select">
                                            <option selected disabled>None</option>
                                            <?php
                                            foreach ($banks as $bank) {
                                                echo '<option value="' . $bank['id'] . '">' . $bank['bank_name'] . '</option>';
                                            }
                                            ?>
                                        </select>
                                    </div>
                                </div>

                                <div class="col-lg-3">
                                    <label for="" class="control-label">Discount Amount:</label>
                                    <input type="text" name="discount_amount" class="form-control" placeholder="0.00" id="discount-amount">
                                </div>
                                <div class="col-lg-6">
                                    <label for="" class="control-label">Details:</label>
                                    <input type="text" name="shipping_detail" class="form-control"
                                        placeholder="Enter Shipping Details" id="">
                                </div>
                                <div class="col-lg-3">
                                    <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" id="amount-container" style="display:none;">
                                    <div class="form-group">
                                        <label for="" class="label-control">Amount:*</label>
                                        <input type="number" class="form-control" name="amount" placeholder="0.00" id="payment-amount">
                                    </div>
                                </div>

                                <script>
                                    document.getElementById('bank-select').addEventListener('change', function() {
                                        var amountContainer = document.getElementById('amount-container');
                                        if (this.value) {
                                            amountContainer.style.display = 'block';
                                        } else {
                                            amountContainer.style.display = 'none';
                                        }
                                    });
                                </script>

                                <div class="col-lg-12" style="display: none;">
                                    <textarea name="note" class="form-control" id=""></textarea>
                                </div>
                                <hr>
                                <div>
                                    <p><strong>Payment due:</strong> <span id="payment-due">0.00</span></p>
                                   <button class="btn btn-primary" id="saveBtn">Save</button>

                                </div>
                            </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    </form>
    </div>
    </div>
    </div>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

    <script>
$(document).ready(function() {
    var addedProductIds = new Set(); // track already added products

    // Function to renumber rows
    function renumberRows() {
        $('#product-table tbody tr').each(function(index) {
            $(this).find('.row-number').text(index + 1);
        });
    }

    // Function to perform search
    function performSearch(search) {
        $.ajax({
            type: 'POST',
            url: 'search_products.php',
            data: { search: search },
            success: function(response) {
                console.log('Search response:', response); 

                if (response.includes('Product not found') || response.trim().length === 0) {
                    $('#product-list').hide();
                } else {
                    $('#product-list').html(response).show();

                    var products = $('#product-list .product-item');

                    // Auto-add if only 1 product or exact match
                    if (products.length === 1) {
                        var prodId = $(products[0]).data('id');
                        if (!addedProductIds.has(prodId)) {
                            $(products[0]).trigger('click');
                        }
                    } else {
                        var exactMatch = null;
                        products.each(function() {
                            if ($(this).text().trim().toLowerCase() === search.toLowerCase()) {
                                exactMatch = $(this);
                                return false; // break loop
                            }
                        });

                        if (exactMatch) {
                            var prodId = $(exactMatch).data('id');
                            if (!addedProductIds.has(prodId)) {
                                $(exactMatch).trigger('click');
                            }
                        }
                    }
                }
            }
        });
    }

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

    // Initial search if input has value
    var initialSearch = $('#product-search').val().trim();
    if (initialSearch.length > 0) {
        performSearch(initialSearch);
    }

    // Click event for product item
    $(document).on('click', '.product-item', function() {
        var productId = $(this).data('id');

        // Prevent duplicate add
        if (addedProductIds.has(productId)) return;
        addedProductIds.add(productId);

        var currentRowCount = $('#product-table tbody tr').length;

        $.ajax({
            type: 'POST',
            url: 'get_product.php',
            data: { 
                id: productId,
                row_number: currentRowCount + 1
            },
            success: function(response) {
                $('#product-table tbody').append(response);
                $('#product-list').hide();
                $('#product-search').val('').trigger('change');
                updateTotals();
                renumberRows();
            }
        });
    });

    // Update row totals
    $('#product-table').on('input', '.quantity, .discount, .profit-margin, .purchase-price, .fair_price', function () {
        updateRow($(this).closest('tr'));
        updateTotals();
    });

    // Remove row
    $(document).on('click', 'ion-icon[name="trash-outline"]', function() {
        var removedId = $(this).closest('tr').data('product-id');
        if (removedId) addedProductIds.delete(removedId); // remove from added list
        $(this).closest('tr').remove();
        updateTotals();
        renumberRows();
    });



    function updateRow(row) {
        var purchasePrice = parseFloat(row.find('.purchase-price').val()) || 0;
        var quantity = parseFloat(row.find('.quantity').val()) || 1;
        var fairCost = parseFloat(row.find('.fair_price').val()) || 0;

        var discountField = row.find('.discount');
        var discountPercent = parseFloat(discountField.val());
        if (isNaN(discountPercent)) {
            discountPercent = 0;
            discountField.val(0); 
        }

        var userProfitMarginPercent = parseFloat(row.find('.profit-margin').val()) || 0;

        // Calculate cost before tax & discount
        var unitCostBeforeDiscount = purchasePrice;
        var unitCostBeforeTax = (unitCostBeforeDiscount * (1 - discountPercent / 100)) + fairCost; 

        var lineTotal = unitCostBeforeTax * quantity; 

        var unitSellingPrice = unitCostBeforeTax * (1 + userProfitMarginPercent / 100);

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

    function updateTotals() {
        var totalItems = 0;
        var netTotalAmount = 0;
        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;
        var paymentAmount = parseFloat($('#payment-amount').val()) || 0;
        var paymentDue = 0;

        $('#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;
        });

        purchaseTotal = netTotalAmount;

        if (discountType === 'Fixed') {
            appliedDiscount = discountAmount;
            purchaseTotal -= appliedDiscount;
        } else if (discountType === 'Percentage') {
            appliedDiscount = (purchaseTotal * (discountAmount / 100));
            purchaseTotal -= appliedDiscount;
        }

        purchaseTotal += shippingCharges;
        paymentDue = purchaseTotal - paymentAmount;

        $('#total-items').text(totalItems);
        $('#net-total-amount').text(netTotalAmount.toFixed(2) + ' ₨');
        $('#applied-discount').text(appliedDiscount.toFixed(2) + ' Rs');
        $('#purchase-total').text(purchaseTotal.toFixed(2) + ' ₨');
        $('#payment-due').text(paymentDue.toFixed(2) + ' Rs');
    }

    $('#product-table').on('click', 'ion-icon[name="trash-outline"]', function () {
        $(this).closest('tr').remove();
        updateTotals();
    });

    $('#discount-type, #discount-amount, #shipping-charges, #payment-amount').on('input change', function () {
        updateTotals();
    });

    $('#product-table tbody tr').each(function () {
        updateRow($(this)); 
    });

    $('.discount').each(function () {
        $(this).val(0).trigger('input'); 
    });

    updateTotals();
});
       $(document).ready(function() {

    // Real-time reference number check
    $('#ref_no').on('input', function() {
        var refNo = $(this).val();
        if (refNo) {
            $.ajax({
                type: 'GET',
                url: 'check_ref_no.php',
                data: { ref_no: refNo },
                success: function(response) {
                    var result = JSON.parse(response);
                    if (result.exists) {
                        $('#ref_no').css('border', '1px solid red');
                        $('#ref_no-message').text('Reference number already exists. Please choose a different oneww.').css('color', 'red');
                    } else {
                        $('#ref_no').css('border', '1px solid green');
                        $('#ref_no-message').text('Reference number is available.').css('color', 'green');
                    }
                },
                error: function() {
                    alert('An error occurred while checking the reference number.');
                }
            });
        } else {
            $('#ref_no').css('border', '1px solid #ccc');
            $('#ref_no-message').text('');
        }
    });

    // Submit form
    $('#searchForm').on('submit', function(event) {
        event.preventDefault();

        var supplierId = $('#supplier').val();
        var refNo = $('#ref_no').val();
        var purchaseDate = $('input[name="purchase_date"]').val();
        var fileInput = $('#file-input').val();

        // Validation
        if (!refNo) { alert('Please enter a reference number.'); return; }

        var isRefNoValid = false;
        $.ajax({
            type: 'GET',
            url: 'check_ref_no.php',
            data: { ref_no: refNo },
            async: false,
            success: function(response) {
                var result = JSON.parse(response);
                if (result.exists) {
                    alert('Error: Reference number already exists. Please choose a different one.');
                    $('#ref_no').css('border', '1px solid red');
                    isRefNoValid = false;
                } else {
                    isRefNoValid = true;
                }
            },
            error: function() {
                alert('An error occurred while checking the reference number.');
            }
        });

        if (!isRefNoValid) return;
        if (!supplierId) { alert('Please select a supplier.'); return; }
        if (!purchaseDate) { alert('Please select a purchase date.'); return; }
        // if (!fileInput) { alert('Please upload a document.'); return; }

        // Disable submit button only after all validations pass
        $('#saveBtn').prop('disabled', true).text('Saving...');

        var formData = new FormData(this);

        // Collect product table data
        var productRows = $('#product-table tbody tr');
        var productData = {
            product_id: [], quantity: [], pp_without_discount: [], discount_percent: [],
            purchase_price: [], profit_margin: [], sell_price: [], fair_price: [], drum: [],
            color_id: [], size_id: [], barcode: []
        };

        productRows.each(function() {
            var row = $(this);
            productData.product_id.push(row.find('input[name="product_id[]"]').val());
            productData.quantity.push(row.find('input[name="quantity[]"]').val());
            productData.pp_without_discount.push(row.find('input[name="pp_without_discount[]"]').val());
            productData.discount_percent.push(row.find('input[name="discount_percent[]"]').val());
            productData.purchase_price.push(row.find('input[name="purchase_price[]"]').val());
            productData.profit_margin.push(row.find('input[name="profit_margin[]"]').val());
            productData.sell_price.push(row.find('input[name="sell_price[]"]').val());
            productData.fair_price.push(row.find('input[name="fair_price[]"]').val());
            productData.drum.push(row.find('input[name="drum[]"]').val());
            productData.color_id.push(row.find('select[name="color_id[]"]').val());
            productData.size_id.push(row.find('select[name="size_id[]"]').val());
            productData.barcode.push(row.find('input[name="barcode[]"]').val());
        });

        // Append product data to FormData
        for (var key in productData) {
            formData.append(key, JSON.stringify(productData[key]));
        }

        // Append other form fields
        formData.append('supplier_id', supplierId);
        formData.append('amount', $('#payment-amount').val());
        formData.append('bank_id', $('select[name="bank_id"]').val());
        formData.append('voucher_no', $('#voucher_no').val());

        // Submit via AJAX
        $.ajax({
            type: 'POST',
            url: 'submit_purchase.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_purchase.php'; }, 1000);
                    } else {
                        alert('Error: ' + result.message);
                        $('#saveBtn').prop('disabled', false).text('Save'); // re-enable on error
                    }
                } catch (error) {
                    console.error("JSON Parsing Error:", error);
                    console.error("Response received:", response);
                    alert("Error: Invalid response from server. Check console for details.");
                    $('#saveBtn').prop('disabled', false).text('Save');
                }
            },
            error: function() {
                alert('An error occurred while submitting the form.');
                $('#saveBtn').prop('disabled', false).text('Save');
            }
        });

    });





        });
    </script>


<script> 
// Block Enter key globally
$(document).on('keydown', function(e) {
    if (e.key === "Enter" || e.keyCode === 13) {
        e.preventDefault(); 
        return false;      
    }
});

</script>
    <!-- Wrapper END -->
    <!-- Footer -->
    <footer class="iq-footer">
        <div class="container-fluid">
            <div class="row">
                <div class="col-lg-6">
                    <ul class="list-inline mb-0">
                        <li class="list-inline-item"><a href="privacy-policy.html">Privacy Policy</a></li>
                        <li class="list-inline-item"><a href="terms-of-service.html">Terms of Use</a></li>
                    </ul>
                </div>
                <div class="col-lg-6 text-right">
                    Copyright <span id="copyright">
                        <script>
                            document.getElementById('copyright').appendChild(document.createTextNode(new Date()
                                .getFullYear()))
                        </script>
                    </span> <a href="#">Vito</a> All Rights Reserved.
                </div>
            </div>
        </div>
    </footer>
    <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>