<?php
include("../db/cn.php");

// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (isset($_SESSION['user_name'], $_SESSION['user_role'], $_SESSION['outlet_name'], $_SESSION['outlet_address'])) {
    $userName = $_SESSION['user_name'];
    $userRole = $_SESSION['user_role'];
    $outlet_address = $_SESSION['outlet_address'];
    $outlet_name = $_SESSION['outlet_name'];
} else {
    // Handle the case where session variables are not set
    exit("Session variables are missing.");
}

// Check if order_id is provided via GET request
if (!isset($_GET["order_id"])) {
    exit("Order ID is missing.");
}

$order_id = mysqli_real_escape_string($connection, $_GET["order_id"]);

$products_query = "SELECT * FROM log_user_sales WHERE order_id = '$order_id'";
$products_result = mysqli_query($connection, $products_query);

// Store fetched products in an array
$products = array();
while ($row = mysqli_fetch_array($products_result)) {
    $product = array(
        "name" => $row["product_name"],
        "product_id" => $row["product_id"],
        "unit_price" => $row["product_price"],
		"discount" => $row["discount"],
        "total_price" => $row["net_amount"],
        "supplier_name" => $row["supplier_name"],
        "company" => $row["company"],
        "company_category" => @$row["company_category"],
        "total_quantity" => $row["product_quantity"]
    );
    $products[] = $product;
}

// Check if the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
    // Initialize variables from form fields or set default values
    $dateTime = $_POST['date_time'] ?? date('Y-m-d');
    $taxAmount = $_POST['tax_amount'] ?? 0;
    $totalAmount = $_POST['total_input'] ?? 0;
    $paidBy = $_POST['paid_by'] ?? '';
    $customerName = $_POST['customer_name'] ?? '';
    $customerPhone = $_POST['customer_phone'] ?? '';
    $discountedAmount = $_POST['discounted'] ?? '';
    $discount = $_POST['discount_amount'] ?? '';
    $discountper = $_POST['discount_percentage'] ?? '';
    $cashAmount = $_POST['cash_amount'] ?? '';
    $changeAmount = $_POST['change_amount'] ?? '';

    // Initialize arrays from form fields or set default values
    $productIds = $_POST['productIds'] ?? [];
    $productNames = $_POST['productNames'] ?? [];
    $productPrices = $_POST['productPrices'] ?? [];
    $productQuantities = $_POST['productQuantities'] ?? [];
    $retailPrices = $_POST['retailPrices'] ?? [];
    $supplierNames = $_POST['supplierNames'] ?? [];
    $companyCategories = $_POST['companyCategories'] ?? [];
    $companies = $_POST['companies'] ?? [];

    // Loop through product details and insert into database
    for ($i = 0; $i < count($productIds); $i++) {
        $productId = mysqli_real_escape_string($connection, $productIds[$i]);
        $productName = mysqli_real_escape_string($connection, $productNames[$i]);
        $productPrice = mysqli_real_escape_string($connection, $productPrices[$i]);
        $productQuantity = mysqli_real_escape_string($connection, $productQuantities[$i]);
        @$productTotal = mysqli_real_escape_string($connection, $retailPrices[$i]);
        $supplierName = mysqli_real_escape_string($connection, $supplierNames[$i]);
        $companyCategory = mysqli_real_escape_string($connection, $companyCategories[$i]);
        $company = mysqli_real_escape_string($connection, $companies[$i]);

        $insert_query = "INSERT INTO order_detail (order_id, customer_name, phone_number, sale_by, paid_by, product_id, product_name, product_price, product_quantity, product_total, tax_amount, discount_amount, discounted, discount_per, cash_amount, change_amount, total_amount, date_time, order_status, outlet_name, user_role, outlet_address) VALUES ('$order_id', '$customerName', '$customerPhone', '$userName', '$paidBy', '$productId', '$productName', '$productPrice', '$productQuantity', '$productTotal', '$taxAmount', '$discount', '$discountedAmount', '$discountper', '$cashAmount', '$changeAmount', '$totalAmount', '$dateTime', 'Refund', '$outlet_name', '$userRole', '$outlet_address')";
        
        $result = mysqli_query($connection, $insert_query);
        if (!$result) {
            echo "Error: " . mysqli_error($connection);
            break;
        }
		
		
		
        // Update total_quantity in products
        $update_query = "UPDATE products SET quantity = quantity + $productQuantity WHERE product_name = '$productName'";
        
        $update_result = mysqli_query($connection, $update_query);
        if (!$update_result) {
            echo "Error updating total_quantity: " . mysqli_error($connection);
            break;
        }

		
    }
echo '<script type="text/javascript">window.location.href="orders_detail_v.php";</script>';
    // Redirect after all products are processed
  // header("Location: orders_detail_v.php");
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Amazon fashion Store</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
        html, body {
            height: 100%;
            margin: 0;
            padding: 0;
            font-family: Arial, sans-serif;
            background:#f2f2f2;
            background-size: cover;
            background-position: center;
            background-attachment: fixed;
        }

        .wrapper {
            display: flex;
            flex-direction: column;
            height: 100%;
        }

        .header,
        .footer {
            width: 100%;
            height: 70px;
                    background: linear-gradient(270deg, #060606, #3C2F23);
            color: #fff;
            text-align: ;
       /* Center text vertically */
        }

        .content {
            flex: 1;
            overflow-y: auto;
            padding: 10px;
        }

        #product-container-wrapper {
            max-height: 300px;
            overflow-y: auto;
        }

        .dropdown-options {
            display: none;
            position: absolute;
            z-index: 1000;
            width: calc(89% - 2px);
            max-height: 200px;
            overflow-y: auto;
            border: 1px solid #ccc;
            background-color: #fff;
        }

        .option {
            padding: 5px 10px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .option:hover,
        .option.highlight {
            background-color: #353535;
            color: #fff;
        }

        @keyframes blink {
            0% {
                opacity: 1;
            }

            50% {
                opacity: 0;
            }

            100% {
                opacity: 1;
            }
        }

        #total-amount {
            font-size: 46px;
            font-weight: 700;
            color: #0A5064;
            animation: blink 1s step-start infinite;
        }

        label {
            font-weight: 600;
        }

        .in_c {
            border: 1.5px solid #0A5064;
        }
		  img.pulse {
        width: 60px;
        height: 60px;
        animation: pulse 2s infinite;
    }
    @keyframes pulse {
        0% {
            transform: scale(1);
        }
        50% {
            transform: scale(1.2);
        }
        100% {
            transform: scale(1);
        }
    }
	.btn-success{ background:#3C2F23;
	color:#fff;
     border:1px solid #353535;	
	}
    </style>
</head>

<body>
    <div class="wrapper">
        <div class="header row">
        <div class="col-sm-3">
<a href="orders_detail_v.php"><img class="pulse" src="img/Amazon Fashion STORE1.png" width="40" height="45"></a>
        </div>
<div class="col-sm-6">
<h3 style="color:#fff; text-align:center;line-height:70px; font-weight:600;">AMAZON FASHION STORE</h3>
 </div>    
 <div class="col-sm-3"></div>
        </div>

        <div class="content">
            <div class="container">
<form action="orderrefund.php?order_id=<?php echo $order_id?>" method="post" enctype="multipart/form-data">
    <div class="container">
  
        <div class="row" style=" border:1px solid #0A5064; border-radius:7px; background:#FFF;padding:10px;">
            <div class="col-sm-5">
            <br>
                <div class="form-group" style=" border:1px solid #ccc; border-radius:7px; background:#EFEFE5;padding:10px;">
                    <input type="text" id="searchInput" class="search-input form-control in_c" placeholder="Enter The Product" />
                    <div id="filteredOptions" class="dropdown-options"></div>
                </div>
            </div>
            <div class="col-sm-4"></div>
            <div class="col-sm-3" style="background:#353535; text-align:center; padding:15px;border-radius:10px;border:1px solid #0A5064; ">
                <span style="font-size:46px; font-weight:700; color:#fff; " id="total-amount">0.00</span>
            </div>
        </div>
         <br>
        <div class="row">
            <div class="col-sm-12" id="product-container-wrapper" style="height:320px;  border:1px solid #0A5064; border-radius:7px; background:#F5F5F5;padding:10px;">
                <table id="cart-table" class="table table-striped table-sm text-center">
                    <thead>
                        <tr class="bg-dark text-white" style="border-radius:10px;">
                        <th>Total.Qty</th>
                        <th>Item Code</th>
                            <th>Description</th>
                            <th> Refund.Qty</th>
                            <th>Unit Price</th>
                            <th>Disc</th>
                            <th>Amount</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Cart items will be dynamically added here -->
                    </tbody>
                </table>
                <!-- Hidden inputs for additional required fields -->
      
        <input type="hidden" name="outlet_name" value="<?php echo $outlet_name; ?>" />
        <input type="hidden" name="login_user" value="<?php echo $userName; ?>" />
        <input type="hidden" name="user_role" value="<?php echo $userRole; ?>" />
        <input type="hidden" name="outlet_address" value="<?php echo $outlet_address; ?>" />
        <input type="hidden" name="date_time" value="<?php echo date('Y-m-d'); ?>" />

                <div id="hidden-fields-container"></div>
            </div>
        </div>
       
        
        <div class="row" style="margin-top:30px;">
    <div class="col-sm-12" style="background:#F5F5F5; padding:18px; border:1px solid #0A5064; border-radius:7px;">
        <div class="row">
            <div class="col-sm-2">
                <div class="form-group">
                    <label>Total</label>
                    <input type="number" id="total-input"  name="total_input" class="form-control in_c" readonly />
                </div>
            </div>
            <div class="col-sm-2">
                <div class="form-group">
                    <label>Bill Amount</label>
                    <input type="number" id="discount-input" name="discounted" class="form-control in_c" oninput="calculateResult()" />
                </div>
            </div>
            <div class="col-sm-2">
                <div class="form-group">
                    <label>Discount Amount</label>
                    <input type="number" id="result-input" name="result" class="form-control in_c" readonly />
                </div>
            </div>
            <div class="col-sm-2">
                <div class="form-group">
                    <label>Discount %</label>
                    <input type="number" id="percentage-display" name="discount_percentage" class="form-control in_c" readonly />
                </div>
            </div>
            <div class="col-sm-2">
                <div class="form-group">
                    <label>Cash Paid</label>
                    <input type="number" id="cash-input" name="cash_amount" class="form-control in_c" />
                </div>
            </div>
            <div class="col-sm-2">
                <div class="form-group">
                    <label>Cash Return</label>
                    <input type="number" id="balance-input" name="change_amount" class="form-control in_c" readonly />
                </div>
            </div>
        </div>
        <br>
        <div class="row">
            <div class="col-sm-2">
                <div class="form-group">
                    <label>S.Tax(0%)</label>
                    <input type="text" class="form-control in_c" name="tax_amount" value="0" readonly />
                </div>
            </div>
            <div class="col-sm-2">
                <div class="form-group">
                    <label>Customer Name</label>
                    <input type="text" class="form-control in_c" name="customer_name" />
                </div>
            </div>
            <div class="col-sm-2">
                <div class="form-group">
                    <label>Phone</label>
                    <input type="text" class="form-control in_c" name="customer_phone" />
                </div>
            </div>
            <div class="col-sm-2">
                <div class="form-group">
                    <label>Method</label>
                    <select name="paid_by" class="form-control">
                        <option value="cash">Cash</option>
                        <option value="credit">Credit</option>
                        <option value="other">Other</option>
                    </select>
                </div>
            </div>
            <div class="col-sm-3">
                <br>
                <button id="bill-button" class="btn btn-success form-control" type="submit" name="submit">Refund</button>
                
                <!--<button id="hold-bill-button" class="btn btn-dark" type="submit" name="hold_order">Hold</button>-->
            </div>
        </div>
    </div>
</div>


        <br>
        <div class="row">
            <div class="col-sm-5"></div>
            <div class="col-sm-2"></div>
            <div class="col-sm-5">
                
            </div>
        </div>
        <div class="row">
            <div class="col-sm-12 text-left">
               
            </div>
        </div>
    </div>
</form>
            </div>
        </div>

       
    </div>
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function calculateResult() {
        var total = document.getElementById('total-input').value;
        var discount = document.getElementById('discount-input').value;
        
        // Calculate the result
        var result = parseFloat(total) - parseFloat(discount);
        
        // Display the result in the result input field
        document.getElementById('result-input').value = result.toFixed(2);
    }


$(document).ready(function () {
    var products = <?php echo json_encode($products); ?>;
    var $searchInput = $('#searchInput');
    var $filteredOptions = $('#filteredOptions');
    var $cartTableBody = $('#cart-table tbody');
    var totalAmount = 0;

    $searchInput.on('input', function () {
        var value = $(this).val().toLowerCase();
        var html = '';
        products.forEach(function (product) {
            if (product.name.toLowerCase().includes(value)) {
                html += '<div class="option" data-value="' + product.name + '">' + product.name + '</div>';
            }
        });
        $filteredOptions.html(html);
        if (value.length > 0) {
            $filteredOptions.show();
            $filteredOptions.find('.option').first().addClass('highlight');
        } else {
            $filteredOptions.hide();
        }
    });

    $searchInput.on('keydown', function (e) {
        var $options = $('.option');
        var currentIndex = $options.index($('.option.highlight'));
        switch (e.which) {
            case 40: // Down Arrow
                e.preventDefault();
                if (currentIndex === -1 || currentIndex === $options.length - 1) {
                    $options.first().addClass('highlight').siblings().removeClass('highlight');
                } else {
                    $options.eq(currentIndex + 1).addClass('highlight').siblings().removeClass('highlight');
                }
                break;
            case 38: // Up Arrow
                e.preventDefault();
                if (currentIndex === -1 || currentIndex === 0) {
                    $options.last().addClass('highlight').siblings().removeClass('highlight');
                } else {
                    $options.eq(currentIndex - 1).addClass('highlight').siblings().removeClass('highlight');
                }
                break;
            case 13: // Enter
                if (currentIndex !== -1) {
                    var selectedProduct = $options.eq(currentIndex).data('value');
                    addProductToCart(selectedProduct);
                    $searchInput.val('');
                    $filteredOptions.hide();
                    return false; // Prevent form submission
                }
                break;
        }
    });

    $(document).on('click', '.option', function (e) {
        e.stopPropagation(); // Prevent event from propagating to parent elements
        var selectedProduct = $(this).data('value');
        addProductToCart(selectedProduct);
        $searchInput.val('');
        $filteredOptions.hide();
    });

    function addProductToCart(productName) {
        var product = products.find(function (p) {
            return p.name === productName;
        });

        if (product) {
            var unitPrice = parseFloat(product.unit_price);
            var productId = product.product_id;
            var supplierName = product.supplier_name;
            var companyCategory = product.company_category;
            var company = product.company;
            var totalQuantity = product.total_quantity;
			var discount = product.discount;
			var totalP = product.tota_price;
            var $existingRow = $cartTableBody.find('tr[data-product="' + product.name + '"]');
            if ($existingRow.length > 0) {
                var $qtyInput = $existingRow.find('.qty-input');
                var newQty = parseInt($qtyInput.val()) + 1;
                $qtyInput.val(newQty);
                var newTotal = unitPrice - discount;
                $existingRow.find('.total-price').text(newTotal.toFixed(2));

                // Update hidden input fields
                var productIndex = $existingRow.index();
                $('input[name="productQuantities[]"]').eq(productIndex).val(newQty);
            } else {
                var newTotal = unitPrice  - discount;
                var row = '<tr data-product="' + product.name + '">' +
                    '<td style="color:#709806;font-weight:700;">' + totalQuantity + '</td>' +
                    '<td style="color:#709806;font-weight:700;">' + productId + '</td>' +
                    '<td style="font-weight:600;">' + product.name + '</td>' +
                    '<td><center><input type="number" class="qty-input form-control" value="1" min="1" style="width:100px;" /></center></td>' +
                    '<td>' + unitPrice + '</td>' +
					'<td>' + discount + '</td>' +
                    '<td class="total-price">' + newTotal.toFixed(2) + '</td>' +
                    '<td><button class="btn btn-danger btn-sm remove-btn btn-sm">x</button></td>' +
                    '</tr>';

                $cartTableBody.append(row);

                // Update hidden input fields with product data
                $('<input>').attr({
                    type: 'hidden',
                    name: 'productIds[]',
                    value: productId
                }).appendTo('#hidden-fields-container');
                $('<input>').attr({
                    type: 'hidden',
                    name: 'productNames[]',
                    value: product.name
                }).appendTo('#hidden-fields-container');
                $('<input>').attr({
                    type: 'hidden',
                    name: 'productPrices[]',
                    value: unitPrice
                }).appendTo('#hidden-fields-container');
                $('<input>').attr({
                    type: 'hidden',
                    name: 'productQuantities[]',
                    value: 1
                }).appendTo('#hidden-fields-container');
                $('<input>').attr({
                    type: 'hidden',
                    name: 'supplierNames[]',
                    value: supplierName
                }).appendTo('#hidden-fields-container');
                $('<input>').attr({
                    type: 'hidden',
                    name: 'companyCategories[]',
                    value: companyCategory
                }).appendTo('#hidden-fields-container');
                $('<input>').attr({
                    type: 'hidden',
                    name: 'companies[]',
                    value: company
                }).appendTo('#hidden-fields-container');
            }

            totalAmount += unitPrice - discount;
            $('#total-amount').text(totalAmount.toFixed(2));
            $('#total-input').val(totalAmount.toFixed(2));
            calculateDiscountedTotal();
        }
    }

    // Add event listener for quantity input change
    $cartTableBody.on('change', '.qty-input', function () {
        var $row = $(this).closest('tr');
        var newQty = parseInt($(this).val());
        var productName = $row.data('product');
        var product = products.find(function (p) {
            return p.name === productName;
        });
        var unitPrice = parseFloat(product.unit_price);
        var newTotal = unitPrice * newQty;
        $row.find('.total-price').text(newTotal.toFixed(2));

        // Update hidden input fields
        var productIndex = $row.index();
        $('input[name="productQuantities[]"]').eq(productIndex).val(newQty);

        // Recalculate total amount
        var totalAmount = 0;
        $cartTableBody.find('.total-price').each(function () {
            totalAmount += parseFloat($(this).text());
        });
        $('#total-amount').text(totalAmount.toFixed(2));
        $('#total-input').val(totalAmount.toFixed(2));
        calculateDiscountedTotal();
    });

    $('#discount-input').on('input', function () {
        calculateDiscountedTotal();
        calculateDiscountPercentage();
    });

    function calculateDiscountPercentage() {
        var totalAmount = parseFloat($('#total-input').val());
        var discountedAmount = parseFloat($('#discount-input').val());

        if (!isNaN(totalAmount) && !isNaN(discountedAmount) && totalAmount > 0) {
            var discountPercentage = ((totalAmount - discountedAmount) / totalAmount) * 100;
            $('#percentage-display').val(discountPercentage.toFixed(2));
        } else {
            $('#percentage-display').val('0.00');
        }
    }

    function calculateDiscountedTotal() {
        var totalAmount = parseFloat($('#total-input').val()) || 0;
        var discountAmount = parseFloat($('#discount-input').val()) || 0;
        var discountedTotal = totalAmount - discountAmount;

        $('#discounted-input').val(discountedTotal.toFixed(2));
        $('#total-after-discount').text(discountedTotal.toFixed(2));
    }

    $('#cash-input').on('input', function () {
        var cashAmount = parseFloat($(this).val()) || 0;
        var discountedTotal = parseFloat($('#discounted-input').val()) || 0;
        var balance = cashAmount - discountedTotal;

        $('#balance-input').val(balance.toFixed(2));
    });

    $(document).on('click', '.remove-btn', function () {
        var $row = $(this).closest('tr');
        var totalPrice = parseFloat($row.find('.total-price').text());
        totalAmount -= totalPrice;
        $('#total-amount').text(totalAmount.toFixed(2));
        $('#total-input').val(totalAmount.toFixed(2));
        $row.remove();
        calculateDiscountedTotal();
    });

    $(document).on('input', '.qty-input', function () {
        var $row = $(this).closest('tr');
        var qty = parseInt($(this).val());
        var unitPrice = parseFloat($row.find('td:nth-child(5)').text());
        var newTotal = qty * unitPrice;
        $row.find('.total-price').text(newTotal.toFixed(2));

        totalAmount = 0;
        $cartTableBody.find('.total-price').each(function () {
            totalAmount += parseFloat($(this).text());
        });

        $('#total-amount').text(totalAmount.toFixed(2));
        $('#total-input').val(totalAmount.toFixed(2));
        calculateDiscountedTotal();
    });

    $('#discount-input').on('input', function () {
        calculateDiscountedTotal();
        calculateDiscountPercentage();
    });

    function calculateDiscountPercentage() {
        var totalAmount = parseFloat($('#total-input').val());
        var discountedAmount = parseFloat($('#discount-input').val());

        if (!isNaN(totalAmount) && !isNaN(discountedAmount) && totalAmount > 0) {
            var discountPercentage = ((totalAmount - discountedAmount) / totalAmount) * 100;
            $('#percentage-display').val(discountPercentage.toFixed(2));
        } else {
            $('#percentage-display').val('0.00');
        }
    }

    function calculateDiscountedTotal() {
        var discountAmount = parseFloat($('#discount-input').val());
        if (!isNaN(discountAmount) && discountAmount > 0) {
            var discountedTotal = totalAmount - discountAmount;
            $('#discounted-input').val(discountedTotal.toFixed(2));
            $('#total-after-discount').text(discountedTotal.toFixed(2));
        } else {
            $('#discounted-input').val(totalAmount.toFixed(2));
            $('#total-after-discount').text(totalAmount.toFixed(2));
        }
    }

    $('#cash-input').on('input', function () {
        var cashAmount = parseFloat($(this).val()) || 0;
        var discountedTotal = parseFloat($('#discount-input').val()) || 0;

        if (discountedTotal > 0) {
            var balance = cashAmount - discountedTotal;
        } else {
            var totalAmount = parseFloat($('#total-input').val()) || 0;
            var balance = cashAmount - totalAmount;
        }

        $('#balance-input').val(balance.toFixed(2));
    });

    // New event listener for Bill Amount field
    $('#bill-amount').on('input', function () {
        var totalAmount = parseFloat($('#total-amount').val()) || 0;
        var billAmount = parseFloat($(this).val()) || 0;
        var discountAmount = totalAmount - billAmount;

        $('#discount-amount').val(discountAmount.toFixed(2));
    });
});

</script>
</body></html> 