<?php
// error_reporting(E_ALL);
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
include 'branch_connection.php';
session_start();
$userid = isset($_SESSION['userid']) ? $_SESSION['userid'] : 'Not set';
$username = isset($_SESSION['username']) ? $_SESSION['username'] : '';
$is_admin = ($username === 'admin'); // Check if user is admin
$message = "";
$edit_mode = false;
$edit_id = 0;

// Delete record
if (isset($_GET['delete'])) {
    $delete_id = intval($_GET['delete']);
    
    // Delete from teledata
    $stmt = $conn->prepare("DELETE FROM tb_positiveleads WHERE id = ?");
    $stmt->bind_param("i", $delete_id);
    if ($stmt->execute()) {
        $message = "Record deleted successfully.";

        // Delete from tb_leads
        $stmt2 = $conn->prepare("DELETE FROM tb_leads WHERE tel_id = ?");
        $stmt2->bind_param("i", $delete_id);
        $stmt2->execute();
        $stmt2->close();
    } else {
        $message = "Error deleting record: " . $stmt->error;
    }
    $stmt->close();
}

// Handle form submission for create or update
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
    // Collect and sanitize inputs
    $company_name = strtoupper(trim($_POST['company_name']));
    $mobile = trim($_POST['mobile']);
    $location = strtoupper(trim($_POST['location']));
    $segment = intval($_POST['segment']);
    $status = trim($_POST['status']);
    $category = intval($_POST['category']);
    $remarks = trim($_POST['remarks']);
    $staff = $userid; // Staff field
    $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
    
    // Check if mobile already exists (excluding current record)
    $stmt = $conn->prepare("SELECT id FROM tb_positiveleads WHERE mobile = ? AND id != ?");
    $stmt->bind_param("si", $mobile, $id);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows > 0) {
        $message = "Error: Mobile number already exists.";
        $stmt->close();
    } else { 
        $stmt->close();
if ($id > 0) {
    // Update existing teledata record
    $stmt = $conn->prepare("
   UPDATE tb_positiveleads 
SET company_name=?, mobile=?, location=?, segment=?, category=?, staff=?, status=?, remarks=?, updated_at = NOW()
WHERE id = ?

");
$stmt->bind_param(
    "sssissssi",
    $company_name,
    $mobile,
    $location,
    $segment,
    $category,
    $staff,
    $status,
    $remarks,
    $id
);



    if ($stmt->execute()) {
        $message = "Record updated successfully.";

        // Decide where to insert based on status
        if ($status == 'Not Interested') {
            $insertTable = "tb_leads";
        } else if ($status != 'Interested') {
            $insertTable = "marketing_order";
        } else {
            $insertTable = "";
        }

        if ($insertTable != "") {
$insertQuery = "
INSERT INTO $insertTable 
(tel_id, mobile, company_name, segment, category, location, status, staff, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())
";

$stmt2 = $conn->prepare($insertQuery);

if (!$stmt2) {
    die("Prepare failed: " . $conn->error);
}

$stmt2->bind_param(
    "ississss",
    $id,             // tel_id (int)
    $mobile,         // mobile (string)
    $company_name,   // company_name (string)
    $segment,        // segment (int)
    $category,       // category (int)
    $location,       // location (string)
    $status,         // status (string)
    $staff           // staff (string or int)
);


            if ($stmt2->execute()) {
                // Delete from tb_positiveleads after successful insert
                $deleteStmt = $conn->prepare("DELETE FROM tb_positiveleads WHERE id = ?");
                $deleteStmt->bind_param("i", $id);
                $deleteStmt->execute();
                $deleteStmt->close();

                $message .= " Record moved to <strong>$insertTable</strong> and deleted from tb_positiveleads.";
            } else {
                $message = "Error inserting into $insertTable: " . $stmt2->error;
            }
            $stmt2->close();
        }
    } else {
        $message = "Error updating record: " . $stmt->error;
    }
    $stmt->close();
}
 else {
            // Insert new teledata record
            $stmt = $conn->prepare("INSERT INTO tb_positiveleads 
(company_name, mobile, location, segment, category, staff, status, remarks)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
");
            $stmt->bind_param(
    "sssissss",
    $company_name,
    $mobile,
    $location,
    $segment,
    $category,
    $staff,
    $status,
    $remarks
);

            if ($stmt->execute()) {
                $message = "New record created successfully.";
                $tele_id = $stmt->insert_id;
            }
        }
    }
}

// If editing, fetch data to populate form
if (isset($_GET['edit'])) {
    $edit_id = intval($_GET['edit']);
    $stmt = $conn->prepare("SELECT * FROM tb_positiveleads WHERE id = ?");
    $stmt->bind_param("i", $edit_id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows == 1) {
        $edit_mode = true;
        $edit_row = $result->fetch_assoc();
    }
    $stmt->close();
}

// Fetch segments for dropdown
$segments = [];
$sql = "SELECT id, segment_name FROM segments ORDER BY segment_name ASC";
$result = $conn->query($sql);
if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $segments[] = $row;
    }
}
$categories = [];
$catSql = "SELECT id, name FROM categories ORDER BY name ASC";
$catRes = $conn->query($catSql);
if ($catRes && $catRes->num_rows > 0) {
    while ($row = $catRes->fetch_assoc()) {
        $categories[] = $row;
    }
}

// Get filter values
$segment_filter = isset($_GET['segment']) ? intval($_GET['segment']) : 0;

// Pagination setup
$limit = 20; // Number of records per page
$page = isset($_GET['page']) && is_numeric($_GET['page']) && $_GET['page'] > 0 ? intval($_GET['page']) : 1;
$offset = ($page - 1) * $limit;

// Base SQL query
$sql2 = "SELECT t.*, s.segment_name, u.name FROM tb_positiveleads t 
          LEFT JOIN segments s ON t.segment = s.id 
          LEFT JOIN users u ON t.staff = u.id";

// Add WHERE conditions
$where_conditions = [];
$query_params = [];
$where_conditions[] = "1=1"; // Always true for easy parameter binding

// Apply user filter (unless admin)
if (!$is_admin) {
    $where_conditions[] = "t.staff = ?";
    $query_params[] = $userid;
}

// Apply segment filter if selected
if ($segment_filter > 0) {
    $where_conditions[] = "t.segment = ?";
    $query_params[] = $segment_filter;
}

// Build complete WHERE clause
if (!empty($where_conditions)) {
    $sql2 .= " WHERE " . implode(" AND ", $where_conditions);
}

// Order and limit
$sql2 .= " ORDER BY t.id DESC LIMIT ? OFFSET ?";
$query_params = array_merge($query_params, [$limit, $offset]);

// Prepare and execute query
$stmt2 = $conn->prepare($sql2);
if ($stmt2) {
    // Dynamically bind parameters based on query needs
    $param_types = str_repeat("i", count($query_params));
    $stmt2->bind_param($param_types, ...$query_params);
    $stmt2->execute();
    $result2 = $stmt2->get_result();
    $teledata_rows = $result2->fetch_all(MYSQLI_ASSOC);
    $stmt2->close();
} else {
    $message = "Error preparing query: " . $conn->error;
}


// Get total records for pagination
$count_sql = "SELECT COUNT(*) as total FROM tb_positiveleads t";
$where_conditions = [];
if (!$is_admin) {
    $where_conditions[] = "t.staff = ?";
}

// Add segment filter if selected
if ($segment_filter > 0) {
    $where_conditions[] = "t.segment = ?";
}

// Build complete WHERE clause
if (!empty($where_conditions)) {
    $count_sql .= " WHERE " . implode(" AND ", $where_conditions);
}

$total_stmt = $conn->prepare($count_sql);
if ($is_admin && $segment_filter == 0) {
    // No parameters needed for admin without segment filter
} elseif ($is_admin) {
    // Admin with segment filter
    $total_stmt->bind_param("i", $segment_filter);
} else {
    // Staff with or without segment filter
    if ($segment_filter > 0) {
        $total_stmt->bind_param("ii", $userid, $segment_filter);
    } else {
        $total_stmt->bind_param("i", $userid);
    }
}

$total_stmt->execute();
$total_result = $total_stmt->get_result();
$total_row = $total_result->fetch_assoc();
$total_records = $total_row['total'];
$total_pages = ceil($total_records / $limit);
$total_stmt->close();

?>

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Positives Programers International</title>
      <meta charset="utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="author" content="DexignLab">
      <meta name="robots" content="index, follow">
      <meta name="format-detection" content="telephone=no">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="shortcut icon" type="image/png" href="assets/images/favicon.png">
      <link href="assets/vendor/bootstrap-select/dist/css/bootstrap-select.min.css" rel="stylesheet">
      <link href="assets/vendor/bootstrap-datepicker-master/css/bootstrap-datepicker.min.css" rel="stylesheet">
      <link href="assets/vendor/owl-carousel/owl.carousel.css" rel="stylesheet">
      <link href="assets/css/jquery.localizationTool.css" rel="stylesheet">
      <link class="main-css" href="assets/css/style.css" rel="stylesheet">
   </head>
   <style>
       
   </style>
   <body>
      <div id="preloader">
         <div class="lds-ripple"><div></div><div></div></div>
      </div>
      <div id="main-wrapper">
         <div class="nav-header">
            <a href="index.html" class="brand-logo"><img src="assets/images/logo-02.svg" alt=""></a>
            <div class="nav-contro l">
               <div class="hamburger"><span class="line"></span><span class="line"></span><span class="line"></span></div>
            </div>
         </div>
         <div class="header">
            <div class="header-content">
               <nav class="navbar navbar-expand">
                  <div class="collapse navbar-collapse justify-content-between">
                     <div class="header-left">
                        <div class="dashboard_bar">Positives</div>
                     </div>
                     <ul class="navbar-nav header-right">
                        <li class="nav-item dropdown notification_dropdown">
                           <a class="nav-link bell dlab-theme-mode p-0" href="javascript:void(0);">
                              <i id="icon-light" class="fas fa-sun"></i>
                              <i id="icon-dark" class="fas fa-moon"></i>
                           </a>
                        </li>
                        <?php
                            $title = "Php Header Footer";
                            include "logout.php";
                        ?>
                     </ul>
                  </div>
               </nav>
            </div>
         </div> 
         <?php
            $title = "Php Header Footer";
            include "header.php";
         ?>
         <div class="content-body">
            <div class="container-fluid">
               <div class="row">
                  <div class="col-xl-4">
                     <div class="card">
                        <div class="card-body" style="padding: 18px;">
                           <div class="basic-form">
                              <?php if (!empty($message)): ?>
                                  <div class="alert alert-info"><?= htmlspecialchars($message) ?></div>
                              <?php endif; ?>
                              <form method="POST" action="">

                                 <input type="hidden" name="id" value="<?= $edit_mode ? htmlspecialchars($edit_row['id']) : '' ?>">
                                 <div class="row">
                                    <div class="mb-2 col-md-12">
                                       <input type="text" name="company_name" class="form-control" placeholder="Company" required value="<?= $edit_mode ? htmlspecialchars($edit_row['company_name']) : '' ?>">
                                    </div>
                                    <div class="mb-2 col-md-12">
                                       <input type="number" name="mobile" class="form-control" placeholder="Mobile No." required value="<?= $edit_mode ? htmlspecialchars($edit_row['mobile']) : '' ?>">
                                    </div>
                                    <div class="mb-2 col-md-12">
                                       <input type="text" name="location" class="form-control" placeholder="Location" required value="<?= $edit_mode ? htmlspecialchars($edit_row['location']) : '' ?>">
                                    </div>
                                    <div class="mb-2 col-md-12">
                                       <select id="inputState" name="segment" class="default-select form-control wide" required>
                                          <option value="" disabled <?= $edit_mode ? '' : 'selected' ?>>Segment</option>
                                          <?php foreach ($segments as $seg): ?>
                                             <option value="<?= htmlspecialchars($seg['id']) ?>" <?= $edit_mode && $edit_row['segment'] == $seg['id'] ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($seg['segment_name']) ?>
                                             </option>
                                          <?php endforeach; ?>
                                       </select>
                                    </div>
                                    <div class="mb-2 col-md-12">
                                       <select id="inputStatus" class="default-select form-control wide" name="status" required>
                                          <option value="" disabled <?= $edit_mode ? '' : 'selected' ?>>Select Status</option>
                                          <?php
                                          $statuses = ['Interested','Not Interested', 'Future', 'Quotation Submitted', 'Order Received'];
                                          $current_status = $edit_mode ? (isset($edit_row['status']) ? $edit_row['status'] : '') : '';
                                          foreach ($statuses as $s) {
                                             $selected = ($current_status == $s) ? 'selected' : '';
                                             echo "<option value=\"$s\" $selected>$s</option>";
                                          }
                                          ?>
                                       </select>
                                    </div>
                                    <div class="mb-2 col-md-12">
   <select name="category" class="default-select form-control wide" required>
      <option value="" disabled <?= $edit_mode ? '' : 'selected' ?>>Select Category</option>

      <?php foreach ($categories as $cat): ?>
         <option value="<?= $cat['id'] ?>"
            <?= $edit_mode && isset($edit_row['category']) && $edit_row['category'] == $cat['id'] ? 'selected' : '' ?>>
            <?= htmlspecialchars($cat['name']) ?>
         </option>
      <?php endforeach; ?>
   </select>
</div>

                                    <div class="mb-2 col-md-12">
                                       <textarea name="remarks" class="form-control" placeholder="Remarks"><?= $edit_mode ? htmlspecialchars($edit_row['remarks']) : '' ?></textarea>
                                    </div>
                                 </div>
                                 <button type="submit" name="submit" class="btn btn-primary w-100"><?= $edit_mode ? 'Update' : 'Submit' ?></button>
                              </form>
                           </div>
                        </div>
                     </div>
                  </div>

                  <div class="col-xl-8">
                     <div class="row w-100 mb-2 float-right">
                        <div class="col-md-12">
                           <div class="row g-0" style="gap: 5px; display: flex; justify-content: space-between; width: 100%;">
                            <div class="col-md-12 d-flex align-items-center" style="gap:10px;">
                                <!-- Segment Filter -->
                                <form method="GET" action="" class="form-inline mb-0 d-flex align-items-center" style="gap:5px;">
                                    <select name="segment" class="form-control form-control-sm" onchange="this.form.submit()">
                                        <option value="">All Segments</option>
                                        <?php foreach ($segments as $seg): ?>
                                            <option value="<?= htmlspecialchars($seg['id']) ?>" <?= $segment_filter == $seg['id'] ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($seg['segment_name']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <?php if (isset($_GET['page'])): ?>
                                        <input type="hidden" name="page" value="<?= htmlspecialchars($_GET['page']) ?>">
                                    <?php endif; ?>
                                </form>
                            
                                <!-- Date Filter -->
                                <form method="GET" action="datewise-report.php" class="form-inline mb-0 d-flex align-items-center" style="gap:5px;">
                                    <input type="date" name="start_date" class="form-control form-control-sm" placeholder="Start Date" value="<?= htmlspecialchars($start_date) ?>">
                                    <input type="date" name="end_date" class="form-control form-control-sm" placeholder="End Date" value="<?= htmlspecialchars($end_date) ?>">
                                    <button type="submit" class="btn btn-primary btn-sm">
                                        <i class="fa fa-search"></i>
                                    </button>
                                </form>
                            </div>

                              <div class="col-md-2 col-sm-3 col-3 text-right">
                                 <!-- Import Excel button can be placed here -->
                              </div>
                           </div>
                        </div>
                     </div>
<?php
// include "config.php";

// Handle Proposal Form Submit
if (isset($_POST['save_proposal'])) {
    $lead_id         = intval($_POST['lead_id']);
    $bdm             = mysqli_real_escape_string($conn, $_POST['bdm']);
    $qtnby           = mysqli_real_escape_string($conn, $_POST['qtnby']);
    $proposal        = mysqli_real_escape_string($conn, $_POST['proposaldetails']);
    $total_amount    = mysqli_real_escape_string($conn, $_POST['total_amount']);
    $discount_amount = mysqli_real_escape_string($conn, $_POST['discount_amount']);
    $source          = mysqli_real_escape_string($conn, $_POST['source']); 
    $currency          = mysqli_real_escape_string($conn, $_POST['currency']); 
    
     // new field
    $remarks= mysqli_real_escape_string($conn, $_POST['remarks']); // new field
    $brcode = $_SESSION['branch_code'];
    // Find last proposal for this year
    $year = date("y");
    $sql_last = "SELECT proposal_no FROM proposals 
                 WHERE proposal_no LIKE 'P$year-%' 
                 ORDER BY id DESC LIMIT 1";
    $result = mysqli_query($conn, $sql_last);

    if ($row_last = mysqli_fetch_assoc($result)) {
        $last_no = intval(substr($row_last['proposal_no'], 6));
        $next_no = $last_no + 1;
    } else {
        $next_no = 1;
    }

   $proposal_no = $brcode.$year."-".str_pad($next_no, 5, "0", STR_PAD_LEFT);

// Insert into proposals table
$sql1 = "INSERT INTO proposals 
         (proposal_no, lead_id, bdm, qtnby, details, total, discount, source, remarks, currency,cus_type) 
         VALUES 
         ('$proposal_no','$lead_id','$bdm','$qtnby','$proposal','$total_amount','$discount_amount','$source','$remarks','$currency','New')";

if (mysqli_query($conn, $sql1)) {

    // ðŸ”¥ GET INSERTED PROPOSAL ID
    $proposal_id = mysqli_insert_id($conn);

    // Update tb_positiveleads
    $sql2 = "UPDATE tb_positiveleads 
             SET bdm='$bdm',
                 qtnby='$qtnby',
                 proposal_details='$proposal',
                 total_amount='$total_amount',
                 currency='$currency',
                 discount_amount='$discount_amount',
                 proposal_no='$proposal_no',
                 source='$source',
                 remarks1='$remarks',
                 status='Quotation Submitted',
                 cus_type = 'New'
                 
             WHERE id='$lead_id'";

    if (mysqli_query($conn, $sql2)) {

        echo "<script>
                alert('Proposal saved & Positive Lead updated successfully!');
                window.location.href='proposal-form.php?orderid=$proposal_id';
              </script>";

    } else {
        echo "<script>alert('Error updating positive leads: " . mysqli_error($conn) . "');</script>";
    }

} else {
    echo "<script>alert('Error inserting proposal: " . mysqli_error($conn) . "');</script>";
}

}

?>

<div class="row">
   <div class="table-responsive">
      <table class="table table-hover table-responsive-sm table-small">
         <thead>
            <tr>
               <th class="td-padding-no">#</th>
               <th class="td-padding-no">Company</th>
               <th class="td-padding-no">Mobile No.</th>
               <th class="td-padding-no">Location</th>
               <th class="td-padding-no">Segment</th>
               <th class="td-padding-no">Status</th>
               <th class="td-padding-no">Remarks</th>
               <th class="td-padding-no">Staff</th>
               <th class="td-padding-no" style="text-align: left!important;">Action</th>
               <th></th>
            </tr>
         </thead>
         <tbody>
            <?php if (count($teledata_rows) > 0): ?>
               <?php 
               $starting_number = $total_records - ($offset);
               foreach ($teledata_rows as $row): ?>
                     <tr>
                        <th class="td-padding-no"><?= $starting_number-- ?></th>
                        <td class="td-padding-no"><?= htmlspecialchars($row['company_name']) ?></td>
                        <td class="td-padding-no"><?= htmlspecialchars($row['mobile']) ?></td>
                        <td class="td-padding-no"><?= htmlspecialchars($row['location']) ?></td>
                        <td class="td-padding-no"><?= htmlspecialchars($row['segment_name']) ?></td>
                        <td class="td-padding-no"><?= isset($row['status']) ? htmlspecialchars($row['status']) : '' ?></td>
                        <td class="td-padding-no">
                            <?php 
                                $remarks = isset($row['remarks']) ? $row['remarks'] : '';
                                $short = (strlen($remarks) > 20) ? substr($remarks, 0, 20).'...' : $remarks;
                            ?>
                        
                            <span class="remarks-text"
                                  onclick="showRemarks('<?= htmlspecialchars(addslashes($remarks)) ?>')"
                                  style="cursor:pointer; white-space:nowrap; display:block; overflow:hidden;">
                                <?= htmlspecialchars($short) ?>
                            </span>
                        </td>

                        <td class="td-padding-no"><?= htmlspecialchars($row['name']) ?></td>
                        <td class="td-padding-no" style="text-align:center;">
                           <span style="gap:2px;width: 100%;text-align:center;" class="d-flex">
                                 <a href="?edit=<?= $row['id'] ?><?= $segment_filter > 0 ? '&segment='.$segment_filter : '' ?><?= isset($_GET['page']) ? '&page='.$_GET['page'] : '' ?>" title="Edit"><i class="fa fa-edit text-warning mx-1"></i></a>
                                 <a href="?delete=<?= $row['id'] ?><?= $segment_filter > 0 ? '&segment='.$segment_filter : '' ?><?= isset($_GET['page']) ? '&page='.$_GET['page'] : '' ?>" title="Delete" onclick="return confirm('Are you sure you want to delete this record?');"><i class="fa fa-trash text-danger mx-1"></i></a>
                                 <a href="#!" data-toggle="modal" data-target="#exampleModalhhh" data-id="<?= $row['id'] ?>" title="Proposal">
                                       <i class="fa fa-file-text text-primary mx-1"></i>
                                 </a>
                              </span>
                        </td>
                        <td></td>
                     </tr>
               <?php endforeach; ?>
            <?php else: ?>
               <tr>
                     <td colspan="9" class="text-center">No records found.</td>
               </tr>
            <?php endif; ?>
         </tbody>
      </table>
   </div>


<div class="modal fade" id="remarksModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Remarks</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="remarksContent" style="white-space:pre-wrap;"></div>
        </div>
    </div>
</div>

<script>
function showRemarks(text) {
    document.getElementById('remarksContent').innerText = text;
    var modal = new bootstrap.Modal(document.getElementById('remarksModal'));
    modal.show();
}
</script>


   <!-- Pagination -->
   <?php if ($total_pages > 1): ?>
   <nav aria-label="Page navigation">
      <ul class="pagination justify-content-center">
         <li class="page-item <?= ($page <= 1) ? 'disabled' : '' ?>">
            <a class="page-link" href="?page=<?= $page - 1 ?><?= $segment_filter > 0 ? '&segment='.$segment_filter : '' ?>" aria-label="Previous">
               <span aria-hidden="true">&laquo;</span>
            </a>
         </li>
         <?php
         $max_links = 5;
         $start = max(1, $page - intval($max_links / 2));
         $end = min($total_pages, $start + $max_links - 1);
         if ($end - $start + 1 < $max_links) {
             $start = max(1, $end - $max_links + 1);
         }
         for ($i = $start; $i <= $end; $i++): ?>
            <li class="page-item <?= ($i == $page) ? 'active' : '' ?>">
               <a class="page-link" href="?page=<?= $i ?><?= $segment_filter > 0 ? '&segment='.$segment_filter : '' ?>"><?= $i ?></a>
            </li>
         <?php endfor; ?>
         <li class="page-item <?= ($page >= $total_pages) ? 'disabled' : '' ?>">
            <a class="page-link" href="?page=<?= $page + 1 ?><?= $segment_filter > 0 ? '&segment='.$segment_filter : '' ?>" aria-label="Next">
               <span aria-hidden="true">&raquo;</span>
            </a>
         </li>
      </ul>
   </nav>
   <?php endif; ?>
</div>
<style>
    /* ====== CKEditor 4: Remove paragraph gaps inside the editor ====== */

/* Target the editable area used by CKEditor 4 */
.cke_editable,
.cke_contents,
.cke_editable.cke_editable_themed,
.cke_editable.cke_contents_ltr {
  line-height: 1.35 !important;   /* change to taste */
  font-family: inherit !important;
}

/* Remove margins from paragraphs inside the editor */
.cke_editable p,
.cke_contents p,
.cke_editable.cke_contents_ltr p {
  margin: 0 !important;
  padding: 0 !important;
}

/* Hide empty <br> lines so empty <p> don't create extra vertical gap */
.cke_editable br,
.cke_contents br {
  display: none !important;
}

/* If you want a small gap only between non-empty paragraphs,
   uncomment and adjust the value below */
/*
.cke_editable p + p,
.cke_contents p + p {
  margin-top: .35em !important;
}
*/

/* Make headings consistent inside editor */
.cke_editable h1,
.cke_editable h2,
.cke_editable h3,
.cke_editable h4,
.cke_editable h5,
.cke_editable h6 {
  margin: 0 !important;
  line-height: 1.15 !important;
}

/* ====== Output (.card) - ensure saved HTML also has no gap ====== */
.card p {
  margin: 0 !important;
  padding: 0 !important;
  line-height: 1.35;
}
.card br {
  display: none !important;
}

</style>
<!-- Proposal Modal -->
<div class="modal fade" id="exampleModalhhh" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
   <div class="modal-dialog" role="document">
      <div class="modal-content">
         <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">New Proposal</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
               <span aria-hidden="true">&times;</span>
            </button>
         </div>
         <div class="modal-body">
            <form method="POST">
               <input type="hidden" name="lead_id" id="lead_id" value="">
               <div class="form-group">
                  <input type="text" class="form-control mb-2" id="bdm" name="bdm" placeholder="BDM" required>
                  <input type="text" class="form-control mb-2" id="qtnby" name="qtnby" placeholder="QTN BY" required>
                  <textarea class="form-control my-2" id="proposaldetails" name="proposaldetails" placeholder=""></textarea>
                  <!--<textarea class="form-control my-2" id="proposaldetails" name="proposaldetails"></textarea>-->
                  <input type="text" class="form-control my-2" id="total_amount" name="total_amount" placeholder="Total" required>
                  <input type="text" class="form-control mb-2" id="discount_amount" name="discount_amount" placeholder="Discount">
                   <input type="text" class="form-control mb-2" id="source" name="source" placeholder="Source">
                   <input type="text" class="form-control mb-2" id="currency" name="currency" placeholder="Currency">
                  <textarea class="form-control mb-2" id="remarks" name="remarks" placeholder="Remarks"></textarea>
               </div>
               <button type="submit" name="save_proposal" class="btn btn-primary">Submit</button>
               </div>
            </form>
         </div>
      </div>
   </div>
</div>
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<!-- Bootstrap 4 JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
 <script src="https://cdn.ckeditor.com/4.22.1/full/ckeditor.js"></script>
<script>
/* 1) Add a styles set for custom line-height choices */
CKEDITOR.stylesSet.add('custom_lineheights', [
  { name: 'Line height 0.2', element: 'p', attributes: { 'style': 'line-height:0.2' } },
  { name: 'Line height 0.3', element: 'p', attributes: { 'style': 'line-height:0.3' } },
  { name: 'Line height 0.4', element: 'p', attributes: { 'style': 'line-height:0.4' } },
  { name: 'Line height 0.5', element: 'p', attributes: { 'style': 'line-height:0.5' } },
  { name: 'Line height 0.6', element: 'p', attributes: { 'style': 'line-height:0.6' } },
  { name: 'Line height 0.7', element: 'p', attributes: { 'style': 'line-height:0.7' } },
  { name: 'Line height 0.8', element: 'p', attributes: { 'style': 'line-height:0.8' } },

  { name: 'Line height 1.0', element: 'p', attributes: { 'style': 'line-height:1.0' } },
  { name: 'Line height 1.2', element: 'p', attributes: { 'style': 'line-height:1.2' } },
  { name: 'Line height 1.4', element: 'p', attributes: { 'style': 'line-height:1.4' } },
  { name: 'Line height 1.6', element: 'p', attributes: { 'style': 'line-height:1.6' } },

  { name: 'Line height 2.0', element: 'p', attributes: { 'style': 'line-height:2.0' } },
  { name: 'Line height 2.5', element: 'p', attributes: { 'style': 'line-height:2.5' } },
  { name: 'Line height 3.0', element: 'p', attributes: { 'style': 'line-height:3.0' } },
  { name: 'Line height 3.5', element: 'p', attributes: { 'style': 'line-height:3.5' } },
  { name: 'Line height 4.0', element: 'p', attributes: { 'style': 'line-height:4.0' } }
]);

/* 2) Replace textarea with CKEditor and configure toolbar/plugins */
CKEDITOR.replace('proposaldetails', {
  // use our styles set in the Styles drop-down
  stylesSet: 'custom_lineheights',
  // Useful plugins already present in the "full" build: font, colorbutton, justify, image, codesnippet...
  toolbar: [
    { name: 'clipboard', items: [ 'Undo', 'Redo' ] },
    { name: 'styles',  items: [ 'Styles', 'Format' ] }, // Styles contains our line-height choices
    { name: 'basicstyles', items: [ 'Bold', 'Italic', 'Underline', 'Strike' ] },
    { name: 'fonts', items: [ 'Font', 'FontSize' ] },
    { name: 'colors', items: [ 'TextColor', 'BGColor' ] },
    { name: 'paragraph', items: [ 'NumberedList', 'BulletedList', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight' ] },
    { name: 'insert', items: [ 'Link', 'Image', 'Table' ] },
    { name: 'tools', items: [ 'Maximize', 'Source' ] },
    // our custom letter-spacing button will be added programmatically below
    { name: 'custom', items: [ 'LetterSpacing' ] }
  ],

  // define default font choices
  font_names: 'Arial; Verdana; Tahoma; Georgia; "Times New Roman"; Roboto; Poppins;',

  // increase font size options
  fontSize_sizes: '8/8px;10/10px;12/12px;14/14px;16/16px;18/18px;24/24px;36/36px;',

  // allow all content styles (you can restrict if needed)
  allowedContent: true
});


/* 3) Add a custom Letter-Spacing button (applies inline span with letter-spacing) */
CKEDITOR.on('instanceReady', function(evt) {
  var editor = evt.editor;

  // Define the command that applies/removes letter-spacing
  editor.addCommand('letterSpacingCmd', {
    exec: function(editor) {
      var sel = editor.getSelection();
      if (!sel) return;

      var selectedText = sel.getSelectedText();
      if (!selectedText) {
        // if nothing selected, offer to set letter spacing on current block/word
        var val = prompt('Enter letter-spacing in px (example: 1.5 for 1.5px). Empty to cancel:', '1.5');
        if (!val) return;
        // wrap current selection position with span
        var style = new CKEDITOR.style({ element: 'span', attributes: { 'style': 'letter-spacing:' + val + 'px;' } });
        editor.applyStyle(style);
        return;
      }

      // If text selected, ask for value and apply inline style span
      var value = prompt('Enter letter-spacing in px (example: 1.5 for 1.5px). Empty to cancel:', '1.5');
      if (!value) return;

      var range = sel.getRanges()[0];
      // create a style and apply
      var style = new CKEDITOR.style({ element: 'span', attributes: { 'style': 'letter-spacing:' + value + 'px;' } });
      editor.applyStyle(style, range);
    }
  });

  // Add a toolbar button that triggers the command
  editor.ui.addButton('LetterSpacing', {
    label: 'Letter Spacing',
    command: 'letterSpacingCmd',
    toolbar: 'custom',
    // simple icon as base64 (small inline SVG) — CKEditor will accept a CSS class or icon name too
    icon: 'https://cdn.iconscout.com/icon/free/png-256/letter-spacing-2064331-1740296.png'
  });

  // OPTIONAL: add a context-menu item (if context menu plugin available)
  try {
    if (editor.contextMenu) {
      editor.addMenuGroup('letterSpacingGroup');
      editor.addMenuItem('applyLetterSpacing', {
        label: 'Apply letter spacing',
        command: 'letterSpacingCmd',
        group: 'letterSpacingGroup'
      });
      editor.contextMenu.addListener(function(element) {
        return { applyLetterSpacing: CKEDITOR.TRISTATE_OFF };
      });
    }
  } catch (e) { /* ignore if contextMenu plugin not present */ }
});
</script>


<!-- Summernote + Bootstrap JS -->
<link href="https://cdn.jsdelivr.net/npm/summernote@0.8.20/dist/summernote-lite.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.4/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/summernote@0.8.20/dist/summernote-lite.min.js"></script>

<script>
   $('#exampleModalhhh').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget); // link that triggered the modal
    var leadId = button.data('id');      // extract lead_id
    $('#lead_id').val(leadId);           // set hidden field
});
$(document).ready(function() {
   $('#proposaldetails').summernote({
      placeholder: 'PROPOSAL DETAILS',
      tabsize: 2,
      height: 200,
     
      toolbar: [
         ['style', ['bold', 'italic', 'underline']],
         ['para', ['ul', 'ol']],
         ['insert', ['link']]
      ]
   });


});
</script>

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
      <script src="assets/vendor/global/global.min.js"></script>
      <script src="assets/vendor/bootstrap-select/dist/js/bootstrap-select.min.js"></script>
      <script src="assets/vendor/bootstrap-datepicker-master/js/bootstrap-datepicker.min.js"></script>
      <script src="assets/vendor/apexchart/apexchart.js"></script>
      <script src="assets/vendor/chartjs/chart.bundle.min.js"></script>
      <script src="assets/vendor/peity/jquery.peity.min.js"></script>
      <script src="assets/js/dashboard/dashboard-1.js"></script>
      <script src="assets/vendor/owl-carousel/owl.carousel.js"></script>
      <script src="assets/js/jquery.localizationTool.js"></script>
      <script src="assets/js/translator.js"></script>    
      <script src="assets/js/custom.min.js"></script>
      <script src="assets/js/dlabnav-init.js"></script>
      <script src="assets/js/demo.js"></script>
   </body>
</html>
<?php $conn->close(); ?>
