
<?php
session_start();
// Check if branch_id exists in session
if (!isset($_SESSION['branch_id']) || empty($_SESSION['branch_id'])) {
    // Redirect to login page if session not set
    header("Location: https://xtodo.programersapps.com/systemsoft/");
    exit;
}

// Store branch_id in a variable
$bid = $_SESSION['branch_id'];
include 'branch_connection.php';

$proposalId = $_GET['orderid'] ?? 0;
$token      = trim($_GET['token'] ?? '');

if (!$proposalId) {
    die("Unauthorized or link expired");
}

/* ===============================
   1️⃣ Validate proposal + token
================================ */
$res = mysqli_query($conn, "
    SELECT id, status ,approval_token
    FROM proposals
    WHERE id='$proposalId'
");

if (!$res || mysqli_num_rows($res) === 0) {
    die("Unauthorized or link expired");
}

$approveproposal = mysqli_fetch_assoc($res);
$approvestatus   = $approveproposal['status'];
$approval_token =  $approveproposal['approval_token'];
$isEmailView     = true;

/* ===============================
   2️⃣ If already approved
================================ */
// if ($approvestatus === 'Approved') {
//     echo "<script>alert('This proposal is already approved');</script>";
// }
?>
<html lang="en">
   <head>
      <link rel="preconnect" href="https://fonts.googleapis.com">
      <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin="">
      <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
      <link href="https://fonts.googleapis.com/css2?family=Bebas+Neue&amp;display=swap" rel="stylesheet">
      <meta charset="UTF-8">
      <title>PROPOSAL FORM</title>
      <style>
         body {
         font-family: Arial, sans-serif;
         margin: 15px;
         color: #333;
         font-size: 10px;
         }
         .container {
         width: 100%;
         max-width: 1200px; /* You can change this to 960px, 1140px, etc. */
         margin-left: auto;
         margin-right: auto;
         /* padding-left: 15px;
         padding-right: 15px; */
         box-sizing: border-box;
         }
         table {
         border-collapse: collapse;
         width: 100%;
         }
         h1, h2, h3 {
         margin: 0;
         padding: 0;
         }
         .header, .footer {
         text-align: center;
         margin-bottom: 0;
         }
         .work-order-header {
         display: flex;
         justify-content: space-between;
         }
         .work-order-box {
         border: 1px solid #ccc;
         padding: 10px;
         margin-bottom: 20px;
         }
         .section-title {
         background-color: #0072C6;
         color: #fff;
         padding: 5px;
         }
         .table-bordered th, .table-bordered td {
         border: 1px solid #000;
         padding: 8px;
         }
         .text-right {
         text-align: right;
         }
         .text-center {
         text-align: center;
         }
         .highlight {
         background-color:black;
         color: white;
         }
         .total-row {
         font-weight: bold;
         background-color: #D9EDF7;
         }
         .img-fluid {
         max-width: 100%;
         height: auto;
         display: block;
         }
         .head-terms{
         font-size: 14px;
         text-align: center;
         }
         @media print {
         body{
         font-size: 10px;
         }
         .terms{
         font-size: 10px!important;
         }
         .head-terms{
         font-size: 9px;
         text-align: center;
         }
         .inner-span{
         font-size: 10px;
         }
         }
         .border-box{
         border: 2px solid black;
         padding: 10px 20px 0px 20px;
         border-radius: 10px;
         }
         @media print {
         .page-break {
         page-break-before: always;
         }
         }
         .card {
         width: 18rem; /* 288px */
         border: 1px solid black;
         border-radius: 0.25rem;
         overflow: hidden;
         font-family: Arial, sans-serif;
         background-color: #fff;
         /*          box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05); */
         }
         .card-header {
         padding: 0.50rem 1rem;
         background-color: black;
         border-bottom: 1px solid #dee2e6;
         font-weight: bold;
         color: white;
         }
         .list-group {
         list-style: none;
         margin: 0;
         padding: 0;
         }
         .list-group-item {
         padding: 0.50rem 1rem;
         border-bottom: 1px solid #dee2e6;
         }
         .list-group-item:last-child {
         border-bottom: none;
         }
         .img-fluid{
         max-width: 75%;
         height: auto;
         display: block;
         }
         .bebas-neue-regular {
         font-family: "Bebas Neue", sans-serif;
         font-weight: 400;
         font-style: normal;
         }
         .ribbon-head {
         position: relative;
         margin: 0 auto 20px;
         padding: 5px 30px;
         text-align: center;
         background-color: black;
         color: white;
         font-family: "Bebas Neue", sans-serif;
         }
         .ribbon-head::before, .ribbon-head::after {
         content: '';
         width: 80px;
         height: 100%;
         background-color: #000000c9;
         /* position ribbon ends behind and slightly lower */
         position: absolute;
         z-index: -1;
         top: 20px;
         /* clip ribbon end shape */
         clip-path: polygon(0 0, 100% 0, 100% 100%, 0 100%, 25% 50%);
         /* draw and position the folded ribbon bit */
         background-image: linear-gradient(45deg, transparent 50%, #544d49 50%);
         background-size: 20px 20px;
         background-repeat: no-repeat;
         background-position: bottom right;
         }
         .ribbon-head::before {
         left: -45px;
         }
         .ribbon-head::after {
         right: -45px;
         transform: scaleX(-1); /* flip horizontally */
         }
         /* everything below is for demo appearances and not important to the concept */
         @media (max-width: 400px) {
         .ribbon-head { font-size: 1.5rem; }
         }
         @media print {
         body {
         -webkit-print-color-adjust: exact !important;
         print-color-adjust: exact !important;
         }
         @page {
         size: A4;          /* Force A4 sheet */
         margin: 0 !important;  /* Remove default page margins */
         }
         .proposal-content {
         max-height: 750px; /* Approximate page height */
         overflow: visible; /* Allow content to flow to next page */
         page-break-inside: avoid; /* Avoid breaking inside content blocks */
         }
         .page-break {
         page-break-after: always;
         }
         }
      </style>
      <style>
         @media print {
         button {
         display: none;
         }
         }
      </style>
      <div style="text-align: center; margin-top: 20px; display: flex; justify-content: center; gap: 15px;">
         <!-- Print Button -->
         <button onclick="window.print()" 
            style="
            background: linear-gradient(90deg, #333, #000);
            color: #fff;
            border: none;
            padding: 12px 28px;
            font-size: 16px;
            cursor: pointer;
            border-radius: 8px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.3);
            transition: all 0.3s ease;
            "
            onmouseover="this.style.transform='scale(1.05)'; this.style.background='linear-gradient(90deg, #555, #111)';"
            onmouseout="this.style.transform='scale(1)'; this.style.background='linear-gradient(90deg, #333, #000)';"
            >
         Print
         </button>
         
         
                 <?php if ($token && $approvestatus == 'Pending') { ?>
    <!-- Token exists → Direct approve -->
    <button onclick="handleApproval()"
        style="
        background: linear-gradient(90deg, #1e7e34, #28a745);
        color: #fff;
        border: none;
        padding: 12px 28px;
        font-size: 16px;
        cursor: pointer;
        border-radius: 8px;
        box-shadow: 0 4px 6px rgba(0,0,0,0.3);
        transition: all 0.3s ease;"
        onmouseover="this.style.transform='scale(1.05)'; this.style.background='linear-gradient(90deg, #218838, #34ce57)';"
        onmouseout="this.style.transform='scale(1)'; this.style.background='linear-gradient(90deg, #1e7e34, #28a745)';">
        For Approval
    </button>
<?php } else if( $approvestatus == 'Pending' && $approval_token ==''){ ?>
    <!-- No token → Popup -->
    <button onclick="handleApproval()"
        style="
        background: linear-gradient(90deg, #1e7e34, #28a745);
        color: #fff;
        border: none;
        padding: 12px 28px;
        font-size: 16px;
        cursor: pointer;
        border-radius: 8px;
        box-shadow: 0 4px 6px rgba(0,0,0,0.3);
        transition: all 0.3s ease;"
        onmouseover="this.style.transform='scale(1.05)'; this.style.background='linear-gradient(90deg, #218838, #34ce57)';"
        onmouseout="this.style.transform='scale(1)'; this.style.background='linear-gradient(90deg, #1e7e34, #28a745)';">
        Send for Approval
    </button>
<?php } ?>

         <!-- Back Button -->
         <button onclick="history.back()" 
            style="
            background: linear-gradient(90deg, #777, #444);
            color: #fff;
            border: none;
            padding: 12px 28px;
            font-size: 16px;
            cursor: pointer;
            border-radius: 8px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.3);
            transition: all 0.3s ease;
            "
            onmouseover="this.style.transform='scale(1.05)'; this.style.background='linear-gradient(90deg, #999, #666)';"
            onmouseout="this.style.transform='scale(1)'; this.style.background='linear-gradient(90deg, #777, #444)';"
            >
         Back
         </button>
      </div>
   </head>
   <?php
        // session_start();
        // $bid = $_SESSION['branch_id'];
        // include 'branch_connection.php';
      
        $branch_sql = "SELECT * FROM branches WHERE id = '$bid'";
        $branch_res = mysqli_query($conn, $branch_sql);
        
        $branch_row = mysqli_fetch_assoc($branch_res);
        
      
      $orderid = $_GET['orderid'];
      
      // 1. Get proposal data first (financial / proposal details)
       $proposal_sql = "SELECT * FROM proposals WHERE id = '$orderid'";
      $proposal_res = mysqli_query($conn, $proposal_sql);
      
      if(!$proposal_res || mysqli_num_rows($proposal_res) == 0){
          die("Proposal not found.");
      }
      
      $proposal = mysqli_fetch_assoc($proposal_res);
      $proposal_no  = $proposal['proposal_no'];
      $order_date = $proposal['created_at'];
      $qtnby = $proposal['qtnby'];
      $currency = $proposal['currency'];
      // print_r($proposal);
      $lead_id = $proposal['lead_id'];
      
      // 2. Get the positive lead data using lead_id (customer / project details)
     // 2. Try fetching from tb_positiveleads first
$lead_sql = "SELECT p.*, 
                    s.segment_name,
                    c.name AS category_name
             FROM tb_positiveleads p
             LEFT JOIN segments s ON p.segment = s.id
             LEFT JOIN categories c ON p.category = c.id
             WHERE p.id = '$lead_id'";

$lead_res = mysqli_query($conn, $lead_sql);

if ($lead_res && mysqli_num_rows($lead_res) > 0) {

    // ✅ Found in positive leads
    $order = mysqli_fetch_assoc($lead_res);
    $lead_source = 'positivelead';

} else {

    // 3. If not found, try marketing_order
    $mo_sql = "SELECT * FROM marketing_order WHERE id = '$lead_id'";
    $mo_res = mysqli_query($conn, $mo_sql);

    if ($mo_res && mysqli_num_rows($mo_res) > 0) {

        // ✅ Found in CRM / marketing order
        $order = mysqli_fetch_assoc($mo_res);
        $lead_source = 'marketing';

    } else {

        // ❌ Not found anywhere (safe fallback)
        $order = [];
        $lead_source = 'unknown';
    }
}

     
   $random_number = rand(1000000000, 9999999999); 
?>
   <body>
      <div>
         <div class="container" style="height:297mm;width: 200mm;">
            <div class="border-box">
               <div class="header" style="display:flex;justify-content:space-between;align-items:start;margin-top:0px;">
                  <div style="width: 33.33%;height:;">
                     <!-- Left or center content (if any) -->
                     <div style=""></div>
                     <!-- QR and barcode container aligned to the right -->
                     <div style="
                        display: flex;
                        align-items: stretch; /* stretch all child elements to equal height */
                        gap: 8px;
                        justify-content: flex-start;margin-bottom:2px;
                        ">
                        <img src="qrcode.png" alt="QR" style="width: 40%; object-fit: contain;">
                        <div style="display: flex; flex-direction: column; gap: 8px; width: 40%;">
                           <div style="flex: 1;border:1px solid #0000002e">
                              <p style="background-color:black;color:white;margin:0;">QUOTATION #</p>
                              <p style="margin:0;background-color:color:black;font-size:13px;height:80%;display:flex;align-items:center;justify-content:center;"><?php echo $proposal['proposal_no'];?></p>
                              <!-- <p style="margin:0;background-color:#f2f2f2;color:black;">00-000</p> -->
                           </div>
                           <div style="flex: 1;border:1px solid #0000002e">
                              <p style="background-color:black;color:white;margin:0;">ORDER DATE</p>
                              <p style="margin:0;background-color:color:black;font-size:15px;height:80%;display:flex;align-items:center;justify-content:center;"><?php echo date("d-m-Y", strtotime($proposal['created_at'])); ?></p>
                           </div>
                        </div>
                     </div>
                  </div>
                  <div style="    width: 33.33%;
                     text-align: center;
                     display: flex
                     ;
                     align-items: center;
                     justify-content: center;flex-direction: column;">
                     <div 
                        >
                        <h1 class="bebas-neue-regular " style="font-size:40px;">PROPOSAL FORM</h1>
                        <img src="title-bg.png" alt="" style="width: 35%;">
                     </div>
                     <img src="gem-logo.png" style="width: 35%; height: auto;">
                     
                  </div>
                  <div style="text-align:left;width: 33.33%;display:flex;flex-direction:column;align-items:flex-end;margin-top:-10px;">
                     <img src="pro-logo.png" style="width: 75%; height: auto;">
                     <img src="barcode.png" alt="Barcode" style="width: 75%;">
                     <p style="text-align: center;letter-spacing: 12px;"><?= $random_number; ?></p>
                     
                  </div>
               </div>
               <div style="width: 100%;margin-top:5px;">
                  <div style="display:flex;gap:10px;">
                     <div class="card" style="width: 33.33%;">
                        <div class="card-header">CUSTOMER DETAILS</div>
                        <ul class="list-group">
                           <li class="list-group-item"><?php echo $order['company_name'];?>
                              <br><?php echo $order['location'];?>
                              <br><?php echo $order['mobile'];?>
                           </li>
                        </ul>
                     </div>
                     <div class="card" style="width: 33.33%;">
                        <div class="card-header">PROPOSAL DETAILS</div>
                        <ul class="list-group">
                           <div>
                              <ul class="list-group">
                                 <li class="list-group-item"><b>BDO /BDM: <?php echo strtoupper($order['bdm']); ?></b></li>
                                 <?php
                                    // Count how many proposals exist for this lead
                                    // $lead_id = $proposal['lead_id'];
                                    $rev_sql = "SELECT COUNT(*) AS revision_count FROM proposals WHERE lead_id = '$lead_id'";
                                    $rev_res = mysqli_query($conn, $rev_sql);
                                    $rev_data = mysqli_fetch_assoc($rev_res);
                                    
                                    // Current revision number
                                    $revision_number = $rev_data['revision_count'];
                                    
                                    // Display: if more than 1, show "Revised"
                                    $revision_text = $revision_number > 1 ? " (Revised #$revision_number)" : "";
                                    ?>
                                 <li class="list-group-item"><b>Quotation Revision#: <?php echo $proposal['proposal_no'] . $revision_text; ?></b></li>
                                 <li class="list-group-item"><b>Quotation By: <?php echo strtoupper($proposal['qtnby']);?></b></li>
                              </ul>
                           </div>
                        </ul>
                     </div>
                     <div class="card" style="width: 33.33%;">
                        <div class="card-header">PROJECT DETAILS</div>
                        <ul class="list-group">
                           <div>
                              <ul class="list-group">
                                 <li class="list-group-item">
    <b>Category:</b> <?php echo strtoupper($order['category_name'] ?? 'N/A'); ?>
</li>

                                 <li class="list-group-item"><b>Customer Type:</b> <?php echo strtoupper($order['cus_type']);?></li>
                                 <li class="list-group-item"><b>Sources:</b><?php echo strtoupper($order['source']);?></li>
                              </ul>
                           </div>
                        </ul>
                     </div>
                  </div>
               </div>
           
               <div></div>
               <style>
                  .signature-box {
                  /*                   border: 1px solid #000; */
                  display: inline-block;
                  padding: 8px 12px;
                  font-family: Arial, sans-serif;
                  position: relative;
                  background-color: #fff;
                  width: 80%;
                  }
                  .signature-title {
                  font-size: 12px;
                  font-weight: bold;
                  color: #222;
                  }
                  .signature-text {
                  font-size: 10px;
                  color: #333;
                  margin-top: 4px;
                  line-height: 1.4;
                  z-index: 2;
                  position: relative;
                  }
                  .checkmark {
                  position: absolute;
                  right: 117px;
                  top: 0px;
                  font-size: 48px;
                  color: green;
                  font-weight: bold;
                  transform: rotate(12deg);
                  }
                  .tooltip {
                  position: absolute;
                  right: 15px;
                  top: 40px;
                  background: #fff8dc;
                  border: 1px solid #aaa;
                  padding: 4px 8px;
                  font-size: 12px;
                  display: none;
                  }
                  .signature-box:hover .tooltip {
                  display: block;
                  }
               </style>
               <div class="" style="margin-top:5px;">
                  <!-- <h4 style="margin-top:20px;margin-bottom:0;">Hosting/Yearly Charges</h4> -->
                  <small style="font-size:10px;font-weight:bold;">This Proposal form is issued in connection with the proposed project, and confirms our intent to proceed with the implementation as per the agreed terms and conditions.</small>
                  <div style="display:flex;gap:60px;margin-top:7px;">
                     <div style="width: 100%;">
                        <div style="display:flex">
                           <div style="width:30%;padding:0 10px 10px 0px;">
                              <table style="width: 100%;">
                                 <thead style="background-color:black;color:white;">
                                    <tr>
                                       <th style="font-size:10px;padding:0.50rem 1rem;text-transform: uppercase;">Terms &amp; Conditions</th>
                                    </tr>
                                 </thead>
                                 <tbody>
                                    <tr>
                                       <td>
                                          <div style="display: flex; align-items: flex-start; margin-bottom: 10px;text-align:justify;font-size:13px;margin-top:10px;">
                                             
                                             <span><?php 
                                               $terms_sql = "SELECT * FROM tb_terms_master WHERE status = 'Active'";
                                                $terms_res = mysqli_query($conn, $terms_sql);
                                                $terms_data = mysqli_fetch_assoc($terms_res);
                                                echo $terms_data['remarks'];
                                             ?></span>
                                          </div>
                                     
                                          <div style="display: flex;gap: 10px;">
                                          </div>
                                       </td>
                                    </tr>
                                 </tbody>
                              </table>
                              <div class="card" style="width: 100%;margin-top:10px;height:120px;">
                                 <div class="card-header" style="background-color:black;color:white;text-align:center;font-size:10px;">Approved By</div>
                                 <div style="padding:2px;">
                                    <div class="signature-box">
                                       <div class="signature-title">Signature valid</div>
                                       
                                        <script>
                                       
                                                                                    function getLocation() {
                                            if (!navigator.geolocation) {
                                                console.log("Geolocation not supported");
                                                return;
                                            }
                                        
                                            navigator.geolocation.getCurrentPosition(
                                                function (position) {
                                                    let lat = position.coords.latitude;
                                                    let lon = position.coords.longitude;
                                        
                                                    console.log("Sending GPS:", lat, lon);
                                        
                                                    fetch("save_location.php?lat=" + lat + "&lon=" + lon)
                                                        .then(response => response.text())
                                                        .then(data => {
                                                            console.log("Server response:", data);
                                                            if (data.trim() !== "") {
                                                                location.reload();
                                                            }
                                                        });
                                                },
                                        
                                                function (error) {
                                                    console.log("GPS Error:", error.message);
                                                },
                                        
                                                { enableHighAccuracy: true }
                                            );
                                        }
                                        
                                        // Run once
                                        window.onload = getLocation;
                                        </script>

                                       <?php
                                    // Company Name
                                    $company = $branch_row['manager_name'] ?? '';
                                    $branch_name = $branch_row['branch_name'] ?? '';
                                    
                                    // Dynamic Date/Time
                                    $datetime = date("Y.m.d H:i:s");
                                    
                                    // Dynamic Timezone Offset (e.g., +05:30 or -05:00)
                                    $timezone_offset = date("P");
                                    
                                   $city = $_SESSION['gps_city'] ?? "Location unavailable";
                                    ?>


                                    
                                    <div class="signature-text">
                                        Digitally signed by <b><?php echo $company; ?></b><br>
                                        Date: <?php echo $datetime . " " . $timezone_offset; ?><br>
                                        Location: <?php echo $branch_name; ?>
                                    </div>

                                      <?php
                                       if($approvestatus == 'Approved'){
                                           ?><div class="checkmark">✔</div>
                                           <?php
                                       }
                                       ?>
                                       <div class="tooltip">Valid signature</div>
                                    </div>
                                    <span style="display:flex;justify-content:space-between;align-items: baseline;margin-top: -15px;"><span><span>Authorised signatory:</span></span><span style="display: flex;align-items: end;justify-content: end;"><img src="seal.png" alt="" class="img-fluid" style="        position: relative;
                                       left: 20px;
                                       width: 40%;
                                       top: -50px;"> <span>(Seal)</span></span></span>
                                 </div>
                              </div>
                           </div>
                           <div style="width:70%;">
                              <div class="card" style="width: 100%; height:685px; display: flex; flex-direction:column;justify-content:space-between;">
    <div class="card-header" style="background-color:black; color:white; text-align:center; text-transform: uppercase;">
        Proposal Summary
    </div>

    <?php
// === CLEAN & PAGINATE PROPOSAL CONTENT ===

// Raw proposal content
$raw_proposal = $proposal['details'] ?? '';
$total        = $proposal['total'];
$discount     = $proposal['discount'];

// 1. Remove Word <br> and </p> tags
$raw_proposal = str_ireplace(
    ['<br>', '<br/>', '<br />', '<BR>', '<BR/>', '<BR />'],
    "\n",
    $raw_proposal
);
$raw_proposal = preg_replace('/<\/p\s*>/i', "\n", $raw_proposal);

// 2. Strip unwanted tags but keep basic formatting
$raw_proposal = strip_tags($raw_proposal, '<strong><b><i><u><ul><ol><li>');

// 3. Decode HTML entities
$raw_proposal = html_entity_decode($raw_proposal);

// 4. Normalize newlines
$raw_proposal = str_replace(["\r\n", "\r"], "\n", $raw_proposal);
$raw_proposal = preg_replace("/\n{2,}/", "\n", $raw_proposal);
$raw_proposal = trim($raw_proposal);

// 5. Split lines
$lines = preg_split('/\n/', $raw_proposal);

// -----------------------------
// Function to calculate visible line height
// -----------------------------
function count_visible_lines($text) {
    $plain = strip_tags($text);
    $plain = preg_replace('/\s+/', ' ', $plain);
    $chars_per_line = 90; // Adjust based on design
    $length = strlen($plain);
    return $length > 0 ? ceil($length / $chars_per_line) : 1;
}

// -----------------------------
// Pagination
// -----------------------------
$max_visible_lines_per_page = 28;
$current_height = 0;
$final_lines = [];

foreach ($lines as $line) {
    $line_height = count_visible_lines($line);
    if (($current_height + $line_height) > $max_visible_lines_per_page) {
        break; // Stop first page
    }
    $final_lines[] = $line;
    $current_height += $line_height;
}

// Build HTML for first page
$formatted_proposal = '';
$list_items = [];
foreach ($final_lines as $line) {
    $line = trim($line);
    // Numbering
    $line = preg_replace('/^(\d+)\.\s*(.+)$/', '<strong>$1. $2</strong>', $line);
    // Bullets
    $line = preg_replace('/^[\*\#]\s*(.+)$/', '<li>$1</li>', $line);

    if (strpos($line, '<li>') !== false) {
        $list_items[] = $line;
    } else {
        if (!empty($list_items)) {
            $formatted_proposal .= '<ul style="margin:5px 0 15px 25px; padding:0;">' . implode('', $list_items) . '</ul>';
            $list_items = [];
        }
        $formatted_proposal .= nl2br($line) . "<br>";
    }
}
if (!empty($list_items)) {
    $formatted_proposal .= '<ul style="margin:5px 0 15px 25px; padding:0;">' . implode('', $list_items) . '</ul>';
}

// Display first page
echo '<div class="proposal-content" style="padding:10px; font-size:13px; text-align:justify; page-break-inside: avoid;">';
echo $formatted_proposal;

// -----------------------------
// Show "continued" message if more lines exist
// -----------------------------

echo '</div>';

// -----------------------------
// Prepare remaining lines for next pages
// -----------------------------
$remaining_lines = array_slice($lines, count($final_lines));

// You can then loop over $remaining_lines to generate continuation pages
// using the same <ul>/<li> logic and add "continued" or "end of page" text
?>


    <!-- Proposal Footer with Amounts -->
    <div style="padding:10px; margin-top:10px;">
        <div class="card-header" style="background-color:white; color:black; text-align:left; text-transform: capitalize; font-size: 12px; padding-left: 15px; border-bottom: 1px solid black;display:flex;justify-content:flex-end;">
           <span> <?php if (count($lines) > count($final_lines)) {
    echo 'Continued…';
} ?></span>
        </div>
        <div class="card-header" style="background-color:white; color:black; text-align:left; text-transform: capitalize; font-size: 12px; padding-left: 15px; border-bottom: 1px solid black;display:flex;justify-content:space-between;">
            <span>All Amt in <?php echo $currency;?> | No additional service or items | E&O</span>
        </div>
        <ul class="list-group" style="display: flex; width: 100%; justify-content: space-between; margin-top:5px;">
            <li class="list-group-item" style="border:1px solid black; width:75%; font-size:13px!important; display:flex; justify-content: space-between;">
                <b>Total: <?php echo $total;?>/-</b><span>(Discount: <?php echo $discount;?>/-)</span>
            </li>
            <li class="list-group-item" style="border:1px solid black; width:25%; font-size:13px!important;">
                <b>Net: <?php echo $total - $discount;?>/-</b>
            </li>
        </ul>
        <p style="padding-left:15px; font-size:13px!important; display:flex; justify-content: space-between; margin-top:5px;">
            <b>
                <?php
                $amount = $total - $discount;
                echo numberToWords($amount) . " Only";
                ?>
            </b>
            <span style="padding-right:10px;"><b>Annexure - A(0)</b></span>
        </p>
    </div>
</div>

                              <div style="display: flex;gap: 10px;">
                                 
                              </div>
                              <div></div>
                           </div>
                        </div>
                     </div>
                  </div>
                  <hr style="margin:0;">
                  <p style="text-align: center;margin-bottom: 0!important;margin-top: 0!important;padding-bottom: 5px;padding-top: 5px;"><?php  echo $branch_row['address'];?></p>
               </div>
            </div>
         </div>
      </div>
   </body>
</html>
<?php
function numberToWords($number) {
    $hyphen      = '-';
    $conjunction = ' and ';
    $separator   = ', ';
    $negative    = 'negative ';
    $decimal     = ' point ';
    $dictionary  = array(
        0 => 'Zero',
        1 => 'One',
        2 => 'Two',
        3 => 'Three',
        4 => 'Four',
        5 => 'Five',
        6 => 'Six',
        7 => 'Seven',
        8 => 'Eight',
        9 => 'Nine',
        10 => 'Ten',
        11 => 'Eleven',
        12 => 'Twelve',
        13 => 'Thirteen',
        14 => 'Fourteen',
        15 => 'Fifteen',
        16 => 'Sixteen',
        17 => 'Seventeen',
        18 => 'Eighteen',
        19 => 'Nineteen',
        20 => 'Twenty',
        30 => 'Thirty',
        40 => 'Forty',
        50 => 'Fifty',
        60 => 'Sixty',
        70 => 'Seventy',
        80 => 'Eighty',
        90 => 'Ninety',
        100 => 'Hundred',
        1000 => 'Thousand',
        1000000 => 'Million',
        1000000000 => 'Billion',
        1000000000000 => 'Trillion'
    );


    if (!is_numeric($number)) return false;
    if (($number >= 0 && (int)$number < 0) || (int)$number < 0 - PHP_INT_MAX) return false;

    if ($number < 0) {
        return $negative . numberToWords(abs($number));
    }

    $string = $fraction = null;

    if (strpos($number, '.') !== false) {
        list($number, $fraction) = explode('.', $number);
    }

    switch (true) {
        case $number < 21:
            $string = $dictionary[$number];
            break;
        case $number < 100:
            $tens   = ((int)($number / 10)) * 10;
            $units  = $number % 10;
            $string = $dictionary[$tens];
            if ($units) $string .= $hyphen . $dictionary[$units];
            break;
        case $number < 1000:
            $hundreds  = (int)($number / 100);
            $remainder = $number % 100;
            $string = $dictionary[$hundreds] . ' ' . $dictionary[100];
            if ($remainder) $string .= $conjunction . numberToWords($remainder);
            break;
        default:
            $baseUnit = pow(1000, floor(log($number, 1000)));
            $numBaseUnits = (int)($number / $baseUnit);
            $remainder = $number % $baseUnit;
            $string = numberToWords($numBaseUnits) . ' ' . $dictionary[$baseUnit];
            if ($remainder) {
                $string .= $remainder < 100 ? $conjunction : $separator;
                $string .= numberToWords($remainder);
            }
            break;
    }

    if (null !== $fraction && is_numeric($fraction)) {
        $string .= $decimal;
        $words = array();
        foreach (str_split((string)$fraction) as $digit) {
            $words[] = $dictionary[$digit];
        }
        $string .= implode(' ', $words);
    }

    return ucfirst($string);
}
?>

<!-- ✅ Add this CSS block -->
<style>
@media print {
  .page {
   
    page-break-inside: avoid;
   
    break-inside: avoid;
  }
  
}
</style>

<?php
// === Continuation pages ===
$max_visible_lines_per_page = 55; // lines per continuation page
$remaining_lines = array_slice($lines, count($final_lines));
$page_number = 1;

// Calculate total pages
$temp_remaining = $remaining_lines;
$total_remaining_pages = 0;
while (count($temp_remaining) > 0) {
    $temp_height = 0;
    $temp_lines_for_page = [];
    foreach ($temp_remaining as $line) {
        $line_height = count_visible_lines($line);
        if (($temp_height + $line_height) > $max_visible_lines_per_page) {
            break;
        }
        $temp_lines_for_page[] = $line;
        $temp_height += $line_height;
    }
    if (count($temp_lines_for_page) == 0) {
        $temp_lines_for_page[] = array_shift($temp_remaining);
    } else {
        $temp_remaining = array_slice($temp_remaining, count($temp_lines_for_page));
    }
    $total_remaining_pages++;
}

// Render continuation pages
$remaining_lines = array_slice($lines, count($final_lines)); // reset
while (count($remaining_lines) > 0 && $page_number <= $total_remaining_pages) {
    $current_height = 0;
    $current_page_lines = [];
    foreach ($remaining_lines as $line) {
        $line_height = count_visible_lines($line);
        if (($current_height + $line_height) > $max_visible_lines_per_page) {
            break;
        }
        $current_page_lines[] = $line;
        $current_height += $line_height;
    }

    // Ensure at least one line per page
    if (count($current_page_lines) === 0 && count($remaining_lines) > 0) {
        $current_page_lines[] = array_shift($remaining_lines);
    } else {
        $remaining_lines = array_slice($remaining_lines, count($current_page_lines));
    }

    // Convert lines to HTML while preserving bullets and numbering
    $proposal_current = '';
    $list_items = [];
    foreach ($current_page_lines as $line) {
        $line = html_entity_decode(trim($line)); // decode HTML entities

        // Numbered lines
        $line = preg_replace('/^(\d+)\.\s*(.+)$/', '<strong>$1. $2</strong>', $line);
        // Bullets (* or #)
        $line = preg_replace('/^[\*\#]\s*(.+)$/', '<li>$1</li>', $line);

        if (strpos($line, '<li>') !== false) {
            $list_items[] = $line;
        } else {
            if (!empty($list_items)) {
                $proposal_current .= '<ul style="margin:5px 0 15px 25px; padding:0;">' . implode('', $list_items) . '</ul>';
                $list_items = [];
            }
            $proposal_current .= nl2br($line) . "<br>";
        }
    }
    if (!empty($list_items)) {
        $proposal_current .= '<ul style="margin:5px 0 15px 25px; padding:0;">' . implode('', $list_items) . '</ul>';
    }

    // Determine continued text
    $continued_text = count($remaining_lines) > 0 ? '--- Continued on next page ---' : '--- End of page ---';

    // Output continuation page (keeps your design)
    echo '
    <div class="page">
        <div class="container" style="height:285mm;width:200mm;margin-top:20px;">
            <div class="border-box" style="border:2px solid #000; border-radius:10px; margin-right:8px; padding-left:25px; box-sizing:border-box; display:flex; flex-direction:column; height:100%; padding-right:25px; padding-top:25px; padding-bottom:8px;">
                <div class="header" style="display:flex;justify-content:space-between;align-items:start;margin-top:0px;">
                    <div style="width:33.33%;">
                        <div style=""></div>
                        <div style="display:flex;align-items:stretch;gap:8px;justify-content:flex-start;margin-bottom:2px;">
                            <img src="qrcode.png" alt="QR" style="width:40%;object-fit:contain;">
                            <div style="display:flex;flex-direction:column;gap:8px;width:40%;">
                                <div style="flex:1;border:1px solid #0000002e">
                                    <p style="background-color:black;color:white;margin:0;">QUOTATION #</p>
                                    <p style="margin:0;font-size:13px;height:80%;display:flex;align-items:center;justify-content:center;">' . htmlspecialchars($proposal_no) . '</p>
                                </div>
                                <div style="flex:1;border:1px solid #0000002e">
                                    <p style="background-color:black;color:white;margin:0;">ORDER DATE</p>
                                    <p style="margin:0;font-size:15px;height:80%;display:flex;align-items:center;justify-content:center;">' . date("d-m-Y", strtotime($order_date)) . '</p>
                                </div>
                            </div>
                        </div>
                        <p style="margin-top:0!important;text-align:left;margin-bottom:0!important;"><b>ANNEXURE - A (' . $page_number . '/' . $total_remaining_pages . ')</b></p>
                    </div>
                    <div style="width:33.33%;text-align:center;display:flex;align-items:center;justify-content:center;flex-direction:column;">
                        <h1 class="bebas-neue-regular" style="font-size:40px;">PROPOSAL FORM</h1>
                        <img src="title-bg.png" alt="" style="width:35%;">
                        <img src="gem-logo.png" style="width:35%;height:auto;">
                    </div>
                    <div style="text-align:left;width:33.33%;display:flex;flex-direction:column;align-items:flex-end;margin-top:-10px;">
                        <img src="pro-logo.png" style="width:75%;height:auto;">
                        <img src="barcode.png" alt="Barcode" style="width:75%;"> 
                        <p style="text-align:center;letter-spacing:12px;margin-bottom:0!important;">' . $random_number . '</p>     
                        <p style="text-align:center;margin-top:5px;">' . htmlspecialchars($proposal_no) . ' | ' . date("m/d/y", strtotime($order_date)) . ' | ' . strtoupper(htmlspecialchars($qtnby)) . '</p>     
                    </div>
                </div>
                <div style="width:100%;margin-top:8px;height:100%;">
                    <div class="card" style="width:100%;height:880px;display:flex;justify-content:space-between;flex-direction:column;">
                        <div class="card-header" style="background-color:black;color:white;text-align:center;text-transform:uppercase;">Proposal in Details</div>
                        <div style="padding:10px;text-align:justify;vertical-align:top;font-size:13px;height:100%;">
                            ' . $proposal_current . '
                            
                        </div>
                        
        <div style="display:flex;justify-content:flex-end;padding-left:10px;padding-right:10px;"><p><b>' . $continued_text . '</b></p></div>
                    </div>
                </div>
                
                <hr style="margin:0;">
                <p style="text-align:center;margin-bottom:0!important;margin-top:0!important;padding-bottom:5px;padding-top:5px;">
                    ' . htmlspecialchars($branch_row['address']) . '
                </p>
            </div>
        </div>
    </div>';

    if ($page_number < $total_remaining_pages && count($remaining_lines) > 0) {
        echo '<div style="page-break-after: always;"></div>';
    }

    $page_number++;
}
?>

<script>
/* =========================
   MAIN HANDLER
========================= */
function handleApproval() {

    let tokenField = document.getElementById('tokenid');
    let token = tokenField ? tokenField.value : '';

    if (token !== '') {
        // Token exists → direct approve
        directApproveProposal();
    } else {
        // No token → popup
        openApproveModal();
    }
}

/* =========================
   POPUP CONTROLS
========================= */
function openApproveModal() {
    document.getElementById('approveModal').style.display = 'flex';
}

function closeApproveModal() {
    document.getElementById('approveModal').style.display = 'none';
}

/* =========================
   TOKEN CASE → DIRECT APPROVE
========================= */
function directApproveProposal() {

    Swal.fire({
        title: 'Approve Proposal?',
        text: 'Are you sure you want to approve this proposal?',
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Yes, Approve',
        cancelButtonText: 'Cancel'
    }).then((result) => {

        if (!result.isConfirmed) return;

        fetch("approve_proposal.php", {
            method: "POST",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            body:
                "proposal_id=<?= $orderid ?>" +
                "&token=<?= $token ?>"
        })
        .then(res => res.text())
        .then(data => {
            Swal.fire({
                icon: 'success',
                title: 'Approved',
                text: data
            }).then(() => {
                location.reload();
            });
        })
        .catch(err => {
            Swal.fire({
                icon: 'error',
                title: 'Approval Failed',
                text: 'Something went wrong'
            });
            console.error(err);
        });

    });
}

/* =========================
   NO-TOKEN CASE → POPUP APPROVE
========================= */
function confirmApprove() {

    let select = document.getElementById('approveUser');
    let userId = select.value;

    if (!userId) {
        Swal.fire({
            icon: 'warning',
            title: 'Select User',
            text: 'Please select a user'
        });
        return;
    }

    let email = select.options[select.selectedIndex].dataset.email;

    // ✅ HIDE MODAL BEFORE SWEET ALERT
    closeApproveModal();

    Swal.fire({
        title: 'Approve Proposal?',
        html: 'Approve proposal and send email to <b>' + email + '</b>?',
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Yes, Approve',
        cancelButtonText: 'Cancel'
    }).then((result) => {

        // ❗ If cancelled → reopen modal
        if (!result.isConfirmed) {
            openApproveModal();
            return;
        }

        fetch("approve_proposal.php", {
            method: "POST",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            body:
                "proposal_id=<?= $orderid ?>" +
                "&user_id=" + userId
        })
        .then(res => res.text())
        .then(data => {
            Swal.fire({
                icon: 'success',
                title: 'Approved',
                text: data
            }).then(() => location.reload());
        })
        .catch(err => {
            Swal.fire({
                icon: 'error',
                title: 'Approval Failed',
                text: 'Something went wrong'
            });
            console.error(err);
        });

    });
}


</script>

      <!-- Approval Modal -->
      <div id="approveModal" style="
    display:none;
    position:fixed;
    top:0; left:0;
    width:100%; height:100%;
    background:rgba(0,0,0,0.65);
    z-index:9999;
    align-items:center;
    justify-content:center;
    font-family: Arial, sans-serif;
">
    <div style="
        background:#fff;
        padding:22px;
        width:360px;
        border-radius:10px;
        box-shadow:0 8px 25px rgba(0,0,0,0.3);
        animation: fadeInScale 0.25s ease;
    ">
        <h3 style="
            margin:0 0 15px 0;
            font-size:18px;
            color:#333;
            text-align:center;
        ">
            Approve & Send Email
        </h3>
<input type="hidden" id="tokenid" value="<?php echo $token ?? ''; ?>">
        <label style="font-size:14px;color:#555;">Select User</label>
        <input type="hidden" value="<?php echo $token; ?>" name="tokeid" id="tokenid">
        <select id="approveUser" style="
            width:100%;
            padding:9px;
            margin-top:6px;
            border-radius:5px;
            border:1px solid #ccc;
            font-size:14px;
        ">
            <option value="">-- Select User --</option>
            <?php
            $user_sql = "SELECT id, name, email FROM users WHERE status='1'";
            $user_res = mysqli_query($conn, $user_sql);
            while($u = mysqli_fetch_assoc($user_res)) {
                echo "<option value='{$u['id']}' data-email='{$u['email']}'>
                        {$u['name']} ({$u['email']})
                      </option>";
            }
            ?>
        </select>

        <div style="
            margin-top:22px;
            display:flex;
            justify-content:flex-end;
            gap:10px;
        ">
            <button onclick="closeApproveModal()" style="
                padding:7px 14px;
                border-radius:5px;
                border:1px solid #ccc;
                background:#f5f5f5;
                cursor:pointer;
            ">
                Cancel
            </button>

            <button onclick="confirmApprove()" style="
                padding:7px 16px;
                border-radius:5px;
                background:#28a745;
                color:#fff;
                border:none;
                cursor:pointer;
            ">
                Approve & Send
            </button>
        </div>
    </div>
</div>

<style>
@keyframes fadeInScale {
    from {
        opacity: 0;
        transform: scale(0.9);
    }
    to {
        opacity: 1;
        transform: scale(1);
    }
}
</style>

