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

// Fetch order details from the database
$orderId = isset($_GET['order_id']) ? mysqli_real_escape_string($connection, $_GET['order_id']) : null;
$orderDetails = [];
$outletName = $loginUser = $userRole = $outletAddress = $dateTime = $totalAmount = $paidBy = $customerName = $customerPhone = $discountedAmount = $discounted = $discountPer = $cashAmount = $changeAmount = $taxAmount = null;

if ($orderId) {
    $query = "SELECT * FROM log_user_sales WHERE r_order_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'];
        $status = $order['status'];
    }
}

$content = ob_get_clean(); // Capture HTML content

// Function to send data to the printer
function sendToPrinter($result) {
    $printerName = "EPSON_TM_T88V_Receipt"; // Change to your printer's name
    $handle = @fopen("USB", "w"); // LPT1 is commonly used for parallel port printers, change if necessary
    if (!$handle) {
        echo "Error opening printer on Windows. Check the printer port and connection.";
        return;
    }
    fwrite($handle, $result);
    fclose($handle);
    echo "";
}

// Call the print function
sendToPrinter($content);
?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><?php echo $tx ?></title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.4.0/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.23/jspdf.plugin.autotable.min.js"></script>
   <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@200;300;400;500;600;700&display=swap" rel="stylesheet">

    <style>
    body {
    font-family: 'Quicksand', sans-serif;
    
}
        @media print {
            body {
                width: 72mm;
                margin: 0;
                padding: 0;
            }
            .container {
                width: 100%;
                margin: 0;
                padding: 0;
            }
            .no-print {
                display: none;
            }
            .text-center {
                text-align: center;
            }
            table {
                width: 100%;
                border-collapse: collapse;
            }
            th, td {
                border: 1px solid #000;
                padding: 5px;
                text-align: center;
            }
            .mb-0, .mb-1 {
                margin-bottom: 5px;
            }
        }
    </style>
</head>
<body>
<div class="container" id="invoice">
    <div class="text-center" style="margin-left:10px;">
        <!--<img src="../img/logo231.png" width="176" height="176" alt="Logo" class="logo">-->
        <h2 style="font-weight:600; text-transform:uppercase;"><?php echo $tx ?></h2>
      <p class="mb-0" style="font-size:14px;margin-top:5px;text-transform:uppercase;font-weight:600;"> Moharah Bazar.</p>
        <p class="mb-0" style="margin-top:-2px;font-weight:600;">Md Mahmood Chohan: 03556411764 <br> 03125516784</p>

        
        <p style="margin-top:-3px;"><strong>Date:</strong> <?php echo htmlspecialchars($dateTime); ?> </p>
    </div>

    <div>
        <p style="text-transform:capitalize;"><strong>Name:</strong> <?php echo htmlspecialchars($customerName); ?><br>
        <strong>Phone:</strong> <?php echo htmlspecialchars($customerPhone); ?><br>
       <strong>Payment:</strong> <?php echo htmlspecialchars($paidBy); ?><br>
        <strong>Order ID:</strong> <?php echo htmlspecialchars($orderId); ?></p>
        <strong>Status:</strong> <?php echo htmlspecialchars($status); ?></p>
    </div>

    <div>
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>Product</th>
                    <th>Qty</th>
                    <th>Price</th>
                    <th>Dis</th>
                    <th>PKR</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($orderDetails as $order): ?>
                <tr>
                    <td><?php echo htmlspecialchars($order['product_name']); ?></td>
                    <td><?php echo htmlspecialchars($order['product_quantity']); ?></td>
                    <td><?php echo htmlspecialchars($order['product_price']); ?></td>
                    <td><?php echo htmlspecialchars($order['discount']); ?></td>
                    <td><?php echo htmlspecialchars($order['net_amount']); ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php
    $sub = mysqli_query($connection, "SELECT SUM(net_amount) AS sub FROM log_user_sales WHERE order_id = '$orderId'");
    $rowSub = mysqli_fetch_array($sub);
    ?>
    <div>
        <p><strong>Sub:</strong> Rs <?php echo htmlspecialchars($rowSub["sub"]); ?> /-<br>
        <strong>Disc:</strong> Rs <?php echo htmlspecialchars($discounted); ?> /-<br>
        <strong>Total:</strong> Rs <?php echo htmlspecialchars($discountedAmount) . ".00"; ?> /-<br>
        <strong>Cash:</strong> Rs <?php echo htmlspecialchars($cashAmount) . ".00"; ?> /-<br>
       <strong>Change:</strong> Rs <?php echo htmlspecialchars($changeAmount) ; ?> /-<br>
    </div>

    <div>
        <p>Generated By: ATR Software | 0334-8739892</p>
    </div>

    <div>
        <h3>Notes:</h3>
      <p>1. Exchanges are accepted within 7 days from the date of purchase.<br>
       2. Items must be in their original condition with all tags attached.<br>
       3. A valid receipt or proof of purchase is required for all exchanges.</p>
       
        <h3 style="text-align:center;">Thanks For Visiting.</h3>
    </div>

    <div class="text-center no-print">
        <button class="no-print btn btn-primary" onclick="window.print()">Print</button>
        <button class="no-print btn btn-success" onclick="downloadPDF()">Download PDF</button>
        <button class="no-print btn btn-secondary" onclick="window.location.href='order_detail_v.php'">Exit</button>
    </div>
</div>


</body>
<script>
    function downloadPDF() {
        // Import jsPDF
        const { jsPDF } = window.jspdf;
        const doc = new jsPDF('p', 'mm', 'a4');

        // Add the logo
        const img = new Image();
        img.src = 'img/Amazon Fashion STORE11.png';
        img.onload = function () {
            // Adding the logo
            doc.addImage(img, 'PNG', 10, 10, 40, 40);

            // Add the store name and other details
            doc.setFontSize(18);
            doc.text('Amazon Fashion Store', 60, 20);

            doc.setFontSize(12);
            doc.text('M. Block Near Ex M.N.A Office Arif Bazar, Burewala', 60, 30);
            doc.text('Muneeb: 0310-6089145, Safi Gujjar: 0303-4993253', 60, 40);
            doc.text('Date: <?php echo htmlspecialchars($dateTime); ?>', 60, 50);

            // Add customer details
            doc.setFontSize(14);
            doc.text('Customer Details', 10, 70);
            doc.setFontSize(12);
            doc.text('Name: <?php echo htmlspecialchars($customerName); ?>', 10, 80);
            doc.text('Phone: <?php echo htmlspecialchars($customerPhone); ?>', 10, 90);
            doc.text('Payment: <?php echo htmlspecialchars($paidBy); ?>', 10, 100);
            doc.text('Order ID: <?php echo htmlspecialchars($orderId); ?>', 10, 110);

            // Add the table header
            doc.setFontSize(14);
            doc.text('Order Details', 10, 130);
            doc.setFontSize(12);
            doc.autoTable({
                startY: 140,
                head: [['Product', 'Qty', 'Price', 'Dis', 'PKR']],
                body: [
                    <?php foreach ($orderDetails as $order): ?>
                    ['<?php echo htmlspecialchars($order['product_name']); ?>', '<?php echo htmlspecialchars($order['product_quantity']); ?>', '<?php echo htmlspecialchars($order['product_price']); ?>', '<?php echo htmlspecialchars($order['discount']); ?>', '<?php echo htmlspecialchars($order['net_amount']); ?>'],
                    <?php endforeach; ?>
                ],
                theme: 'grid'
            });

            // Add totals
            let finalY = doc.lastAutoTable.finalY + 10;
            doc.setFontSize(14);
            doc.text('Summary', 10, finalY);
            doc.setFontSize(12);
            finalY += 10;
            doc.text('Sub: Rs <?php echo htmlspecialchars($rowSub["sub"]); ?> /-', 10, finalY);
            finalY += 10;
            doc.text('Disc: Rs <?php echo htmlspecialchars($discounted); ?> /-', 10, finalY);
            finalY += 10;
            doc.text('Total: Rs <?php echo htmlspecialchars($discountedAmount) . ".00"; ?> /-', 10, finalY);
            finalY += 10;
            doc.text('Cash: Rs <?php echo htmlspecialchars($cashAmount) . ".00"; ?> /-', 10, finalY);
            finalY += 10;
            doc.text('Change: Rs <?php echo htmlspecialchars($changeAmount); ?> /-', 10, finalY);

            // Add footer
            finalY += 20;
            doc.text('Generated By: Amazon Fashion Store', 10, finalY);
            finalY += 10;
            doc.setFontSize(10);
            doc.text('Notes:', 10, finalY);
            finalY += 10;
            doc.text('1. Exchanges are accepted within 7 days from the date of purchase.', 10, finalY);
            finalY += 10;
            doc.text('2. Items must be unworn, unwashed, and in their original condition with all tags attached.', 10, finalY);
            finalY += 10;
            doc.text('3. A valid receipt or proof of purchase is required for all exchanges.', 10, finalY);
            finalY += 10;
            doc.text('Thanks For Visiting.', 60, finalY + 20, 'center');

            // Save the PDF with the name 'invoice.pdf'
            doc.save('invoice.pdf');
        };
    }
</script>
</html>

