<?php
include("db/cn.php"); // Include your database connection file

// Define and set the $order_id variable
$order_id = ''; // Set the order ID according to your logic

if(isset($_SESSION['user_name']) && isset($_SESSION['user_role']) && isset($_SESSION['outlet_name'])
 && isset($_SESSION['outlet_address'])) {
    $userName = $_SESSION['user_name'];
    $userRole = $_SESSION['user_role'];
    $outlet_address = $_SESSION['outlet_address'];
    $outlet_name = $_SESSION['outlet_name'];
}

// Initialize total, tax, and discount variables
$total = 0;
$discount = 0;
$tax_percentage = 10; // Assuming tax percentage is fixed
$tax = 0;

// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Retrieve data from the POST request
    $productRows = array(); // Initialize an array to store product data

    // Check if necessary POST variables are set
    if (isset($_POST['product_names']) && isset($_POST['product_quantities']) && isset($_POST['product_prices'])) {
        // Retrieve product data from the POST request
        $productNames = $_POST['product_names'];
        $productQuantities = $_POST['product_quantities'];
        $productPrices = $_POST['product_prices'];

        // Loop through the product data and create an array of product rows
        for ($i = 0; $i < count($productNames); $i++) {
            $productRows[] = array(
                'name' => $productNames[$i],
                'quantity' => $productQuantities[$i],
                'price' => $productPrices[$i]
            );
        }

        // Loop through product rows to calculate total amount
        foreach ($productRows as $product) {
            $total += $product['quantity'] * $product['price'];
        }

        // Calculate tax
        $tax = ($total * $tax_percentage) / 100;

        // Retrieve user and outlet information (assuming it's stored in session)
        $userName = isset($_SESSION['user_name']) ? $_SESSION['user_name'] : '';
        $outlet_name = isset($_SESSION['outlet_name']) ? $_SESSION['outlet_name'] : '';
        $outlet_address = isset($_SESSION['outlet_address']) ? $_SESSION['outlet_address'] : '';
    } else {
        // Handle case where necessary POST variables are not set
        echo "";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>POS Invoice</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        @media print {
            .buttons {
                display: none; /* Hide buttons in print mode */
            }
        }
    </style>
</head>
<body>
<div class="container my-4">
    <div class="text-center mb-4">
        <img src="img/print_logo.jpg" alt="Logo" width="40" height="40" class="mb-2">
        <h2 class="mb-1">HASSAN PHARMACY</h2>
        <p class="mb-0" style="font-size:16px; font-weight:700;">SADDIQE HOSPITAL STADIUM ROAD, KWL</p>
        <p class="mb-0">Cell: 0321-6898403</p>
        <p class="mb-0"><?php echo $_POST['orderid']; ?></p>
    </div>

    <div class="mb-0" style="font-size:14px;">
        <h6>Customer Name: <span class="text-capitalize"><?php echo $_POST['customer']; ?></span></h6>
        <h6>Customer Phone: <span class="text-capitalize"><?php echo $_POST['phone']; ?></span></h6>
        <h6>Payment: <span class="text-capitalize"><?php echo $_POST['paid_by']; ?></span></h6>
    </div>

    <div class="table-responsive mb-1">
        <table class="table table-stripped table-sm text-center">
            <thead>
                <tr>
                    <th>Product</th>
                    <th>Qty</th>
                    <th>Price</th>
                    <th>Amount</th>
                </tr>
            </thead>
            <tbody style="font-size:14px;">
                <?php
                if (isset($_POST['product_name'])) {
                    for ($i = 0; $i < count($_POST['product_name']); $i++) {
                        $amount = $_POST['product_quantity'][$i] * $_POST['product_price'][$i];
                        echo "<tr>";
                        echo "<td class='text-capitalize'>" . $_POST['product_name'][$i] . "</td>";
                        echo "<td>" . $_POST['product_quantity'][$i] . "</td>";
                        echo "<td>" . $_POST['product_price'][$i] . "</td>";
                        echo "<td>" . $amount . "</td>";
                        echo "</tr>";
                    }
                }
                ?>
            </tbody>
        </table>
    </div>

    <?php if ($_SERVER["REQUEST_METHOD"] == "POST"): ?>
        <?php
        if (isset($_POST['product_names']) && isset($_POST['product_quantities']) && isset($_POST['product_prices'])) {
            $discount = isset($_POST['discount_amount']) ? $_POST['discount_amount'] : 0;
            $total_with_tax = $total + $tax - $discount;
        }
        ?>
        <div class="row ">
            <div class="col-12">
                <div class=" mb-1 text-dark">
                    <h6>Total: <span class="float-end">Rs <?php echo isset($_POST['total_amount']) ? $_POST['total_amount'] : 0; ?>/-</span>
                    </h6>
                </div>
                <div class="mb-0">Discount: <span class="float-end">Rs <?php echo isset($_POST['discount_amount']) ? $_POST['discount_amount'] : 0; ?>/-</span></div>
                <div class="mb-0">Cash Amount: <span class="float-end">Rs <?php echo isset($_POST['cash_amount']) ? $_POST['cash_amount'] : 0; ?>/-</span></div>
                <div>Change Amount: <span class="float-end">Rs <?php echo isset($_POST['change_amount']) ? $_POST['change_amount'] : 0; ?>/-</span></div>
            </div>
        </div>
    <?php else: ?>
        <p class="text-danger">Error: Form not submitted.</p>
    <?php endif; ?>

    <div class="mb-0">
        <h6>Generated By: <span class="text-capitalize"><?php echo $_SESSION['user_role']; ?></span></h6>
    </div>

    <div class="" style="font-size:14px;">
        <h6>Notes:</h6>
        <p>1. Items will be returned with cash memo within 7 days.<br>
        2. Inhaler / loose tablets / lotion / fridge items / cosmetic items will not be returned.<br>
        3. Without sign and stamp, the bill will not be valid.</p>
    </div>

    <div class="text-center buttons">
        <button class="btn btn-primary me-2" onclick="window.print()">Print Invoice</button>
        <button class="btn btn-secondary" onclick="window.location.href='pos.php'">Exit</button>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>