<?php 
include "config.php";

$order_id = $_GET['order_id'];

// Order info
$stmt = $con->prepare("SELECT o.id, o.total_amount, o.created_at, o.note,
                              c.company_name, c.contact_person, c.address, c.upload_file
                       FROM orders o 
                       JOIN tbl_customers c ON o.customer_id = c.id 
                       WHERE o.id = ?");
$stmt->bind_param("i", $order_id);
$stmt->execute();
$order = $stmt->get_result()->fetch_assoc();
$stmt->close();

// Order items
$stmt = $con->prepare("SELECT * FROM order_items WHERE order_id = ?");
$stmt->bind_param("i", $order_id);
$stmt->execute();
$items = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// Split items into chunks of 10 rows
$chunks = array_chunk($items, 20);
?>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <title>Order Form</title>
      
      <style>
         body { font-family: Arial, sans-serif; margin: 10px; }
         .invoice {
            width: 98%;
    border: 1px solid #000;
    padding: 10px;
    box-sizing: border-box;
    display: flex
;
    flex-direction: column;
    width: 21cm;
    height: 29.7cm;
         }
         .header { display: flex; justify-content: space-between; align-items: center; }
         .logo { width: 150px; }
         .details { margin-top:10px; font-size:13px; }
         table { width:100%; border-collapse:collapse; margin-top:10px; font-size:13px; }
         th, td { border:1px solid #000; padding:4px; vertical-align:top; }
         .totals { text-align:right; font-weight:bold; }
         .footer { font-size:12px; margin-top:auto; }
         @media print {
            @page { size: A4 portrait; margin:0; }
            body { margin:0; }
            .invoice { page-break-after:always; }
            .invoice:last-child { page-break-after:auto; }
         .toolbar{display:none;}
         }
         tbody tr td{
         border-top: none;
         border-bottom: none;
         }
         .d-none-print-show {
         display: none !important; /* Hidden by default */
         }
         .page {
    display: flex
;
    flex-direction: row;
    justify-content: center;
    gap: 20px;
    transform: scale(0.95);
}
      </style>
   </head>
   <body>
       <div style="display:flex;justify-content:center;">
        <div class="toolbar">
         <button onclick="saveAsPDF()">💾 Save as PDF</button>
         <button onclick="window.print()">🖨 Print</button>
         <button onclick="history.back()">⬅ Back</button>
      </div></div>
      <div class="page">
      <div id="invoiceArea">
      <?php foreach($chunks as $pageIndex => $chunk): ?>
      <div class="invoice">
         
         <!-- Header -->
         <div class="header">
            <img class="logo" src="images/pro-logo.png" alt="Logo">
            <div style="text-align:right;">
              <img src="uploads/<?= !empty($order['upload_file']) 
        ? htmlspecialchars($order['upload_file']) 
        : 'default.png' ?>" 
     alt="<?= htmlspecialchars($order['company_name']) ?>" 
     width="60" height="60" 
     style="border:1px solid #000; object-fit:cover;">

            </div>
         </div>

         <!-- Order details row -->
         <div style="display:flex;justify-content:space-between;align-items:center;margin-top:5px;">
            <div style="width:33%;font-size:14px;">
               <strong>To:</strong> <?= htmlspecialchars($order['company_name']) ?> 
               (<?= htmlspecialchars($order['contact_person']) ?>)<br>
               <?= nl2br(htmlspecialchars($order['address'])) ?>
            </div>
            <div style="width:33%;text-align:center;">
               <h4 style="border:1px solid black;padding:4px;display:inline-block;">ORDER FORM</h4>
            </div>
            <div style="width:33%;text-align:right;">
               <strong><?= ($pageIndex==0)?'Original':'Duplicate' ?></strong><br>
               <span style="font-size:12px;">No: <?= $order_id; ?><br>Date: <?= $order['created_at'];?></span>
            </div>
         </div>
<h6 style="margin-bottom: 0;margin-top: 0;">Sir, We thank you for the enquiry and have pleasure in submitting our best offer as below item. We hope that you will find our offer competitive and new look forward to the pleasure of receiving your valued order. Which we will have our best and prompt attention.</h6>
         <!-- Items Table -->
         <table>
            <thead>
               <tr>
                  <th>#</th>
                  <th>I.code</th>
                  <th>Product Name</th>
                  <th>Rate</th>
                  <th>Qty</th>
                  <th>Color</th>
                  <th>Size</th>
                  <th>Remarks</th>
                  <th>Total</th>
               </tr>
            </thead>
            <tbody>
               <?php 
               $i = $pageIndex*10 + 1;
               foreach($chunk as $row): 
                   $productid = $row['product_id'];
                   $pstmt = $con->prepare("SELECT item_name, product_color, unit_amt, unit,description,item_code 
                                            FROM tbl_stock_items WHERE id=?");
                   $pstmt->bind_param("i",$productid);
                   $pstmt->execute();
                   $product = $pstmt->get_result()->fetch_assoc();
                   $pstmt->close();
               ?>
               <tr>
                  <td><?= $i++ ?></td>
                  <td><?= htmlspecialchars($product['item_code']) ?></td>
                  <td><?= htmlspecialchars($row['product_name']) ?></td>
                  <td><?= number_format($row['price'],2) ?></td>
                  <td><?= htmlspecialchars($row['quantity']) ?></td>
                  <td><?= htmlspecialchars($product['product_color']) ?></td>
                  <td><?= htmlspecialchars($product['unit_amt'].' '.$product['unit']) ?></td>
                  <!--<td><?= htmlspecialchars($row['remarks']) ?></td>-->
                  <td style="word-wrap: break-word; white-space: normal; max-width: 100px;">
    <?= htmlspecialchars($row['remarks']) ?>
</td>

                  <td><?= number_format($row['price'] * $row['quantity'],2) ?></td>
               </tr>
               <?php endforeach; ?>
            </tbody>

            <!-- Totals only on last page -->
            <?php if($pageIndex == count($chunks)-1): ?>
            <tfoot>
               <tr><td colspan="8" class="totals">Total</td><td><?= number_format($order['total_amount'],2) ?></td></tr>
               <tr><td colspan="8" class="totals">Discount</td><td></td></tr>
               <tr><td colspan="8" class="totals">Net Total</td><td><?= number_format($order['total_amount'],2) ?></td></tr>
               <tr><td colspan="9" style="text-align:left;">Note:<?= $order['note'] ?></td></tr>
               
            </tfoot>
            <?php endif; ?>
         </table>

         <!-- Footer -->
         <div style="position:fixed;bottom: 0; width: 20.4cm;">
         <div class="footer">
             <div style="display: flex;justify-content: space-between;align-items: flex-end;align-items:baseline;">
                  <div style="display: flex;justify-content:end;width: 72%;">
                     <div>
                        <img src="seal.png" alt="" style="  
                               position: absolute;
    width: 55mm;
    margin-bottom: 70px;
    bottom:20px;">
                     </div>
                     <!-- <div>
                        <img src="sign.png" alt="" style="    position: absolute;
                           width: 35mm;
                           margin-bottom: -15px;
                           bottom:132px;mix-blend-mode: darken;">
                     </div>
 -->                  </div>
                  <!-- <div>
                     For Programers International
                     </div> -->
               </div>
            <div style="display:flex;justify-content:space-between;margin-top:20px;">
               <span>Authorised Person:<br>Date:</span>
               <span>(Seal)</span>
            </div>
            <hr style="border-top:1px solid black;">
            <div style="border:1px solid black;padding:8px;font-size:11px;text-align:center;">
               <b>Terms & Conditions:</b><br>
               <b>Delivery:</b> within 90 Days | <b>Quality:</b> Same as sample | 
               <b>Payment:</b> 50% advance, balance on delivery | <b>Bill:</b> GST applicable<br>
               *This is a computer generated order form. No signature required.
            </div>
            <div style="padding:6px;font-size:11px;text-align:center;">
               Praveen International Packing Solutions, Kechri Wadakkancheri Road, Velur-680601,
               Ph: +91 9946235343 / 894333014 
            </div>
         </div></div>
      </div>
      <?php endforeach; ?>
      </div>
   </body>
</html>
 <!-- JS for Save as PDF -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
    <script>
        function saveAsPDF() {
    const element = document.getElementById('invoiceArea'); 
    const opt = {
        margin:       0,
        filename:     'invoice.pdf',
        image:        { type: 'jpeg', quality: 0.98 },
        html2canvas:  { scale: 2 },
        jsPDF:        { unit: 'in', format: 'a4', orientation: 'portrait' }
    };
    html2pdf().set(opt).from(element).save();
}
</script>