<?php
include('db/cn.php');
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'];
 }
// Fetch order_id from URL
$orderId = isset($_GET['inv_id']) ? $_GET['inv_id'] : null;

$orderDetails = [];
$outletName = $loginUser = $userRole = $outletAddress = $dateTime = $totalAmount = $paidBy = $customerName = $customerPhone = $discountedAmount = $discounted = $discountPer = $cashAmount = $changeAmount = $taxAmount = null;

if ($orderId) {
    $query = "SELECT * FROM purchase WHERE inv_id = '$orderId'";
    $result = mysqli_query($connection, $query);

    if ($result && mysqli_num_rows($result) > 0) {
        $orderDetails = mysqli_fetch_all($result, MYSQLI_ASSOC);
        $order = $orderDetails[0];
        $outletName = $order['outlet_name'];
        $loginUser = $order['login_user'];
        $userRole = $order['user_role'];
        $outletAddress = $order['outlet_address'];
        $dateTime = $order['date_time'];
        $totalAmount = $order['net_amount'];
        $paidBy = $order['paid_by'];
        $customerName = $order['customer_name'];
        $customerPhone = $order['customer_phone'];
        $discountedAmount = $order['discount_amount'];
        $discounted = $order['discounted'];
        $discountPer = $order['discount_per'];
        $cashAmount = $order['cash_amount'];
        $changeAmount = $order['change_amount'];
        $taxAmount = $order['tax_amount'];
        $Area = $order['area'];
        $piece = $order['piece'];
        $labour_amount = $order['labour_amount'];
        $date_time = $order['date_time'];
    }
}

ob_end_flush();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Invoice</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <style>
        .invoice-header {
            margin-bottom: 20px;
        }
        .invoice-logo {
            width: 206px;
            height: 166px;
        }
        .invoice-details p, .invoice-summary p {
            margin-bottom: 5px;
        }
        .invoice-summary {
            margin-top: 20px;
        }
        .table th, .table td {
            text-align: center;
        }
        .no-print {
            margin-top: 20px;
        }
        .footer-note {
            margin-top: 20px;
            text-align: center;
        }
		@media print {
            .no-print {
                display: none;
            }
        }
		.hide-temporary {
            display: none;
        }
    </style>
</head>
<body>
    <div id="invoice" class="container">
        <!-- Header -->
        <div class="text-center invoice-header">
            <img src="img/HARDWARE 15.png" alt="Logo" class="invoice-logo">
            <p class="mb-0" style="font-size:25px;">کچا کھوہ روڈ عبدالحکیم</p>
            <p class="mb-0">Cell: 0343-8759922</p>
            <p class="mb-0">Cell: 0300-6880502</p>
            <p><strong>Date:</strong> <?php echo $date_time; ?></p>
        </div>

        <!-- Customer Details -->
        <div class="invoice-details mb-4">
            <p><strong>Name:</strong> <?php echo htmlspecialchars($customerName); ?></p>
            <p><strong>Phone:</strong> <?php echo htmlspecialchars($customerPhone); ?></p>
            <p><strong>Payment:</strong> <?php echo htmlspecialchars($paidBy); ?></p>
            <p class="mb-0"><strong>Invoice ID:</strong> <?php echo htmlspecialchars($orderId); ?></p>
        </div>

        <!-- Order Table -->
        <div class="mb-4">
            <table class="table table-bordered">
                <thead class="thead-light">
                    <tr>
                        <th>Product</th>
                        <th>Outline</th>
                        <th>Qty</th>
                        <th>Price</th>
                        <th>Amount</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($orderDetails as $order): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($order['product_name']); ?></td>
                        <td>
                            <?php 
                                if (!empty($order['l_feet']) && !empty($order['w_feet'])) {
                                    echo htmlspecialchars($order['l_feet']) . ' x ' . htmlspecialchars($order['w_feet']) . ' feet';
                                } elseif (!empty($order['l_inch']) && !empty($order['w_inch'])) {
                                    echo htmlspecialchars($order['l_inch']) . ' x ' . htmlspecialchars($order['w_inch']) . ' inches';
                                }
                            ?>
                        </td>
                        <td><?php echo htmlspecialchars($order['product_quantity']); ?></td>
                        <td><?php echo htmlspecialchars($order['product_price']); ?></td>
                        <td><?php echo htmlspecialchars($order['product_quantity'] * $order['product_price']); ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- Summary -->
        <?php
            $sub = mysqli_query($connection,"select SUM(net_amount) AS sub from purchase where inv_id = '$orderId'");
            $rowSub = mysqli_fetch_array($sub);
            ?>
        <div class="row">
        <div class="col-sm-4"></div>
        <div class="col-sm-4"></div>
        <div class="col-sm-4">
        <table class="table table-bordered">
        <tr>
        <td>Sub</td>
        <td>Rs <?php echo htmlspecialchars($rowSub["sub"]); ?></td>
        </tr>
        <tr>
        <td>Disc</td>
        <td>Rs <?php echo htmlspecialchars($discounted); ?></td>
        </tr>
        <tr>
        <td>Total</td>
        <td> Rs <?php echo htmlspecialchars($discountedAmount) . ".00"; ?></td>
        </tr>
        <tr>

        
        
        </table>
        </div>
        </div>
        
        

        <!-- Footer -->
        <div class="footer-note text-left" >
            <p>Generated By: Admin</p>
            <h6>Note:</h6>
            <p>Specific Items Can Be Returned OR Exchanged Within 10 Days.</p>
            <!--<h3>Thanks For Visiting.</h3>-->
        </div>

        <!-- Print and Exit Buttons -->
       <div class="text-center no-print">
            <button id="printBtn" class="btn btn-primary" onclick="window.print()">Print Invoice</button>
            <button id="downloadBtn" class="btn btn-dark" onclick="downloadPDF()">Download PDF</button>
            <button id="exitBtn" class="btn btn-secondary" onclick="window.location.href='orders_detail_v.php'">Exit</button>
        </div>
    </div>
  <script>
        async function downloadPDF() {
            const { jsPDF } = window.jspdf;
            const doc = new jsPDF();
            
            // Get the content of the invoice div
            const invoiceElement = document.getElementById('invoice');
            const downloadBtn = document.getElementById('downloadBtn');

          // Temporarily hide the buttons
            printBtn.classList.add('hide-temporary');
            downloadBtn.classList.add('hide-temporary');
            exitBtn.classList.add('hide-temporary');

            // Use html2canvas to capture the content of the div as a canvas
            html2canvas(invoiceElement, {
                scale: 2  // Increase the scale factor to enhance image resolution
            }).then((canvas) => {
                // Convert the canvas to an image
                const imgData = canvas.toDataURL('image/png');

                // Calculate dimensions for the PDF
                const imgWidth = 190; // Width in mm
                const imgHeight = canvas.height * imgWidth / canvas.width;

                // Add the image to the PDF
                doc.addImage(imgData, 'PNG', 10, 10, imgWidth, imgHeight);

                // Save the PDF
                doc.save('order.pdf');

                // Show the buttons again
                printBtn.classList.remove('hide-temporary');
                downloadBtn.classList.remove('hide-temporary');
                exitBtn.classList.remove('hide-temporary');
            });
        }
    </script>

    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>

<?php

?>