<?php
include 'branch_connection.php';
session_start();

$userid = isset($_SESSION['userid']) ? $_SESSION['userid'] : 'Not set';
$username = isset($_SESSION['username']) ? $_SESSION['username'] : '';
$is_admin = ($username === 'admin');
$message = "";
$edit_mode = false;
$edit_id = 0;

// Filters
$limit = 10;
$page = (isset($_GET['page']) && is_numeric($_GET['page']) && $_GET['page'] > 0) ? intval($_GET['page']) : 1;
$offset = ($page - 1) * $limit;

$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$sort = isset($_GET['sort']) ? $_GET['sort'] : '';
$order_by = 'p.id DESC';

if ($sort === 'asc') {
    $order_by = 'c.company_name ASC';
} elseif ($sort === 'desc') {
    $order_by = 'c.company_name DESC';
}

$search_condition = "";
if (!empty($search)) {
    $search_escaped = mysqli_real_escape_string($conn, $search);
    $search_condition = "WHERE c.company_name LIKE '%$search_escaped%' OR c.mobile LIKE '%$search_escaped%'";
}

 $sql2 = "
SELECT 
    p.*,

    /* customer name */
    COALESCE(c.customer_name, mo.customer_name) AS customer_name,

    /* company name */
    COALESCE(c.company_name, mo.company_name) AS company_name,

    /* mobile */
    COALESCE(c.mobile, mo.mobile) AS mobile,

    /* location */
    COALESCE(c.location, mo.location) AS location

FROM proposals p

LEFT JOIN tb_positiveleads c 
    ON p.lead_id = c.id

LEFT JOIN marketing_order mo 
    ON p.lead_id = mo.id

$search_condition
ORDER BY $order_by
LIMIT $limit OFFSET $offset
";



$result2 = mysqli_query($conn, $sql2);
$proposal_rows = array();
if ($result2 && mysqli_num_rows($result2) > 0) {
    while ($row = mysqli_fetch_assoc($result2)) {
        $proposal_rows[] = $row;
    }
}

// Count total records for pagination
$count_sql = "SELECT COUNT(*) as total 
              FROM proposals p 
              LEFT JOIN tb_positiveleads c ON p.lead_id = c.id 
              $search_condition";
$total_result = mysqli_query($conn, $count_sql);
$total_row = mysqli_fetch_assoc($total_result);
$total_records = $total_row['total'];
$total_pages = ceil($total_records / $limit);
?>
<!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>
<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">Proposals</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 
include "header.php"; 
?>
<div class="content-body">
<div class="container-fluid">
<div class="row">
<div class="col-xl-12">

<div class="row mb-3">
    <form method="GET" class="d-flex justify-content-between align-items-center w-100">
        <div class="input-group" style="max-width: 300px;">
            <input type="text" name="search" class="form-control" placeholder="Search by company or mobile"
                   value="<?php echo isset($_GET['search']) ? htmlspecialchars($_GET['search']) : ''; ?>">
            <button class="btn btn-primary" type="submit">Search</button>
        </div>

        <div class="input-group" style="max-width: 200px;">
            <label class="input-group-text">Sort:</label>
            <select name="sort" class="form-select" onchange="this.form.submit()">
                <option value="">Default</option>
                <option value="asc" <?php if(isset($_GET['sort']) && $_GET['sort']=='asc') echo 'selected'; ?>>A → Z</option>
                <option value="desc" <?php if(isset($_GET['sort']) && $_GET['sort']=='desc') echo 'selected'; ?>>Z → A</option>
            </select>
        </div>
    </form>
</div>

<?php

if (isset($_POST['save_proposal'])) {
    $lead_id         = intval($_POST['lead_id']);
    $proposal_id     = !empty($_POST['proposal_id']) ? intval($_POST['proposal_id']) : null;
    $bdm             = mysqli_real_escape_string($conn, $_POST['bdm']);
    $qtnby           = mysqli_real_escape_string($conn, $_POST['qtnby']);
    $proposal        = mysqli_real_escape_string($conn, $_POST['proposaldetails']);
    
    // $proposal = mysqli_real_escape_string($conn, clean_word_html($_POST['proposal_details']));
    $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']);
    $remarks         = mysqli_real_escape_string($conn, $_POST['remarks']); 
    $brcode          = $_SESSION['branch_code'];

    if ($proposal_id) {
        // Update existing proposal
        $sql1 = "UPDATE proposals SET 
                    bdm='$bdm',
                    qtnby='$qtnby',
                    details='$proposal',
                    total='$total_amount',
                    discount='$discount_amount',
                    source='$source',
                    currency='$currency',
                    remarks='$remarks'
                 WHERE id='$proposal_id'";

        if (mysqli_query($conn, $sql1)) {
            // Update positive lead
            mysqli_query($conn, "UPDATE tb_positiveleads 
                SET bdm='$bdm',
                    qtnby='$qtnby',
                    proposal_details='$proposal',
                    total_amount='$total_amount',
                    currency='$currency',
                    discount_amount='$discount_amount',
                    source='$source',
                    remarks1='$remarks',
                    status='Quotation Submitted'
                WHERE id='$lead_id'");
            echo "<script>alert('Proposal updated successfully!');window.location.href='all-proposals.php';</script>";
        } else {
            echo "<script>alert('Error updating proposal: " . mysqli_error($conn) . "');</script>";
        }
    } else {
        // Add new proposal
        $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);

        $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)) {
            $proposal_id = mysqli_insert_id($conn);
            mysqli_query($conn, "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'");
            echo "<script>alert('Proposal saved successfully!');window.location.href='all-proposals.php';</script>";
        } else {
            echo "<script>alert('Error inserting proposal: " . mysqli_error($conn) . "');</script>";
        }
    }
}
?>

<div class="table-responsive">
<table class="table table-hover table-responsive-sm table-small">
<thead>
<tr>
<th>#</th>
<th>Company</th>
<th>Mobile No.</th>
<th>Location</th>
<th>Proposal No</th>
<th>BDM</th>
<th>Quotation By</th>
<th>Total</th>
<th>Discount</th>
<th>Proposal Date</th>
<th>Status</th>
<th style="text-align:left!important;">Action</th>
</tr>
</thead>
<tbody>
<?php if (!empty($proposal_rows)): ?>
    <?php foreach ($proposal_rows as $index => $row): ?>
    <tr>
        <td><?php echo ($offset + $index + 1); ?></td>
        <td><?php echo htmlspecialchars($row['company_name']); ?></td>
        <td><?php echo htmlspecialchars($row['mobile']); ?></td>
        <td><?php echo htmlspecialchars($row['location']); ?></td>
        <td><?php echo htmlspecialchars($row['proposal_no']); ?></td>
        <td><?php echo htmlspecialchars($row['bdm']); ?></td>
        <td><?php echo htmlspecialchars($row['qtnby']); ?></td>
        <td><?php echo htmlspecialchars($row['total']); ?></td>
        <td><?php echo htmlspecialchars($row['discount']); ?></td>
        <td><?php echo !empty($row['created_at']) ? date('d/m/Y', strtotime($row['created_at'])) : 'N/A'; ?></td>
        <td style="
    color:
    <?php
        if ($row['status'] === 'Approved') {
            echo 'green';
        } elseif ($row['status'] === 'Pending') {
            echo 'orange';
        } else {
            echo 'black';
        }
    ?>
">
    <?php echo htmlspecialchars($row['status']); ?>
</td>

        <td style="text-align:center;">
            <span class="d-flex justify-content-center" style="gap:8px; width:100%;">

                <a href="all-proposal-form2.php?orderid=<?php echo $row['id']; ?>" title="View Proposal" style="color:#007bff; font-size:18px;">
                    <i class="fa fa-eye"></i>
                </a>

                <a href="workordernew.php?orderid=<?php echo $row['id']; ?>" title="View Orderform" style="color:#007bff; font-size:18px;">
                    <i class="fa fa-file-text"></i>
                </a>

                <!-- FIXED Bootstrap 4 modal trigger + correct data attributes -->
                <a href="#!"
                   data-toggle="modal" data-target="#exampleModalhhh"
                   data-id="<?= $row['id'] ?>"
                   data-proposal_id="<?= $row['id'] ?>"
                   data-bdm="<?= htmlspecialchars($row['bdm'], ENT_QUOTES) ?>"
                   data-qtnby="<?= htmlspecialchars($row['qtnby'], ENT_QUOTES) ?>"
                   data-details="<?= htmlspecialchars($row['details'], ENT_QUOTES) ?>"
                   data-total="<?= htmlspecialchars($row['total'], ENT_QUOTES) ?>"
                   data-discount="<?= htmlspecialchars($row['discount'], ENT_QUOTES) ?>"
                   data-source="<?= htmlspecialchars($row['source'], ENT_QUOTES) ?>"
                   data-currency="<?= htmlspecialchars($row['currency'], ENT_QUOTES) ?>"
                   data-remarks="<?= htmlspecialchars($row['remarks1'], ENT_QUOTES) ?>"
                   title="Edit Proposal">
                   <i class="fa fa-edit text-warning mx-1"></i>
                </a>

            </span>
        </td>
    </tr>
    <?php endforeach; ?>
<?php else: ?>
<tr><td colspan="12" style="text-align:center;">No proposals found.</td></tr>
<?php endif; ?>
</tbody>
</table>

<!-- Pagination -->
<nav aria-label="Page navigation">
<ul class="pagination">
<?php for($p = 1; $p <= $total_pages; $p++): ?>
<li class="page-item <?php echo ($p == $page) ? 'active' : ''; ?>">
<a class="page-link" href="?page=<?php echo $p; ?>"><?php echo $p; ?></a>
</li>
<?php endfor; ?>
</ul>
</nav>
<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;
}
.cke_editable p {
        margin-top: 0 !important;
        margin-bottom: 0 !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">
               <input type="hidden" name="proposal_id" id="proposal_id">

               <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"></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>

            </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>

<!-- CKEditor 4 -->
  <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>
<script>
// Remove CKEditor banner
CKEDITOR.config.removePlugins = 'notification';

// Activate CKEditor
CKEDITOR.replace('proposaldetails', {
    extraPlugins: 'pastefromword',
    allowedContent: true,
    pasteFromWordPromptCleanup: true,
    pasteFromWordRemoveFontStyles: false,
    pasteFromWordRemoveStyles: false,
});

// Fill modal values when clicking edit button
$('#exampleModalhhh').on('show.bs.modal', function(event) {
    var btn = $(event.relatedTarget);

    $('#proposal_id').val(btn.data('proposal_id'));
    $('#lead_id').val(btn.data('id'));

    $('#bdm').val(btn.data('bdm'));
    $('#qtnby').val(btn.data('qtnby'));

    // CKEditor content
    CKEDITOR.instances['proposaldetails'].setData(btn.data('details'));

    $('#total_amount').val(btn.data('total'));
    $('#discount_amount').val(btn.data('discount'));
    $('#source').val(btn.data('source'));
    $('#currency').val(btn.data('currency'));
    $('#remarks').val(btn.data('remarks'));
});
</script>

<?php include "footer.php"; ?>

<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 mysqli_close($conn); ?>