<?php
session_start();

if(!isset($_SESSION["sess_user"])) {
    header("Location: index.php");
    exit();
}
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
   <?php  
  if(isset($_GET["search"])){ 
 include('includes/config.php');
          $vendor=$_GET['vendor'];
          $fromdate = $_GET['from_date'];
          $todate =$_GET['to_date'];
          
         $billNo = isset($_GET['bill_no']) ? $_GET['bill_no'] : '';
         $getBillDate = isset($_GET['bill_date']) ? $_GET['bill_date'] : '';
         
          $date = new DateTime($getBillDate);
          $billDate = $date->format('d-M-Y'); // Format: 19-Jan-2025

          $preBalance = isset($_GET['previous_bal']) ? $_GET['previous_bal'] : '';
         $details = isset($_GET['details']) ? $_GET['details'] : '';
         $title = isset($_GET['title']) ? $_GET['title'] : $_GET['Custom Shipment Report'];
         
         

          
          
          $results = mysqli_query($con, "SELECT * FROM `shipment` as s   WHERE  s.s_date BETWEEN '".$fromdate."' AND '".$todate."' AND s.s_status!=2 LIMIT 1");

      $frdate = $_GET['from_date']; $frmdates =date("M-j-Y",strtotime($frdate)); 
      $todate =$_GET['to_date']; $tomdates = date("M-j-Y",strtotime($todate));
      
      
       while($rows = mysqli_fetch_assoc($results)) {
        $title = $title ? $title : 'Custom Shipment Report';
       
       ?> <title><?php echo ("$title.\n From $frmdates To $tomdates."); ?>
     
</title>
   
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <!-- Favicon icon -->
    <link rel="shortcut icon" href="images/logos/small png logo.png" type="image/x-icon" >
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/select/1.6.0/css/select.dataTables.min.css">
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.5.2/css/buttons.bootstrap4.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.2.3/css/responsive.bootstrap4.min.css">
          <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.2.3/css/responsive.bootstrap4.min.css">

    
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/select/1.6.0/js/dataTables.select.min.js"></script>
    <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.25/jspdf.plugin.autotable.min.js"></script>
    
    <style>
    .pagination { list-style: none; padding-left: 0; }
    .pagination li { display: inline; margin: 5px; }
    .pagination li a { text-decoration: none; padding: 5px 10px; border: 1px solid #ddd; }
    .pagination li a.active { background-color: #007bff; color: white; }
    .pagination li a:hover { background-color: #ddd; }

    .table th, .table td { text-align: center; }

    /* Make the table responsive */
    @media (max-width: 768px) {
        .table {
            width: 100%;
            display: block;
            overflow-x: auto;
            white-space: nowrap;
        }
    }
</style>


</head>


<!--<body onload="window.print()">-->
<body>
<div class="container-fluid">

<div class="page-header">
   
     

                     <?php 
if(!$_GET['hide_logo']) {
//A few settings
    $img_file = 'images/logos/madinaconst-lgnew.png';

// Read image path, convert to base64 encoding
$imgData = base64_encode(file_get_contents($img_file));

// Format the image SRC:  data:{mime};base64,{data};
//$src = 'data: '.mime_content_type($img_file).';base64,'.$imgData;

$src = 'data: '.$img_file.';base64,'.$imgData;


// Echo out a sample image
echo '<center><div  class="logo"><img height="200" width="200" src="'.$src.'">  </div></center>';

}
?>
    
     
    <br>
     
    <h3 align="center"><?php echo $title ? $title :'Custom Shipment Report'   ?> Report.</small></h3>
    <?php  $frdate = $_GET['from_date']; $frmdates =date("M-j-Y",strtotime($frdate)); 
      $todate =$_GET['to_date']; $tomdates = date("M-j-Y",strtotime($todate));
      echo  ("<center><h3>From $frmdates To $tomdates.<h3></center>");
       ?>
  <?php } ?>
    
</div>


<div class="row">
    <div class="col-md-4">
    <?php if($billNo) { ?>
    <b>Bill No <?php echo $billNo; ?></b><br>
   
    
    <?php }  ?>   
    <?php if($details) { ?>
     <b>Details: <?php echo $details;  ?></b>
     <?php }?>
    </div>
    <div class="col-md-4">
        
    </div>
    
    <div class="col-md-4">
        <?php if($billDate) { ?>
    <b>Date <?php echo $billDate; ?></b>
    
    <?php }  ?>   
    </div>
         
</div>


<div class="container mt-4">
  
    
     


    <div class="mb-3">
        <button id="export-pdf" class="btn btn-primary">Export to PDF</button>
        <input type="checkbox" id="select-all" class="ml-3"> <label for="select-all">Select All</label>
    </div>

    <div class="mb-3">
        <h5>Select Columns to Show/Export:</h5>
        <div id="column-selectors" class="d-flex">
            <!-- Column checkboxes will be dynamically added here -->
        </div>
    </div>
    </div>
<div class="table-responsive">
   <table id="datatable" class="display table table-striped table-bordered dt-responsive nowrap" style="width:100%">
 <thead>
            <tr>
                <th>#</th>
                <th>S No</th>
                <th>SM No</th>
                <th>Date</th>
                <th>Slip No</th>
                <th>Vendor</th>
                <th>Vehicle</th>
                <th>Item</th>
                <th>Qty </th>
               <th>Measurement </th>
                <th>Rate</th>
                <th class="total-column">Amount</th>
                <th class="total-column">Diesel</th>
                <th class="total-column">MCost</th>
                 <th class="total-column">VehM</th>
                <th class="total-column">D/Tx/Exp</th>
                <th class="total-column">Cost</th>
                <th class="total-column">Profit</th>
            </tr>
    </thead>
    <tbody>
        <?php
        include('includes/config.php');
        $fromdate = $_GET['from_date'];
        $todate = $_GET['to_date'];
        $no = 0;

        $result = mysqli_query($con, "SELECT * FROM `shipment` as s WHERE s.s_date BETWEEN '".$fromdate."' AND '".$todate."' AND s.s_status!=2 ORDER BY s.s_date ASC");
        while($row = mysqli_fetch_assoc($result)) {
            $no++;    
            
            $rate = $row['s_rate'];
            $rate = (int)$rate;
            
            $v = $row['measurement_total'];
            $v = (int)$v;
            
            $amount = $row['ship_total'];
            $amount = (int)$amount;  // This will cast the float to an integer
            
            
            $diesel = $row['s_diesel'];
            $diesel = (int)$diesel;
            
            $mcost = $row['material_cost'];
            $mcost = (int)$mcost;
            
            $taxdriver = $row['tax_driver_exp'];
            $taxdriver = (int)$taxdriver;
            
            $cost = $row['allmcost_total'];
            $cost = (int)$cost;
            
            $vehMcost = $row['veh_maintaince'];
            $vehMcost = (int)$vehMcost;
            
            $profitcost =  $amount - $cost;

            // Accumulate totals
            $totaldiesel += $row['s_diesel'];
            $totalmcost += $row['material_cost'];
            $totaldriver += $row['tax_driver_exp'];
            $totalcost += $cost;
            $totalships += $amount;
            $totalprofit += $profitcost;
        ?>
                    <tr>
                <td><input type="checkbox" class="select-row"></td>
                <td><? echo $no; ?></td>
                <td><?= $row['order_num']; ?></td>
                <td><?= date("d/m/Y", strtotime($row['s_date'])); ?></td>
                <td><?= $row['slip_no']; ?></td>
                <td><?= $row['vendor_id']; ?></td>
                <td><?= $row['measure_id']; ?></td>
                <td><?= $row['material_id']; ?></td>
                <td><?= $row['qty']; ?></td>
                <td><?=number_format($v, 0, '.', '');; ?></td>
                <td><?= number_format($rate, 0, '.', ''); ?></td>
                <td class="amount"><?=  number_format($amount, 0, '.', ''); ?></td>
                <td class="diesel"><?= number_format($diesel,0,'.',''); ?></td>
                <td class="mcost"><?= number_format($mcost,0,'.',''); ?></td>
                <td class="vehmcost"><?= number_format($vehMcost,0,'.',''); ?></td>
                <td class="dtxexp"><?= number_format($taxdriver,0,'.',''); ?></td>
                <td class="cost"><?= number_format($cost,0,'.',''); ?></td>
                <td class="profit"><? echo $profitcost ?></td>
                
               
                
            </tr>
        <?php } ?>
          <tfoot>
            <tr>
                <td colspan="11" style="text-align: right;">Total</td>
                <td class="total-footer amount-total">0</td>
                <td class="total-footer diesel-total">0</td>
                <td class="total-footer mcost-total">0</td>
                 <td class="total-footer vehmcost-total">0</td>
                <td class="total-footer dtxexp-total">0</td>
                <td class="total-footer cost-total">0</td>
                <td class="total-footer profit-total">0</td>
            </tr>
    </tfoot>
    </table></div></div>

   

    
  <div class="row">
        <div class="col-md-4">
            
        </div>
        
        <div class="col-md-4">
            
        </div>
        
        <div class="col-md-4">
           <?php if($preBalance) { ?>
    <b>Previous Balance: <?php echo $preBalance; ?></b>
<?php } else { ?>
    <b>Previous Balance: 0</b>
<?php } ?>
<br>
<?php if($totalBillAmount) { ?>
    <b>Total Bill Amount: <?php echo $totalBillAmount; ?></b>
<?php } else { ?>
    <b>Total Bill Amount: <?php echo $totalships; ?></b>
<?php } ?>

        </div>
    </div>
   
</div>
<?php } ?>

 <!--<script>
//     $(document).ready(function () {
//         // Initialize DataTable
//         var table = $('#datatable').DataTable({
//             columnDefs: [
//                 { targets: 0, orderable: false, searchable: false }, // Disable sorting and searching for the checkbox column
//             ],
//              pageLength: 20, // Default number of rows to show per page
//              lengthMenu: [
//         [20, 50, 100, -1], 
//         [20, 50, 100, "All"]
//         ],
//         });

//         // Generate column selectors dynamically (exclude the # column)
//         $('#datatable thead th').each(function (index) {
//             var columnName = $(this).text();
//             if (index !== 0 && index !==1 && columnName) { // Exclude the # column
//                 $('#column-selectors').append(
//                     `<div>
//                         <input type="checkbox" class="column-checkbox" data-column-index="${index}" checked> ${columnName}
//                     </div>`
//                 );
//             }
//         });

//         // "Select All" functionality (exclude footer row from selection logic)
//         $('#select-all').on('change', function () {
//             var isChecked = $(this).prop('checked');
//             $('.select-row').prop('checked', isChecked);
//             updateTotals();
//         });

//         // Individual row checkbox change
//         $('#datatable').on('change', '.select-row', function () {
//             var totalCheckboxes = $('.select-row').length;
//             var checkedCheckboxes = $('.select-row:checked').length;
//             $('#select-all').prop('checked', totalCheckboxes === checkedCheckboxes);
//             updateTotals();
//         });

//         // Update totals for visible columns and selected rows
//         function updateTotals() {
//             var totals = {
//                 amount: 0,
//                 diesel: 0,
//                 mcost: 0,
//                 vehmcost:0,
//                 dtxexp: 0,
//                 cost: 0,
//                 profit: 0,
//             };

//             $('#datatable tbody tr').each(function () {
//                 if ($(this).find('.select-row').prop('checked')) {
//                     totals.amount += parseFloat($(this).find('.amount').text()) || 0;
//                     totals.diesel += parseFloat($(this).find('.diesel').text()) || 0;
//                     totals.mcost += parseFloat($(this).find('.mcost').text()) || 0;
//                      totals.vehmcost += parseFloat($(this).find('.vehmcost').text()) || 0;
//                     totals.dtxexp += parseFloat($(this).find('.dtxexp').text()) || 0;
//                     totals.cost += parseFloat($(this).find('.cost').text()) || 0;
//                     totals.profit += parseFloat($(this).find('.profit').text()) || 0;
//                 }
//             });

//             // Update footer totals
//             $('#datatable tfoot .amount-total').text(totals.amount.toFixed(0));
//             $('#datatable tfoot .diesel-total').text(totals.diesel.toFixed(0));
//             $('#datatable tfoot .mcost-total').text(totals.mcost.toFixed(0));
//              $('#datatable tfoot .vehmcost-total').text(totals.vehmcost.toFixed(0));
//             $('#datatable tfoot .dtxexp-total').text(totals.dtxexp.toFixed(0));
//             $('#datatable tfoot .cost-total').text(totals.cost.toFixed(0));
//             $('#datatable tfoot .profit-total').text(totals.profit.toFixed(0));
//         }


//       $('#export-pdf').on('click', function () {
//     const { jsPDF } = window.jspdf;

//     // Create a new jsPDF instance with landscape orientation
//     var doc = new jsPDF('landscape', 'mm', 'a4');

//     // Get selected columns
//     var selectedColumns = [];
//     $('.column-checkbox:checked').each(function () {
//         selectedColumns.push(parseInt($(this).data('column-index')));
//     });

//     // Prepare the header for selected columns
//     var header = ['S No'];
//     $('#datatable thead th').each(function (index) {
//         if (selectedColumns.includes(index)) {
//             header.push($(this).text().trim());
//         }
//     });

//     // Prepare the body rows for selected columns
//     var rows = [];
//     var serialNo = 1; // Start serial number from 1
//     $('#datatable tbody tr').each(function () {
//         if ($(this).find('.select-row').prop('checked')) {
//           // var rowData = [];
//               var rowData = [serialNo++]; // Add serial number as the first column
//             $(this).find('td').each(function (index) {
//                 if (selectedColumns.includes(index)) {
//                     rowData.push($(this).text().trim());
//                 }
//             });
//             rows.push(rowData);
//         }
//     });

//   var totalsRow = [];

// // Define the original column indices for the range 2 to 16
// var originalColumnRange = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,17];

// // Map visible columns to their original indices
// var visibleColumnIndices = [];
// $('.column-checkbox:checked').each(function () {
//     visibleColumnIndices.push(parseInt($(this).data('column-index')));
// });

// // Add "Total" label at the first visible column
// var totalsIndex = visibleColumnIndices.indexOf(2); // Index for column 1 (where "Total" should go)
// if (totalsIndex !== -1) {
//     totalsRow[totalsIndex] = 'Total'; // Add "Total" at the correct position
// }

// // Initialize totalsRow with blank spaces
// originalColumnRange.forEach(() => {
//     totalsRow.push(''); // Fill with empty strings to align with all columns
// });

// // Filter visible columns that fall within the range 10 to 15
// var targetColumns = visibleColumnIndices.filter(function (index) {
//     return originalColumnRange.slice(9, 16).includes(index); // Columns 10 to 15
// });

// // Calculate totals only for the visible columns in the range
// targetColumns.forEach(function (columnIndex) {
//     var columnTotal = 0;

//     $('#datatable tbody tr').each(function () {
//         if ($(this).find('.select-row').prop('checked')) {
//             var cellValue = parseFloat($(this).find(`td:nth-child(${columnIndex + 1})`).text().trim()) || 0;
//             columnTotal += cellValue;
//         }
//     });

//     // Add calculated total to the correct position in totalsRow
//     var totalPosition = visibleColumnIndices.indexOf(columnIndex) + 1;
//     if (totalPosition !== -1) {
//         totalsRow[totalPosition] = columnTotal.toFixed(0);
//     }
// });

// // Add totalsRow to the body rows if there are rows to display
// if (rows.length > 0) {
//     rows.push(totalsRow);
// }

//     // Calculate the Previous Balance and Net Total
//     //var previousBalance = '<?php //echo $preBalance >= 0 ? $preBalance : " "; ?>';
//     var previousBalance = '<?php echo $preBalance; ?>';
//     var footerText = [];

// if (previousBalance && parseFloat(previousBalance) >= 0 || parseFloat(previousBalance) != "") {
//     footerText.push(`Previous Balance: ${parseFloat(previousBalance).toFixed(0)}`);
// }


// var netTotal = parseFloat($('.amount-total').text()) + (parseFloat(previousBalance) || 0);
// footerText.push(`Total Bill Amount: ${netTotal.toFixed(0)}`);






    
//     // Generate the PDF
//     if (rows.length > 0) {
//          const billNoX = 15; // Left side position for the bill number
        
        
//         var title = '<?php echo $title ? $title : 'Custom Shipment Report'; ?>';
        
//         var getBillNo = '<?php echo $billNo ?>';
//         var getBillDate = '<?php echo $billDate ?>';
//         var getDetails = '<?php echo $details; ?>';
        
//           const dateRange = "From <?php echo $frmdates. ' To ' . $tomdates ?>";
// var pageWidth = doc.internal.pageSize.width;


// const billDateX = pageWidth - 15;  // Right side position for the Bill Date (15px margin from the right edge)

// // Calculate the width of the title text to center it
// var textWidth = doc.getStringUnitWidth(title) * doc.internal.getFontSize();
// var xPosition = (pageWidth - textWidth) / 2; // Calculate center position

// // Add logo
// const logoBase64 = '<?php echo isset($src) ? $src : ""; ?>';
// const imgWidth = 50, imgHeight = 50;
// const logoX = (pageWidth - imgWidth) / 2; // Center the logo horizontally
// const logoY = 10; // Set logo position from the top of the page




// if(logoBase64) {
//     doc.addImage(logoBase64, 'PNG', logoX, logoY, imgWidth, imgHeight);
// }

// // Set the Y position for the title, below the logo
// const titleY = logoY + imgHeight + 5; // 5px padding below the logo
// //doc.text(title, xPosition, titleY); // Add title below the logo

// // Set font to Helvetica Bold and adjust font size
// doc.setFont("helvetica", "bold").setFontSize(16);


//   doc.text(title, pageWidth / 2, 65, { align: 'center' });
//   const detailsY = billNoX + 55; // Add a small space below the Bill No.
// const maxBillNoWidth = 70; // Maximum width for the Bill No column (adjust as needed)

  
//     // Add Bill No on the left side (regular style)
// doc.setFont("helvetica", "bolditalic").setFontSize(10);
// if(getBillNo){
// doc.text("Bill No: " + getBillNo, billNoX, titleY);  // Place Bill No on the left side
// }
// // Add Bill Date on the right side with bold and italic styles
// doc.setFont("helvetica", "bolditalic").setFontSize(10);  // Set font to both bold and italic

// if(getBillDate){
// doc.text("Date: " + getBillDate, billDateX, titleY, { align: 'right' });  // Place Bill Date on the right side with bold and italic
// }
    
//     // Add Details just below the Bill No.
// // Alternatively, you can use `doc.splitTextToSize()` for more control over line wrapping
// // Set maximum width for the text box, based on the Bill No column width
// const maxWidth = maxBillNoWidth; // Set a width for the Bill No column to contain the details text

// // Split the details text into lines that fit within the maxWidth
// const detailsText = getDetails;
// const lines = doc.splitTextToSize(detailsText, maxWidth);
// doc.text(lines, billNoX, detailsY); // Split and add text with line breaks

// // Set font to bold and add the dateRange text
// doc.setFont("helvetica", "bold").setFontSize(12);  // Set font to bold

//     doc.text(dateRange, pageWidth / 2, 75, { align: 'center' });
        
//  doc.autoTable({
//     head: [header],  // Add the header row
//     body: rows,      // Add the rows including the totals
//     startY: 85,      // Start rendering the table below the title
//     theme: 'striped', // Use striped rows for readability
//     styles: { 
//         halign: 'center',  // Center-align the content in cells
//         valign: 'middle',  // Vertically align the content in the center
//         overflow: 'linebreak', // Enable word wrapping
//         fontSize: 8,         // Set smaller font size for the table
//         rowHeight: 8,          // Adjust row height to make the table more compact
//         // fontStyle: 'bold',     // Set the font to bold for table data (body)
//         cellPadding: 1,         // Set padding inside cells
//         textColor: [0, 0, 0]   // Set the body text color to black (RGB: 0, 0, 0)
//     },
//     headStyles: {
//         fontSize: 8,          // Set font size for the header (thead)
//         halign: 'center',     // Center-align the header text
//         fontStyle: 'bold',    // Make header text bold
//         textColor: [255, 255, 255] // Set the text color to white (RGB: 255, 255, 255)

//     },
//     columnStyles: {  // Ensure columns align correctly
//         0: { halign: 'right' },  // Align the first column (Total) to the right
//     },
//     tableWidth: 'auto',     // Set the table width to auto-adjust based on content
//     margin: { top: 10, bottom: 20 },  // Adjust the margins
//     pageBreak: 'auto',      // Automatically add page breaks if the table overflows
//     didDrawCell: (data) => {
//         // Draw light borders only for the body cells (excluding the header)
//         if (data.row.index >= 0) {  // Ensure we are working with body rows
//             if (data.cell) {  // Ensure the cell exists
//                 doc.setLineWidth(0.1);  // Lighter border thickness
//                 doc.setDrawColor(200, 200, 200);  // Set light gray border color
                
//                 // Draw the border (rectangle) around each body cell
//                 doc.rect(data.cell.x, data.cell.y, data.cell.width, data.cell.height);
//             }
//         }
//     }
// });


        
 

//  const maxRowsPerPage = 25;  // Max rows per page to prevent table overflow
 
// var startY = doc.lastAutoTable.finalY + 3;  // Minimized top margin, adjust as needed

// // Create a "table-like" structure with two rows (Previous Balance and Net Total)
// var footerData = [];

// // Check if footerText[0] (Previous Balance) exists before adding it
// if (footerText[0] && footerText[0].includes(':')) {
//     let previousBalanceValue = footerText[0].split(':')[1].trim();

//     // Convert to number for validation
//     let numericValue = parseFloat(previousBalanceValue);

//     // Add to footerData only if the value is not blank, not zero, and not NaN
//     if (previousBalanceValue !== "" && numericValue !== 0 && !isNaN(numericValue)) {
//         footerData.push(['Previous Balance', previousBalanceValue]);
//     }
// }


// // Check if footerText[1] (Total Bill Amount) exists before adding it
// if (footerText[1] && footerText[1].includes(':')) {
//     footerData.push(['Total Bill Amount', footerText[1].split(':')[1].trim()]);
// }

// // Define column widths, assuming you want them to have equal width
// var columnWidths = [0.4, 0.6]; // Adjust these values for your design (total should add up to 1)

// // Use autoTable to create the "table" without borders
// doc.autoTable({
//     startY: startY,
//     head: [['', '']], // Empty header (no headers for this footer table)
//     body: footerData,
//     columnStyles: {
//         0: { halign: 'left', fontStyle: 'bold' },  // Align the left column to the left (for labels) and bold
//         1: { halign: 'right', fontStyle: 'bold' }, // Align the right column to the right (for values) and bold
//     },
//     columnWidth: columnWidths,
//     theme: 'plain',  // No borders for the table
//     margin: { left: 14, right: 14 }, // Set left and right margins
// });

// // Get the position of the last added row (Net Total)
// var lastRowY = doc.lastAutoTable.finalY;

// // Draw a line between Previous Balance and Net Total, immediately after Previous Balance
// var lineStartX = 14;  // Start line at left margin
// var lineEndX = doc.internal.pageSize.width - 14; // End line at right margin
// doc.line(lineStartX, lastRowY - 7, lineEndX, lastRowY - 7); // Line just below Previous Balance

// // Check if there's enough space for the footer content
// var pageHeight = doc.internal.pageSize.height;
// var contentHeight = lastRowY + 14;  // Total height used by content and lines

// // If there's not enough space on the page for the footer content, add a new page
// if (contentHeight > pageHeight - 30) {  // Leave some space at the bottom (e.g., 30 units)
//     doc.addPage();  // Add a new page if necessary
//     startY = 10;  // Reset startY for the new page (for example)
//     doc.setFontSize(12);
//     doc.setFont('helvetica', 'bold');
// }





//         //doc.save('datatable_export.pdf'); // Save the generated PDF
//          // Save PDF
//     const fileName = title + "_" + new Date().toISOString().split('T')[0] + ".pdf";
//     doc.save(fileName);
//     } else {
//         alert('Please select at least one row to export.');
//     }
// });





//     });
</script>
-->





<!-- new code -->
<script>
    $(document).ready(function () {
        // Initialize DataTable
        var table = $('#datatable').DataTable({
            columnDefs: [
                { targets: 0, orderable: false, searchable: false }, // Disable sorting and searching for the checkbox column
            ],
             pageLength: 20, // Default number of rows to show per page
             lengthMenu: [
        [20, 50, 100, -1], 
        [20, 50, 100, "All"]
        ],
        });

        // Generate column selectors dynamically (exclude the # column)
        $('#datatable thead th').each(function (index) {
            var columnName = $(this).text();
            if (index !== 0 && index !==1 && columnName) { // Exclude the # column
                $('#column-selectors').append(
                    `<div>
                        <input type="checkbox" class="column-checkbox" data-column-index="${index}" checked> ${columnName}
                    </div>`
                );
            }
        });

        // "Select All" functionality (exclude footer row from selection logic)
        $('#select-all').on('change', function () {
            var isChecked = $(this).prop('checked');
            $('.select-row').prop('checked', isChecked);
            updateTotals();
        });

        // Individual row checkbox change
        $('#datatable').on('change', '.select-row', function () {
            var totalCheckboxes = $('.select-row').length;
            var checkedCheckboxes = $('.select-row:checked').length;
            $('#select-all').prop('checked', totalCheckboxes === checkedCheckboxes);
            updateTotals();
        });

        // Update totals for visible columns and selected rows
        function updateTotals() {
            var totals = {
                amount: 0,
                diesel: 0,
                mcost: 0,
                vehmcost:0,
                dtxexp: 0,
                cost: 0,
                profit: 0,
            };

            $('#datatable tbody tr').each(function () {
                if ($(this).find('.select-row').prop('checked')) {
                    totals.amount += parseFloat($(this).find('.amount').text()) || 0;
                    totals.diesel += parseFloat($(this).find('.diesel').text()) || 0;
                    totals.mcost += parseFloat($(this).find('.mcost').text()) || 0;
                     totals.vehmcost += parseFloat($(this).find('.vehmcost').text()) || 0;
                    totals.dtxexp += parseFloat($(this).find('.dtxexp').text()) || 0;
                    totals.cost += parseFloat($(this).find('.cost').text()) || 0;
                    totals.profit += parseFloat($(this).find('.profit').text()) || 0;
                }
            });

            // Update footer totals
            $('#datatable tfoot .amount-total').text(totals.amount.toFixed(0));
            $('#datatable tfoot .diesel-total').text(totals.diesel.toFixed(0));
            $('#datatable tfoot .mcost-total').text(totals.mcost.toFixed(0));
             $('#datatable tfoot .vehmcost-total').text(totals.vehmcost.toFixed(0));
            $('#datatable tfoot .dtxexp-total').text(totals.dtxexp.toFixed(0));
            $('#datatable tfoot .cost-total').text(totals.cost.toFixed(0));
            $('#datatable tfoot .profit-total').text(totals.profit.toFixed(0));
        }


      $('#export-pdf').on('click', function () {
    const { jsPDF } = window.jspdf;

    // Create a new jsPDF instance with landscape orientation
    var doc = new jsPDF('landscape', 'mm', 'a4');

    // Get selected columns
    var selectedColumns = [];
    $('.column-checkbox:checked').each(function () {
        selectedColumns.push(parseInt($(this).data('column-index')));
    });

    // Prepare the header for selected columns
    var header = ['S No'];
    $('#datatable thead th').each(function (index) {
        if (selectedColumns.includes(index)) {
            header.push($(this).text().trim());
        }
    });

    // Prepare the body rows for selected columns
    var rows = [];
    var serialNo = 1; // Start serial number from 1
    $('#datatable tbody tr').each(function () {
        if ($(this).find('.select-row').prop('checked')) {
           // var rowData = [];
              var rowData = [serialNo++]; // Add serial number as the first column
            $(this).find('td').each(function (index) {
                if (selectedColumns.includes(index)) {
                    rowData.push($(this).text().trim());
                }
            });
            rows.push(rowData);
        }
    });

  var totalsRow = [];

// Define the original column indices for the range 2 to 16
var originalColumnRange = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,17];

// Map visible columns to their original indices
var visibleColumnIndices = [];
$('.column-checkbox:checked').each(function () {
    visibleColumnIndices.push(parseInt($(this).data('column-index')));
});

// Add "Total" label at the first visible column
var totalsIndex = visibleColumnIndices.indexOf(2); // Index for column 1 (where "Total" should go)
if (totalsIndex !== -1) {
    totalsRow[totalsIndex] = 'Total'; // Add "Total" at the correct position
}

// Initialize totalsRow with blank spaces
originalColumnRange.forEach(() => {
    totalsRow.push(''); // Fill with empty strings to align with all columns
});

// Filter visible columns that fall within the range 10 to 15
var targetColumns = visibleColumnIndices.filter(function (index) {
    return originalColumnRange.slice(9, 16).includes(index); // Columns 10 to 15
});

// Calculate totals only for the visible columns in the range
targetColumns.forEach(function (columnIndex) {
    var columnTotal = 0;

    $('#datatable tbody tr').each(function () {
        if ($(this).find('.select-row').prop('checked')) {
            var cellValue = parseFloat($(this).find(`td:nth-child(${columnIndex + 1})`).text().trim()) || 0;
            columnTotal += cellValue;
        }
    });

    // Add calculated total to the correct position in totalsRow
    var totalPosition = visibleColumnIndices.indexOf(columnIndex) + 1;
    if (totalPosition !== -1) {
        totalsRow[totalPosition] = columnTotal.toFixed(0);
    }
});

// Add totalsRow to the body rows if there are rows to display
if (rows.length > 0) {
    rows.push(totalsRow);
}

    // Calculate the Previous Balance and Net Total
    //var previousBalance = '<?php //echo $preBalance >= 0 ? $preBalance : " "; ?>';
    var previousBalance = '<?php echo $preBalance; ?>';
    var footerText = [];

if (previousBalance && parseFloat(previousBalance) >= 0 || parseFloat(previousBalance) != "") {
    footerText.push(`Previous Balance: ${parseFloat(previousBalance).toFixed(0)}`);
}


var netTotal = parseFloat($('.amount-total').text()) + (parseFloat(previousBalance) || 0);
footerText.push(`Total Bill Amount: ${netTotal.toFixed(0)}`);






    
    // Generate the PDF
    if (rows.length > 0) {
         const billNoX = 15; // Left side position for the bill number
        
        
        var title = '<?php echo $title ? $title : 'Custom Shipment Report'; ?>';
        
        var getBillNo = '<?php echo $billNo ?>';
        var getBillDate = '<?php echo $billDate ?>';
        var getDetails = '<?php echo $details; ?>';
        
          const dateRange = "From <?php echo $frmdates. ' To ' . $tomdates ?>";
var pageWidth = doc.internal.pageSize.width;


const billDateX = pageWidth - 15;  // Right side position for the Bill Date (15px margin from the right edge)

// Calculate the width of the title text to center it
var textWidth = doc.getStringUnitWidth(title) * doc.internal.getFontSize();
var xPosition = (pageWidth - textWidth) / 2; // Calculate center position

// Add logo
const logoBase64 = '<?php echo isset($src) ? $src : ""; ?>';
const imgWidth = 50, imgHeight = 50;
const logoX = (pageWidth - imgWidth) / 2; // Center the logo horizontally
const logoY = 10; // Set logo position from the top of the page

// VARIABLES FOR DYNAMIC POSITIONING
var titleY, detailsY, startTableY, titlePositionY, dateRangePositionY;

// CHECK IF LOGO SHOULD BE HIDDEN
<?php if(!isset($_GET['hide_logo']) || $_GET['hide_logo'] != '1'){ ?> 
// LOGO SHOW - Normal positioning
if(logoBase64) {
    doc.addImage(logoBase64, 'PNG', logoX, logoY, imgWidth, imgHeight);
}
titleY = logoY + imgHeight + 5;
detailsY = billNoX + 55;
startTableY = 85;
titlePositionY = 65; // Original title position
dateRangePositionY = 75; // Original date range position
<?php } else { ?>
// LOGO HIDDEN - Adjust all positions to remove logo space
titleY = 20;
detailsY = billNoX + 35;
startTableY = 55; // Further reduced from 65 to 55
titlePositionY = 35; // Reduced from 65 to 35
dateRangePositionY = 45; // Reduced from 75 to 45
<?php } ?>

// Set font to Helvetica Bold and adjust font size
doc.setFont("helvetica", "bold").setFontSize(16);

// DYNAMIC TITLE POSITION
doc.text(title, pageWidth / 2, titlePositionY, { align: 'center' });
const maxBillNoWidth = 70; // Maximum width for the Bill No column (adjust as needed)

// Add Bill No on the left side (regular style)
doc.setFont("helvetica", "bolditalic").setFontSize(10);
if(getBillNo){
doc.text("Bill No: " + getBillNo, billNoX, titleY);  // Place Bill No on the left side
}
// Add Bill Date on the right side with bold and italic styles
doc.setFont("helvetica", "bolditalic").setFontSize(10);  // Set font to both bold and italic

if(getBillDate){
doc.text("Date: " + getBillDate, billDateX, titleY, { align: 'right' });  // Place Bill Date on the right side with bold and italic
}
    
    // Add Details just below the Bill No.
// Alternatively, you can use `doc.splitTextToSize()` for more control over line wrapping
// Set maximum width for the text box, based on the Bill No column width
const maxWidth = maxBillNoWidth; // Set a width for the Bill No column to contain the details text

// Split the details text into lines that fit within the maxWidth
const detailsText = getDetails;
const lines = doc.splitTextToSize(detailsText, maxWidth);
doc.text(lines, billNoX, detailsY); // Split and add text with line breaks

// Set font to bold and add the dateRange text with DYNAMIC POSITION
doc.setFont("helvetica", "bold").setFontSize(12);  // Set font to bold
doc.text(dateRange, pageWidth / 2, dateRangePositionY, { align: 'center' });
        
 doc.autoTable({
    head: [header],  // Add the header row
    body: rows,      // Add the rows including the totals
    startY: startTableY,      // DYNAMIC table start position
    theme: 'striped', // Use striped rows for readability
    styles: { 
        halign: 'center',  // Center-align the content in cells
        valign: 'middle',  // Vertically align the content in the center
        overflow: 'linebreak', // Enable word wrapping
        fontSize: 8,         // Set smaller font size for the table
        rowHeight: 8,          // Adjust row height to make the table more compact
        // fontStyle: 'bold',     // Set the font to bold for table data (body)
        cellPadding: 1,         // Set padding inside cells
        textColor: [0, 0, 0]   // Set the body text color to black (RGB: 0, 0, 0)
    },
    headStyles: {
        fontSize: 8,          // Set font size for the header (thead)
        halign: 'center',     // Center-align the header text
        fontStyle: 'bold',    // Make header text bold
        textColor: [255, 255, 255] // Set the text color to white (RGB: 255, 255, 255)

    },
    columnStyles: {  // Ensure columns align correctly
        0: { halign: 'right' },  // Align the first column (Total) to the right
    },
    tableWidth: 'auto',     // Set the table width to auto-adjust based on content
    margin: { top: 10, bottom: 20 },  // Adjust the margins
    pageBreak: 'auto',      // Automatically add page breaks if the table overflows
    didDrawCell: (data) => {
        // Draw light borders only for the body cells (excluding the header)
        if (data.row.index >= 0) {  // Ensure we are working with body rows
            if (data.cell) {  // Ensure the cell exists
                doc.setLineWidth(0.1);  // Lighter border thickness
                doc.setDrawColor(200, 200, 200);  // Set light gray border color
                
                // Draw the border (rectangle) around each body cell
                doc.rect(data.cell.x, data.cell.y, data.cell.width, data.cell.height);
            }
        }
    }
});


        
 

 const maxRowsPerPage = 25;  // Max rows per page to prevent table overflow
 
var startY = doc.lastAutoTable.finalY + 3;  // Minimized top margin, adjust as needed

// Create a "table-like" structure with two rows (Previous Balance and Net Total)
var footerData = [];

// Check if footerText[0] (Previous Balance) exists before adding it
if (footerText[0] && footerText[0].includes(':')) {
    let previousBalanceValue = footerText[0].split(':')[1].trim();

    // Convert to number for validation
    let numericValue = parseFloat(previousBalanceValue);

    // Add to footerData only if the value is not blank, not zero, and not NaN
    if (previousBalanceValue !== "" && numericValue !== 0 && !isNaN(numericValue)) {
        footerData.push(['Previous Balance', previousBalanceValue]);
    }
}


// Check if footerText[1] (Total Bill Amount) exists before adding it
if (footerText[1] && footerText[1].includes(':')) {
    footerData.push(['Total Bill Amount', footerText[1].split(':')[1].trim()]);
}

// Define column widths, assuming you want them to have equal width
var columnWidths = [0.4, 0.6]; // Adjust these values for your design (total should add up to 1)

// Use autoTable to create the "table" without borders
doc.autoTable({
    startY: startY,
    head: [['', '']], // Empty header (no headers for this footer table)
    body: footerData,
    columnStyles: {
        0: { halign: 'left', fontStyle: 'bold' },  // Align the left column to the left (for labels) and bold
        1: { halign: 'right', fontStyle: 'bold' }, // Align the right column to the right (for values) and bold
    },
    columnWidth: columnWidths,
    theme: 'plain',  // No borders for the table
    margin: { left: 14, right: 14 }, // Set left and right margins
});

// Get the position of the last added row (Net Total)
var lastRowY = doc.lastAutoTable.finalY;

// Draw a line between Previous Balance and Net Total, immediately after Previous Balance
var lineStartX = 14;  // Start line at left margin
var lineEndX = doc.internal.pageSize.width - 14; // End line at right margin
doc.line(lineStartX, lastRowY - 7, lineEndX, lastRowY - 7); // Line just below Previous Balance

// ADD FOOTER ADDRESS - ALWAYS SHOWS ON LAST PAGE
var addressY = lastRowY + 5;
doc.setFont("helvetica", "normal").setFontSize(9);
doc.text('Office: Shop # 1, Sheikh Plaza Near Lieda Office Nazar Chowrangi Hite HuB , Balochistan.', pageWidth / 2, addressY, { align: 'center' });

// Check if there's enough space for the footer content
var pageHeight = doc.internal.pageSize.height;
var contentHeight = addressY + 10;  // Total height used by content and lines

// If there's not enough space on the page for the footer content, add a new page
if (contentHeight > pageHeight - 30) {  // Leave some space at the bottom (e.g., 30 units)
    doc.addPage();  // Add a new page if necessary
    // Add address on new page as well
    doc.setFont("helvetica", "normal").setFontSize(9);
    doc.text('Office: Shop # 1, Sheikh Plaza Near Lieda Office Nazar Chowrangi Hite HuB , Balochistan.', pageWidth / 2, 20, { align: 'center' });
}

        //doc.save('datatable_export.pdf'); // Save the generated PDF
         // Save PDF
    const fileName = title + "_" + new Date().toISOString().split('T')[0] + ".pdf";
    doc.save(fileName);
    } else {
        alert('Please select at least one row to export.');
    }
});





    });
</script>
<style>
    #columnSelect {
        width: 200px; /* Set width as needed */
        padding: 10px;
        font-size: 14px;
        border: 2px solid #ccc; /* Border color */
        border-radius: 5px; /* Rounded corners */
        background-color: #f9f9f9;
        color: #333;
        transition: border-color 0.3s ease, box-shadow 0.3s ease;
    }

    #columnSelect:hover {
        border-color: #007bff; /* Change border color on hover */
    }

    #columnSelect:focus {
        outline: none; /* Remove the default focus outline */
        border-color: #007bff; /* Add border color when focused */
        box-shadow: 0 0 5px rgba(0, 123, 255, 0.5); /* Optional shadow effect */
    }

    option {
        padding: 10px;
        font-size: 14px;
    }
</style>
<script>
    $(document).ready(function() {
        // Initialize Select2 on the select box
        $('#columnSelect').select2({
            placeholder: "Select columns",  // Placeholder text
            allowClear: true,               // Allow clearing the selection
            width: '100%'                   // Full width of the select box
        });
    });
</script>





<!-- Include Select2 CSS -->
<link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet" />


<script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>




<!-- Export a Table to PDF - END -->

</div>

</body>
</html>
<?php //} ?>