<?php
session_start();

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

<!DOCTYPE html>
  <?php  
  if(isset($_GET['search'])){ ?><html>
  
          
<head>
    <meta charset="utf-8" />
   <?php
 include('includes/config.php');
          $vendor=$_GET['vendor'];
          $fromdate = $_GET['from_date'];
          $todate =$_GET['to_date'];
          $results = mysqli_query($con, "SELECT * FROM `payment_generate` as p  WHERE p.vendor_id ='".$vendor."' AND p.p_date BETWEEN '".$fromdate."' AND '".$todate."' ORDER BY p.p_date ASC LIMIT 1");

      $frdate = $_GET['from_date']; $frmdates =date("j-M-Y",strtotime($frdate)); 
      $todate =$_GET['to_date']; $tomdates = date("j-M-Y",strtotime($todate));
      
      
       while($rows = mysqli_fetch_assoc($results)) {
       
       ?> <title><?php $company = $rows['vendor_id']; echo ("$company.\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/soft-lg-1.png" type="image/x-icon" >
 <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://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>
      <script src="main/assets/js/html2canvas.js"></script>
</head>



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

<div class="page-header">
                                            
                                                
                                         
                                          <?php
if(!$_GET['hide_logo']){
    $img_file = 'images/logos/madinaconst-lgnew.png';

    // Get image MIME type and base64 encode the image
    $imageInfo = getimagesize($img_file);
    $src = 'data:' . $imageInfo['mime'] . ';base64,' . base64_encode(file_get_contents($img_file));

    // Display the image
    echo '<center><div class="logo"><img height="250" width="350" src="' . $src . '"></div></center>';
}
?>

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

</div>


<?php
include('includes/config.php');



?>


    
<table id="example" class="table table-striped table-bordered dt-responsive nowrap" style="width:100%">                  
                        

                  <thead>
                      
                  <tr>
                     <th class="text-center">SNO</th>
                    <th class="text-center">Date</th>
                    <!--<th>Vendor</th>-->
                     <th class="text-center">Bill Amount</th>
                    <th class="text-center">CH#</th>
                    <th class="text-center">Received Amount</th>
                    <th class="text-center">Balance Amount</th>
                   
                  </tr>
                  </thead>
                  <tbody>

 <?php   include('includes/config.php');
       
          $vendor=$_GET['vendor'];
          $fromdate = $_GET['from_date'];
          $todate =$_GET['to_date'];
          
      $no=0;
     

 $result = mysqli_query($con, "SELECT * FROM `payment_generate` as p   WHERE p.vendor_id  ='".$vendor."' AND p.p_date BETWEEN '".$fromdate."' AND '".$todate."' ORDER BY p.p_date ASC, p.pay_id ASC");

      
       
      
       while($row = mysqli_fetch_assoc($result)) {
       $no++;    
    
     // $amount = $row['payment_totalamount'];
      $generatedamount =$row['generate_amount'];
     // $balanceamount =  $amount - $generatedamount;
      
      $totalreceived +=$generatedamount;
     
       ?>
       
        <?php   include('includes/config.php');
       
          $vendor=$_GET['vendor'];
          $fromdate = $_GET['from_date'];
          $todate =$_GET['to_date'];
          
      $nos=0;
        $rows=0;

 $results = mysqli_query($con, "Select sum(ship_total) as totalamount FROM shipment  WHERE vendor_id  ='".$vendor."'  AND s_status='1'");

       $temp;
      
      
      
       while($rows = mysqli_fetch_assoc($results)) {
       $nos++;    
    
      $shiptotalamounts = $rows['totalamount'];
      
    
      
       
       ?>
       <?php
  //additional balance by vendor
    include('includes/config.php');
               
     
      $resultres = mysqli_query($con, "SELECT sum(add_balance) as addtionalbalance FROM `vendorAdditional_balance` WHERE vendor_id='$vendor'");
       while($rowrev = mysqli_fetch_assoc($resultres)) {
        $newtotalamount = $rowrev['addtionalbalance'];
        
        
        $shiptotalamount = $shiptotalamounts += $newtotalamount;
        
        
        if(!$newtotalamount)
        {
              $balanceamount =  $shiptotalamounts - $generatedamount;
    
        }
        else 
        {
              $balanceamount =  $shiptotalamount - $generatedamount;
        }
        
  ?>
       
       
       
                      <tr>
                     <td class="text-center"><?php echo $no; ?></td>
                     <td class="text-center">
                     <?php $ordate = $row['p_date']; echo date("d/m/Y", strtotime($ordate));
                     //$ordates =date("M-j-Y",strtotime($ordate)); echo $ordates; ?>
                     </td>
                     <?php if($no==1){ ?>
                    <td class="text-center"><?php echo  $shiptotalamount; ?></td>
                    <?php } else{ ?>
                    <td class="text-center"><?php echo  isset($temp)?$temp:$shiptotalamount; ?></td>
                    <?php }  ?>
                    <td class="text-center"><?php echo $paymenttype =  $row['payment_type']; if($paymenttype == 'Cheque') { ?>
                    : <?php  echo $row['cheque_no']; ?>
                    <?php } else if($paymenttype == 'Transefer-Via-Account') { echo '<br>'. $row['bank_name'];  } ?>
                    </td>
                    <td class="text-center"><?php echo  $generatedamount; ?></td>
                   <?php if($no==1){ ?>
                    <td class="text-center"><?php echo $balanceamount; ?></td>
                    <?php } else{ ?>
                     <td class="text-center"><?php echo  $temp - $generatedamount; ?></td>
                     <?php } ?>
                    <?php 
                    if($no==1)
                    {
                        $temp = $balanceamount;
                    }
                    else
                    {
                        $temp = $temp - $generatedamount;
                    }
                     
                    ?>
                    
                     
                       
                      </tr>
                     
 <?php } } 
 
 
 // 
       }
 ?>
                  </tbody>
              <tfoot>
                  <tr>
                    <th></th>
                    <th><?php
                 
           // Cast to integer to remove decimal part and trailing zeros
    $formattedTotal = (int)$shiptotalamounts;
    
    
    $allbalanceamount = $formattedTotal -$totalreceived;

    //echo $formattedTotal;
  ?>
 </th>
                    <th class="text-center">Pre Total:<?php echo $formattedTotal; ?></th>
                    <th class="text-center"></th>
                    
                    <th class="text-center">Recv:<?php echo $totalreceived;?></th>
                    <th class="text-center">Bal:<?php //balance amount
                   echo $allbalanceamount; ?></th>
                    
                    </tr>
                  </tfoot>
                </table>
                 </tbody>
    </table>
   
</div>
<?php } ?>
<!-- you need to include the shieldui css and js assets in order for the components to work -->
  <script src="https://code.jquery.com/jquery-3.3.1.js"></script>
    <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/1.5.2/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/1.5.2/js/buttons.bootstrap4.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/pdfmake.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/vfs_fonts.js"></script>
    <script src="https://cdn.datatables.net/buttons/1.5.2/js/buttons.html5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/1.5.2/js/buttons.print.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/1.5.2/js/buttons.colVis.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.2.3/js/dataTables.responsive.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.2.3/js/responsive.bootstrap4.min.js"></script>
    <script>
// $(document).ready(function() {
    
  
//     $('#example').DataTable( {
//         dom: 'Bfrtip',
//         //"paging": false,
          
//         buttons: [
//             { extend: 'copyHtml5', footer: true },
//             { extend: 'excelHtml5', footer: true },
//           // { extend: 'csvHtml5', footer: true },
//             { extend: 'pdfHtml5',header:true, footer: true, orientation: 'portrait',
//         pageSize: 'A4', customize:  function (doc) { 
                     
                     
//                     doc.layout = 'lightHorizotalLines;'
//                   // doc.pageMargins = [10, 0, 60, 0];
//                     doc.pageMargins = [45, 30, 50, 90];
//                     doc.defaultStyle.fontSize = 8;
//                     doc.styles.tableHeader.fontSize = 9;
//                     doc.styles.title.fontSize = 10;
                      
//                   // Get the table object from the PDF document
//                     var table = doc.content[1].table;
                    
//                     // Set the widths of the columns here
//                     table.widths = ['5%','10%', '25%', '20%',  '20%', '20%'];
                    
                    
//                      // Set text alignment for td cells to center
//                     for (var rowIndex = 0; rowIndex < table.body.length; rowIndex++) {
//                         var row = table.body[rowIndex];
//                         row.forEach(function(cell) {
//                             cell.alignment = 'center';
//                         });
//                     }
                    
//                     // Customize the tfoot style
//                     if (table.footer && table.footer.length > 0) {
//     var footerRow = table.footer[table.footer.length - 1];
//     footerRow.forEach(function(cell) {
//         cell.alignment = 'center';
//         cell.fontSize = 7; // Adjust the font size as needed
//     });
// }
//               <?php if(!$_GET['hide_logo']){ ?> 
//     doc.content.splice(0, 0, {
//         alignment: 'center',
//         margin: [0, 0, 0, 0],
//         image: '<?php echo $src; ?>',
//         width: 200,
//         height: 150,
//     });
    
//              doc.footer = function (currentPage, pageCount) {
//             return {
//                 text: 'Office: Shop # 1, Sheikh Plaza Near Lieda Office Nazar Chowrangi Hite HuB , Balochistan.',
//                 alignment: 'center',
//                 fontSize: 10, // Adjust the font size as needed
//             };
//         };
    
    
// <?php } else { ?>
//     // Adjust the margin of surrounding content to simulate the space where the logo would be
//     doc.content[0].margin[1] += 160; // Increase the top margin by 10 units (adjustable)
// <?php } ?>
                     
            
                    
                    
                    
                           
//          } }
        
            
//         ]
//     } );
// } );


     </script>
    
<!-- Export a Table to PDF - END -->
<script>
$(document).ready(function() {
    
    $('#example').DataTable( {
        dom: 'Bfrtip',
        //"paging": false,
          
        buttons: [
            { extend: 'copyHtml5', footer: true },
            { extend: 'excelHtml5', footer: true },
          // { extend: 'csvHtml5', footer: true },
            { extend: 'pdfHtml5',header:true, footer: true, orientation: 'landscape',
        pageSize: 'A4', customize:  function (doc) { 
                     
                    // Default page margins for landscape
                    doc.pageMargins = [45, 30, 50, 90];
                    doc.defaultStyle.fontSize = 6.4;
                    doc.styles.tableHeader.fontSize = 7;
                    doc.styles.title.fontSize = 10;
                  
                    var table = doc.content[1].table;

                    // Set the widths of the columns here
                    table.widths = ['5%', '9%', '10%', '10%','10%', '10%', '5%', '10%', '7%', '9%', '9%', '9%'];

                    // Fetch PHP values for Bill No and Bill Date
                    var billNo = '<?php echo $billNo; ?>';
                    var billDate = '<?php echo $billDate; ?>';
                    var details = '<?php echo $details; ?>';
                    var preBalance = '<?php echo $preBalance ?>';
                    var totalshipment = '<?php echo $totalship; ?>';
                    var totalBillAmount = '<?php echo $totalbillAmount ?>';
                    
                    // Set custom header with details
                    var headerContent = [
                        [
                            { text: billNo ? 'Bill No: ' + billNo : '', alignment: 'left', fontSize: 10, bold: true }, 
                            { text: billDate ? '<?php echo date("j-M-Y", strtotime($billDate)); ?>' : '', alignment: 'right', fontSize: 10, bold: true }
                        ],
                        [
                            { text: details ? details : '', alignment: 'left', fontSize: 9, bold: true, italics: true, colSpan: 2 }
                        ]
                    ];

                    // Add the header to the PDF
                    doc.content.unshift({
                        margin: [0, 0, 0, 10],
                        table: {
                            widths: ['50%', '50%'],
                            body: headerContent
                        },
                        layout: 'noBorders'
                    });

                    // Set text alignment for td cells to center
                    for (var rowIndex = 0; rowIndex < table.body.length; rowIndex++) {
                        var row = table.body[rowIndex];
                        row.forEach(function(cell) {
                            cell.alignment = 'center';
                        });
                    }

                    // Set the pageBreak property for the entire column
                    var columnIndex = 0;
                    table.body.forEach(function(row) {
                        row[columnIndex].pageBreak = 'avoid';
                    });
                    
                    // Customize the tfoot style
                    if (table.footer && table.footer.length > 0) {
                        var footerRow = table.footer[table.footer.length - 1];
                        footerRow.forEach(function(cell) {
                            cell.alignment = 'center';
                            cell.fontSize = 5;
                        });
                    }
                    
                    <?php if(!$_GET['hide_logo']){ ?> 
                        // JAB LOGO DIKHE - Logo add karo
                        doc.content.splice(0, 0, {
                            alignment: 'center',
                            margin: [0, 0, 0, 0],
                            image: '<?php echo $src; ?>',
                            width: 200,
                            height: 150,
                        });
                        
                        // Logo ke baad space add karo
                        doc.content.splice(1, 0, {
                            text: ' ',
                            margin: [0, 0, 0, 5]
                        });
                        
                    <?php } else { ?>
                        // JAB LOGO HIDE HO - Same space rakhne ke liye
                        // Logo ki jagah khali space add karo taake layout same rahe
                        
                        // Option 1: Khali jagah add karo (white space) - RECOMMENDED
                        doc.content.splice(0, 0, {
                            text: ' ',
                            alignment: 'center',
                            margin: [0, 0, 0, 0],
                            fontSize: 1,
                            height: 150  // Logo ki height jitni khali space
                        });
                        
                        // Uske baad wahi 5 margin ka space
                        doc.content.splice(1, 0, {
                            text: ' ',
                            margin: [0, 0, 0, 5]
                        });
                        
                        // Top margin wahi rakho 30 (change mat karo)
                        doc.pageMargins = [45, 30, 50, 90];
                        
                    <?php } ?>
                    
                    // Add the "Previous Balance" and "Total Bill Amount" at the bottom right (ALWAYS SHOW)
                    if (preBalance) {
                        doc.content.push({
                            margin: [0, 10, 0, 0],
                            table: {
                                widths: ['50%', '50%'],
                                body: [
                                    [
                                        { text: 'Previous Balance:', alignment: 'left', fontSize: 10, bold: true },
                                        { text: preBalance || 0, alignment: 'right', fontSize: 10, bold: true }
                                    ],
                                    [
                                        { text: 'Total Bill Amount:', alignment: 'left', fontSize: 10, bold: true },
                                        { text: totalBillAmount || totalshipment || 0, alignment: 'right', fontSize: 10, bold: true }
                                    ]
                                ]
                            },
                            layout: {
                                hLineWidth: function(i, node) { 
                                    if (i === 0 || i === node.table.body.length) {
                                        return 0;
                                    }
                                    if (i === 0 || i === 1) {
                                        return 2;
                                    } 
                                    return 0.5;
                                },
                                vLineWidth: function(i) { 
                                    return 0.5;
                                },
                                hLineColor: function(i, node) { 
                                    if (i === 0 || i === 1) {
                                        return '#000000';
                                    }
                                    return '#d3d3d3';
                                },
                                vLineColor: function(i) { 
                                    return '#d3d3d3';
                                },
                                paddingLeft: function(i) { return 10; },
                                paddingRight: function(i) { return 10; },
                                paddingTop: function(i) { return 5; },
                                paddingBottom: function(i) { return 5; }
                            }
                        });
                    }
                    
                    // FOOTER ADDRESS - ALWAYS SHOWS ON LAST PAGE
                    doc.footer = function (currentPage, pageCount) {
                        if (currentPage === pageCount) {
                            return {
                               text: 'Office: Shop # 1, Sheikh Plaza Near Lieda Office Nazar Chowrangi Hite HuB , Balochistan.',
                                alignment: 'center',
                                fontSize: 10,
                                margin: [0, 5, 0, 5]
                            };
                        } else {
                            return null;
                        }
                    };
                    
         } }
        
            
        ]
    } );
} );
</script>
     
  
</div>
    <?php } else { echo '<title>Record Not Found</title>'; } ?>
</body>
</html>