<?php
include 'config.php'; // DB connection file

// 🔹 Pagination setup
$limit = 10; // Records per page
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
$offset = ($page - 1) * $limit;

// 🔹 Search functionality
$search = "";
$where = "";
if (isset($_GET['search']) && $_GET['search'] != "") {
    $search = mysqli_real_escape_string($con, $_GET['search']);
    $where = "WHERE name LIKE '%$search%'";
}

// 🔹 Total records count
$totalRes = mysqli_query($con, "SELECT COUNT(*) as total FROM sales_man $where");
$totalRow = mysqli_fetch_assoc($totalRes);
$totalRecords = $totalRow['total'];
$totalPages = ceil($totalRecords / $limit);

// 🔹 Fetch paginated records
$result = mysqli_query($con, "SELECT * FROM sales_man $where ORDER BY id DESC LIMIT $limit OFFSET $offset");

// 🔹 Fetch company name
$companyRes = mysqli_query($con, "SELECT company_name FROM companies LIMIT 1");
$companyRow = mysqli_fetch_assoc($companyRes);
$companyName = $companyRow ? $companyRow['company_name'] : "Company Name";
?>
<html><head><script src="chrome-extension://mooikfkahbdckldjjndioackbalphokd/assets/prompt.js"></script></head>
   <body style="margin:0px; font-family:Arial, Helvetica, sans-serif; font-size:12px;" cz-shortcut-listen="true">
      <br>
      <style>
         @media print {
         thead {display: table-header-group;}
         .b { display:none;}
         }
      </style>
      <style>
       table {
            width: 100%;
            border-collapse: collapse;
            font-size: 11px;
        }

        th, td {
            border: 1px dashed #999999!important;
            padding: 5px;
            text-align: left;
        }
   .container {
            width: 80%;
            margin: 0 auto;
            padding: 20px;
/*            border: 1px solid #ccc;*/
            background-color: #f9f9f9;
        }
        th {
            background-color: #CCCCCC;
        }
         .button-row {
         display: flex;              /* Use flexbox for alignment */
         justify-content: center;    /* Center the buttons horizontally */
         align-items: center;        /* Center the buttons vertically (if needed) */
         margin-top: 20px;           /* Add some spacing from other content */
         }
         button {
         padding: 10px 20px;         /* Add padding to the buttons */
         margin: 10 10px;             /* Add spacing between the buttons */
         font-size: 16px;            /* Adjust font size */
         cursor: pointer;            /* Change cursor on hover */
         background-color: #407cbb;  /* Button background color */
         color: white;               /* Button text color */
         border: none;               /* Remove border */
         border-radius: 5px;         /* Rounded corners */
         transition: background-color 0.3s ease; /* Add hover transition */
         }
         button:hover {
         background-color: #0056b3; /* Darker background on hover */
         }
          @media print {
            .container {
                width: 95%;
                margin: 0;
                padding-left: 50px;
                border: none;
                background-color: transparent;
            }
        }
      </style>
      <div class="button-row">
         <button class="b" onclick="printContent()">Print</button>
         <button class="b" id="downloadPdfBtn">Download</button>
         <button class="b" onclick="window.location.href='add_sm.php'">Back</button>
      </div>
      <div id="invoice" class="container" style="height:1010px; margin:0px auto; background-color:#FFFFFF; padding:0px 0px 25px 0;">
         <div style="  height:1100px; margin:0px auto;">
            <div style="text-align:left; margin-top:5px;font-weight:bold; font-size:20px;display:flex;justify-content:space-between;align-items:center;">
              <!-- Task Register -->
                <strong style="float: left; color:red;">
                    <u><?php echo htmlspecialchars($companyName); ?></u>
                </strong>
                <small style="font-size:13px;font-weight:100;">
                    Date: <?php echo date("d/m/Y"); ?>
                </small>
                </div>
                <div style="width:100%;">
                <p style="margin-top:5px;margin-bottom:5px;display:flex;justify-content:space-between;">
                    Report: Sales Man Register Report
                </p>

               <!-- <p>Report of: All Branches of All Staffs  from 10.01.2025 to 11.01.2025</p> -->
                               <table style="width:100%; font-size:11px; border:none;">
                   <thead>
                      <tr style="text-align:center; background-color:#CCCCCC;">
                         <th style="width:30px;border:solid 1px #999999;text-align: left">#</th>
                         <th style="width:150px;border:solid 1px #999999;text-align:left;">Name</th>
                         <th style="width:80px;border:solid 1px #999999;text-align: left;">Position</th>
                         <th style="width:80px;border:solid 1px #999999;text-align: left;">Contact No.</th>
                         <th style="width:100px;border:solid 1px #999999;text-align: left;">Email</th>
                         <th style="width:150px;border:solid 1px #999999;text-align:left;">Address</th>
                         <th style="width:30px;border:solid 1px #999999;text-align: right;"> </th>
                      </tr>
                   </thead>
                  <tbody>
                    <?php 
                  if (mysqli_num_rows($result) > 0) {
                      $i = $offset + 1;
                      while ($row = mysqli_fetch_assoc($result)) { ?>
                          <tr>
                              <td><?php echo $i; ?></td>
                              <td><?php echo htmlspecialchars($row['name']); ?></td>
                              <td><?php echo htmlspecialchars($row['position']); ?></td>
                              <td><?php echo htmlspecialchars($row['contact']); ?></td>
                              <td><?php echo htmlspecialchars($row['email']); ?></td>
                              <td><?php echo htmlspecialchars($row['address']); ?></td>
                              <td></td>
                          </tr>
                      <?php $i++; } 
                  } else { ?>
                      <tr><td colspan="7" style="text-align:center;">No results found</td></tr>
                  <?php } ?>
                    </tbody>

                  </table>

               <style>
    table {
    width: 100%;
    font-size: 11px;
    border-collapse: collapse;
    table-layout: fixed;
}

th {
    background-color: #CCCCCC;
    text-align: left;
}

</style>
                           </div>
              <div class="container" style="
            position: fixed;
    bottom: 10px;
    left: 0;
    display: flex
;
    justify-content: space-around;
    align-items: center;
    font-size: 15px;
    padding: 5px 15px;
    background: white;
    z-index: 9999;
    width: 100%;">
            <?php
                        function getClientIP() {
                            if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
                                return $_SERVER['HTTP_CLIENT_IP'];
                            } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                                return $_SERVER['HTTP_X_FORWARDED_FOR'];
                            } else {
                                return $_SERVER['REMOTE_ADDR'];
                            }
                        }
                        $clientIP = getClientIP();
                    ?>
        
            <small>IP: <?php echo $clientIP; ?></small>
                
                <small><div class="pagination">
                <?php if($page > 1): ?>
                    <a href="?page=<?php echo $page-1; ?>&search=<?php echo urlencode($search); ?>">&laquo; Prev</a>
                <?php endif; ?>
                
                <?php for($p=1; $p <= $totalPages; $p++): ?>
                    <a href="?page=<?php echo $p; ?>&search=<?php echo urlencode($search); ?>" class="<?php echo ($p==$page)?'active':''; ?>">
                        <?php echo $p; ?>
                    </a>
                <?php endfor; ?>
                
                <?php if($page < $totalPages): ?>
                    <a href="?page=<?php echo $page+1; ?>&search=<?php echo urlencode($search); ?>">Next &raquo;</a>
                <?php endif; ?>
            </div></small>
                 <small>By PROGRAMERS.in</small>
            </div>
            <br>
            <br>
         </div>
      </div>
      <script>
         // Print the content
         function printContent() {
             window.print();
         }
      </script>
      <!--- To download report -->
      <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/html2canvas/1.4.1/html2canvas.min.js"></script>
      <script>
         document.getElementById('downloadPdfBtn').addEventListener('click', function () {
             const element = document.getElementById('invoice'); // Get the table element
         
             // Store original styles
             const originalBackgroundColor = element.style.backgroundColor;
             const originalTextColor = element.style.color;
         
             // Apply temporary styles
             element.style.backgroundColor = 'white';
             element.style.color = 'black';
         
             html2canvas(element, {
                 scale: 2, // Improve quality of the output
             }).then((canvas) => {
                 const imgData = canvas.toDataURL('image/png'); // Convert to image
                 const pdf = new jspdf.jsPDF('p', 'mm', 'a4'); // Create a PDF object
         
                 // Calculate dimensions for the image to fit A4
                 const imgWidth = 190; // A4 width minus margins
                 const imgHeight = (canvas.height * imgWidth) / canvas.width;
         
                 pdf.addImage(imgData, 'PNG', 10, 10, imgWidth, imgHeight); // Add image to PDF
                 pdf.save('Salesman Register.pdf'); // Save as PDF
         
                 // Restore original styles
                 element.style.backgroundColor = originalBackgroundColor;
                 element.style.color = originalTextColor;
             });
         });
      </script>
   
</body></html>