<?php
   session_start();
   if (!isset($_SESSION['userid'])) {
       // Redirect to login page if userid is not set
       header("Location: ../index.php");
       exit(); // Always use exit after header redirection
   }
   include 'branch_connection.php';

   // Helper function for file upload
   function uploadFile($fileInput, $uploadDir = "uploads/") {
       if (!empty($_FILES[$fileInput]['name'])) {
           $fileName = basename($_FILES[$fileInput]['name']);
           $targetFilePath = $uploadDir . time() . "_" . $fileName;
           $fileType = strtolower(pathinfo($targetFilePath, PATHINFO_EXTENSION));
   
           // Validate file type
           $allowedTypes = ['jpg', 'png', 'jpeg', 'gif', 'mp3', 'wav', 'pdf'];
           if (in_array($fileType, $allowedTypes) && $_FILES[$fileInput]['size'] < 5000000) { // Limit file size to 5MB
               if (!is_dir($uploadDir)) {
                   mkdir($uploadDir, 0755, true);
               }
               if (move_uploaded_file($_FILES[$fileInput]['tmp_name'], $targetFilePath)) {
                   return $targetFilePath;
               }
           }
       } 
       return null;
   }
   
   // Insert or Update
   if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_POST['submit']) {
       // Sanitize inputs
       $staff = $_SESSION['userid'];
       $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
       $order_date = $_POST['order_date'];
       $product_category = $conn->real_escape_string($_POST['product_category']);
       $mobile = $conn->real_escape_string($_POST['mobile']);
       $order_amt = floatval($_POST['order_amt']);
       $order_form = $conn->real_escape_string($_POST['order_form']);
       $srs_text = $conn->real_escape_string($_POST['srs_text']);
       $order_tips = $conn->real_escape_string($_POST['order_tips']);
       $delivery_date = $_POST['delivery_date'];
       $bdo = $conn->real_escape_string($_POST['bdo']);
       $bdm = $conn->real_escape_string($_POST['bdm']);
       $status = $conn->real_escape_string($_POST['status']); // New status field
       $customer_name = $conn->real_escape_string($_POST['customer_name']);
       $services = isset($_POST['services']) 
    ? implode(",", $_POST['services']) 
    : "";

       // For files, preserve existing files if not uploading new ones
       $srs_image = null;
       $srs_voice = null;
       $misc_file = null;
   
       if ($id > 0) {
           $sqlExisting = "SELECT srs_image, srs_voice, misc_file FROM marketing_order WHERE id = ?";
           $stmtExisting = $conn->prepare($sqlExisting);
           $stmtExisting->bind_param("i", $id);
           $stmtExisting->execute();
           $resExisting = $stmtExisting->get_result();
           if ($resExisting && $resExisting->num_rows === 1) {
               $rowEx = $resExisting->fetch_assoc();
               $existing_srs_image = $rowEx['srs_image'];
               $existing_srs_voice = $rowEx['srs_voice'];
               $existing_misc_file = $rowEx['misc_file'];
           } else {
               $existing_srs_image = $existing_srs_voice = $existing_misc_file = null;
           }
           $stmtExisting->close();
       } else {
           $existing_srs_image = $existing_srs_voice = $existing_misc_file = null;
       }
   
       // Upload files if new files are provided, else use existing
       $uploaded_srs_image = uploadFile('srs_image');
       $srs_image = $uploaded_srs_image !== null ? $uploaded_srs_image : $existing_srs_image;
       $uploaded_srs_voice = uploadFile('srs_voice');
       $srs_voice = $uploaded_srs_voice !== null ? $uploaded_srs_voice : $existing_srs_voice;
       $uploaded_misc_file = uploadFile('misc_file');
       $misc_file = $uploaded_misc_file !== null ? $uploaded_misc_file : $existing_misc_file;
   
       if ($id > 0) {
           // Update existing record
           if ($status === 'Cancelled') {
       // Insert into leads table instead of updating marketing_order
        $stmt = $conn->prepare("INSERT INTO tb_leads (customer_name, mobile , status) 
                                   VALUES (?, ?, ?)");
           $stmt->bind_param("sss", 
               $customer_name, $mobile, $status);
           $stmt->execute();
   
       // Optionally: delete cancelled record from marketing_order
       $delete = $conn->prepare("DELETE FROM marketing_order WHERE id=?");
       $delete->bind_param("i", $id);
       $delete->execute();
   } else {
       // Update in marketing_order as usual
      $stmt = $conn->prepare("
    UPDATE marketing_order SET
        order_date = ?,
        product_category = ?,
        mobile = ?,
        order_amt = ?,
        order_form = ?,
        srs_image = ?,
        srs_text = ?,
        srs_voice = ?,
        order_tips = ?,
        misc_file = ?,
        delivery_date = ?,
        bdo = ?,
        bdm = ?,
        customer_name = ?,
        services = ?,
        status = ?,
        staff = ?
    WHERE id = ?
");

if (!$stmt) {
    die('SQL ERROR: ' . $conn->error);
}

$stmt->bind_param(
    "ssssssssssssssssii",
    $order_date,
    $product_category,
    $mobile,
    $order_amt,
    $order_form,
    $srs_image,
    $srs_text,
    $srs_voice,
    $order_tips,
    $misc_file,
    $delivery_date,
    $bdo,
    $bdm,
    $customer_name,
    $services,
    $status,
    $staff,
    $id
);

       $stmt->execute();
   }
   
   
           // Check if status is 'Order Confirmed' and order_id is not already set
           if ($status === 'Order Confirmed') {
               // Check if order_id already exists
               $checkSql = "SELECT order_id FROM marketing_order WHERE id = $id";
               $checkResult = mysqli_query($conn, $checkSql);
               $checkRow = mysqli_fetch_assoc($checkResult);
   
               if (empty($checkRow['order_id'])) {
                   // Get current year and month
                   $prefix = date("ym"); // e.g., 2506
   
                   // Count how many 'Order Confirmed' records already have an order_id
                   $countSql = "SELECT COUNT(*) AS total FROM marketing_order WHERE status='Order Confirmed' AND order_id IS NOT NULL";
                   $countResult = mysqli_query($conn, $countSql);
                   $countRow = mysqli_fetch_assoc($countResult);
                   $count = $countRow['total']; // 0 for first, 1 for second, etc.
   
                   // Convert count to letter (A=0, B=1, C=2...)
                   $letter = chr(64 + $count); // chr(65) = 'A'
   
                   // Generate order_id
                   $order_id = $prefix . "-08" . $letter . "-" . $id;
   
                   // Update the record with order_id
                   $updateOrderIdSql = "UPDATE marketing_order SET order_id = '$order_id' WHERE id = $id";
                   mysqli_query($conn, $updateOrderIdSql);
               }
           }
   
       } else {
          if ($status === 'Cancelled') {
           // Save in leads table instead
           $stmt = $conn->prepare("INSERT INTO tb_leads (customer_name, mobile , status) 
                                   VALUES (?, ?, ?)");
           $stmt->bind_param("sss", $customer_name, $mobile, $status);
           $stmt->execute();
       } else {
           // Save in marketing_order (as it is now)
          $stmt = $conn->prepare("
    INSERT INTO marketing_order (
        order_date, product_category, mobile, order_amt, order_form,
        srs_image, srs_text, srs_voice, order_tips, misc_file,
        delivery_date, bdo, bdm, customer_name, services, status, staff
    )
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
");

if (!$stmt) {
    die('SQL ERROR: ' . $conn->error);
}

$stmt->bind_param(
    "ssssssssssssssssi",
    $order_date,
    $product_category,
    $mobile,
    $order_amt,
    $order_form,
    $srs_image,
    $srs_text,
    $srs_voice,
    $order_tips,
    $misc_file,
    $delivery_date,
    $bdo,
    $bdm,
    $customer_name,
    $services,
    $status,
    $staff
);

           $stmt->execute();
       }
   
   
           // Get insert ID
           $last_id = $conn->insert_id;
   
           // Check if status is 'Order Confirmed' and order_id is not already set
           if ($status === 'Order Confirmed') {
               // Check if order_id already exists
               $checkSql = "SELECT order_id FROM marketing_order WHERE id = $last_id";
               $checkResult = mysqli_query($conn, $checkSql);
               $checkRow = mysqli_fetch_assoc($checkResult);
   
               if (empty($checkRow['order_id'])) {
                   // Get current year and month
                   $prefix = date("ym"); // e.g., 2506
   
                   // Count how many 'Order Confirmed' records already have an order_id
                   $countSql = "SELECT COUNT(*) AS total FROM marketing_order WHERE status='Order Confirmed' AND order_id IS NOT NULL";
                   $countResult = mysqli_query($conn, $countSql);
                   $countRow = mysqli_fetch_assoc($countResult);
                   $count = $countRow['total']; // 0 for first, 1 for second, etc.
   
                   // Convert count to letter (A=0, B=1, C=2...)
                   $letter = chr(65 + $count); // chr(65) = 'A'
   
                   // Generate order_id
                   $order_id = $prefix . "-08" . $letter . "-" . $last_id;
   
                   // Update the record with order_id
                   $updateOrderIdSql = "UPDATE marketing_order SET order_id = '$order_id' WHERE id = $last_id";
                   mysqli_query($conn, $updateOrderIdSql);
               }
           }
       }
       header('Location: ' . $_SERVER['PHP_SELF']);
       exit();
   }
   
   // Delete record
   if (isset($_GET['delete'])) {
       $deleteId = intval($_GET['delete']);
       $stmtDelete = $conn->prepare("DELETE FROM marketing_order WHERE id = ?");
       $stmtDelete->bind_param("i", $deleteId);
       $stmtDelete->execute();
       $stmtDelete->close();
       header('Location: ' . strtok($_SERVER['REQUEST_URI'], '?'));
       exit();
   }
   
   // Search functionality
  $search_query = '';
if (!empty($_GET['search'])) {
    $search_input = $conn->real_escape_string($_GET['search']);
    $search_query = " AND (
        order_date LIKE '%$search_input%' 
        OR product_category LIKE '%$search_input%' 
        OR mobile LIKE '%$search_input%'
        OR bdo LIKE '%$search_input%' 
        OR bdm LIKE '%$search_input%'
    )";
}

   
   // Pagination variables
   $limit = 20; // Number of records per page
   $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
   $offset = ($page - 1) * $limit;
   
   // Adjust SQL query for pagination and sorting
  $sql = "
    SELECT mo.*, c.name AS category_name
    FROM marketing_order mo
    LEFT JOIN categories c ON mo.product_category = c.id
    WHERE mo.status='Completed'
    $search_query
    ORDER BY mo.id DESC
    LIMIT ? OFFSET ?
";


$stmt = $conn->prepare($sql);

   $stmt->bind_param("ii", $limit, $offset);
   $stmt->execute();
   $results = $stmt->get_result();
   
   // Calculate total records for pagination
   $total_records = mysqli_num_rows(
    $conn->query("
        SELECT mo.id
        FROM marketing_order mo
        LEFT JOIN categories c ON mo.product_category = c.id
        WHERE mo.status='Completed'
        $search_query
    ")
);

   $total_pages = ceil($total_records / $limit);
   
   // For editing an existing record
   $edit_record = null;
   if (isset($_GET['edit'])) {
       $edit_id = intval($_GET['edit']);
       $stmtEdit = $conn->prepare("SELECT * FROM marketing_order WHERE id = ? ORDER BY id DESC");
       $stmtEdit->bind_param("i", $edit_id);
       $stmtEdit->execute();
       $resEdit = $stmtEdit->get_result();
       if ($resEdit && $resEdit->num_rows === 1) {
           $edit_record = $resEdit->fetch_assoc();
       }
       $stmtEdit->close();
   }
   $selected_services = [];

if ($edit_record && isset($edit_record['services'])) {
    $selected_services = explode(",", $edit_record['services']);
}


  $from_date = isset($_GET['from_date']) ? $_GET['from_date'] : '';
$to_date   = isset($_GET['to_date']) ? $_GET['to_date'] : '';
$search    = isset($_GET['search']) ? mysqli_real_escape_string($conn, $_GET['search']) : '';

$sql = "SELECT * FROM marketing_order WHERE status='Completed'";

// Date filter
if ($from_date != '' && $to_date != '') {
    $sql .= " AND order_date BETWEEN '$from_date' AND '$to_date'";
}

// Search filter
if ($search != '') {
    $sql .= " AND (
        product_category LIKE '%$search%' OR
        mobile LIKE '%$search%' OR
        bdo LIKE '%$search%' OR
        bdm LIKE '%$search%' OR
        customer_name LIKE '%$search%'
    )";
}

$sql .= " ORDER BY id DESC";

$result = mysqli_query($conn, $sql);

?>

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Leads 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">
      <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.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.php" class="brand-logo"><img src="assets/images/logo-02.svg" alt=""></a>
            <div class="nav-control">
               <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">
                           CRM Data
                        </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-12">
                     <div class="row">
                        <div class="col-xl-4">
   <div class="card">
      <div class="card-body">
         <div class="basic-form">
             <form method="post" enctype="multipart/form-data">
                 <input type="hidden" name="id" value="<?= $edit_record['id'] ?? '' ?>">
                 <div class="row">
                     <div class="mb-2 col-md-12">
                         <input placeholder="Order Date" class="form-control flatpickr-date" name="order_date" 
                         value="<?= $edit_record['order_date'] ?? '' ?>" required>
                     </div>
                     <div class="mb-2 col-md-12">
                         <input type="text" class="form-control" placeholder="Product Category" name="product_category" 
                         value="<?= $edit_record['product_category'] ?? '' ?>" required>
                     </div>
                     <div class="mb-2 col-md-12">
                         <input type="text" class="form-control" placeholder="Customer Name" name="customer_name" 
                         value="<?= $edit_record['customer_name'] ?? '' ?>" required>
                     </div>
                     <div class="mb-2 col-md-12">
                         <input type="text" class="form-control" placeholder="Mobile No." name="mobile" 
                         value="<?= $edit_record['mobile'] ?? '' ?>" required>
                     </div>
                     <div class="mb-2 col-md-12">
                         <input type="number" step="0.01" class="form-control" placeholder="Order Amt" name="order_amt" 
                         value="<?= $edit_record['order_amt'] ?? '' ?>" required>
                     </div>
                     <div class="mb-2 col-md-12">
                         <input type="text" class="form-control" placeholder="Order Form" name="order_form" 
                         value="<?= $edit_record['order_form'] ?? '' ?>">
                     </div>
                     <div class="mb-2 col-md-12">
                         <input type="file" class="form-control" name="srs_image">
                         <small class="form-text text-muted"><?= $edit_record['srs_image'] ?? 'Upload SRS (JPG/PNG)' ?></small>
                     </div>
                     <div class="mb-2 col-md-12">
                         <textarea class="form-control" rows="3" name="srs_text" placeholder="SRS Text"><?= $edit_record['srs_text'] ?? '' ?></textarea>
                     </div>
                     <div class="mb-2 col-md-12">
                         <input type="file" class="form-control" name="srs_voice">
                         <small class="form-text text-muted"><?= $edit_record['srs_voice'] ?? 'SRS Voice (audio)' ?></small>
                     </div>
                     <div class="mb-2 col-md-12">
                         <input type="text" class="form-control" placeholder="Order Tips" name="order_tips" 
                         value="<?= $edit_record['order_tips'] ?? '' ?>">
                     </div>
                     <div class="mb-2 col-md-12">
                         <input type="file" class="form-control" name="misc_file">
                         <small class="form-text text-muted"><?= $edit_record['misc_file'] ?? 'Miscellaneous file' ?></small>
                     </div>
                     <div class="mb-2 col-md-12">
                         <input placeholder="Delivery Date" class="form-control flatpickr-date" name="delivery_date" 
                         value="<?= $edit_record['delivery_date'] ?? '' ?>">
                     </div>
                     <div class="mb-2 col-md-12">
                         <input type="text" class="form-control" placeholder="BDO" name="bdo" 
                         value="<?= $edit_record['bdo'] ?? '' ?>">
                     </div>
                     <div class="mb-2 col-md-12">
                         <input type="text" class="form-control" placeholder="BDM" name="bdm" 
                         value="<?= $edit_record['bdm'] ?? '' ?>">
                     </div>
                     <style>
                                             .msWrap_aa12 { position: relative; width: 260px; font-family: Arial; }
                                             .msBtn_aa12 {
                                             border: 1px solid #bfbfbf;
                                             padding: 8px 10px;
                                             border-radius: 4px;
                                             background: #fff;
                                             cursor: pointer;
                                             display: flex;
                                             justify-content: space-between;
                                             align-items: center;
                                             }
                                             .msBtn_aa12:hover { border-color: #888; }
                                             .msDrop_aa12 {
                                             position: absolute;
                                             top: 100%; left: 0; width: 100%;
                                             background: white;
                                             border: 1px solid #ccc;
                                             border-radius: 4px;
                                             margin-top: 5px;
                                             display: none;
                                             max-height: 220px;
                                             overflow-y: auto;
                                             z-index: 999;
                                             box-shadow: 0 2px 6px rgba(0,0,0,0.15);
                                             }
                                             .msItem_aa12 {
                                             padding: 6px 10px;
                                             display: flex;
                                             gap: 8px;
                                             align-items: center;
                                             cursor: pointer;
                                             }
                                             .msItem_aa12:hover { background: #f3f3f3; }
                                             .msArrow_aa12 { font-size: 12px; }
                                             .realSelect_aa12 { display: none; }
                                          </style>
                                         <select id="realSelect" class="realSelect_aa12 mb-2 w-100" name="services[]" multiple>
                                             <option value="Website"  <?= in_array("Website", $selected_services) ? "selected" : "" ?>>
                                             Website
                                          </option>

                                          <option value="Social Media Promotion"
                                             <?= in_array("Social Media Promotion", $selected_services) ? "selected" : "" ?>>
                                             Social Media Promotion
                                          </option>

                                          <option value="Domain"
                                             <?= in_array("Domain", $selected_services) ? "selected" : "" ?>>
                                             Domain
                                          </option>

                                          <option value="Server"
                                             <?= in_array("Server", $selected_services) ? "selected" : "" ?>>
                                             Server
                                          </option>

                                          </select>
                                          <div class="msWrap_aa12 w-100 mb-2">
                                             <div class="msBtn_aa12" id="msBtn">
                                                <span id="msText">Select Services</span>
                                                <span class="msArrow_aa12">&#9662;</span>
                                             </div>
                                             <div class="msDrop_aa12" id="msDrop"></div>
                                          </div>
                                          <script>
                                             const realSelect = document.getElementById("realSelect");
                                             const msBtn = document.getElementById("msBtn");
                                             const msDrop = document.getElementById("msDrop");
                                             const msText = document.getElementById("msText");
                                             
                                             // Build items from SELECT
                                             [...realSelect.options].forEach((opt, index) => {
                                               const div = document.createElement("div");
                                               div.className = "msItem_aa12";
                                             
                                               div.innerHTML = `
                                                 <input type="checkbox" class="msChk" data-index="${index}" ${opt.selected ? "checked" : ""}>
                                                 <label>${opt.text}</label>
                                               `;
                                             
                                               // WHOLE ROW CLICKABLE
                                               div.addEventListener("click", (e) => {
                                                 e.stopPropagation();
                                                 const cb = div.querySelector(".msChk");
                                                 cb.checked = !cb.checked;
                                                 updateSelected();
                                               });
                                             
                                               msDrop.appendChild(div);
                                             });
                                             
                                             msBtn.addEventListener("click", (e) => {
                                               e.stopPropagation();
                                               msDrop.style.display = msDrop.style.display === "block" ? "none" : "block";
                                             });
                                             
                                             msDrop.addEventListener("click", (e) => e.stopPropagation());
                                             
                                             function updateSelected() {
                                               let selectedTexts = [];
                                             
                                               document.querySelectorAll(".msChk").forEach((chk) => {
                                                 const idx = chk.dataset.index;
                                                 realSelect.options[idx].selected = chk.checked;
                                             
                                                 if (chk.checked)
                                                   selectedTexts.push(realSelect.options[idx].text);
                                               });
                                             
                                               msText.textContent = selectedTexts.length
                                                 ? selectedTexts.join(", ")
                                                 : "Select Services";
                                             }
                                             
                                             document.addEventListener("click", () => msDrop.style.display = "none");
                                             
                                             updateSelected();
                                          </script>
                     <div class="mb-2 col-md-12">
                         <select class="form-control" name="status" required>
                             <option value="">Select Status</option>
                             <option value="Order Confirmed" <?= isset($edit_record['status']) && $edit_record['status'] == 'Order Confirmed' ? 'selected' : '' ?>>Order Confirmed</option>
                             <option value="Completed" <?= isset($edit_record['status']) && $edit_record['status'] == 'Completed' ? 'selected' : '' ?>>Completed</option>
                             <option value="Cancelled" <?= isset($edit_record['status']) && $edit_record['status'] == 'Cancelled' ? 'selected' : '' ?>>Cancelled</option>
                         </select>
                     </div>
                 </div>
                 <button type="submit" name="submit" class="btn btn-primary w-100">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;">
                       <form method="GET" class="d-flex gap-2 w-100">
                    <!-- From Date -->
                    <div class="col-md-2 col-sm-3 col-3">
                       <input name="from_date" placeholder="From" class="w-100 flatpickr-date" 
       type="text"
       value="<?= isset($_GET['from_date']) ? $_GET['from_date'] : '' ?>">

                    </div>
                    <!-- To Date -->
                    <div class="col-md-2 col-sm-3 col-3">
                        <input name="to_date" placeholder="To" class="w-100 flatpickr-date" 
       type="text"
       value="<?= isset($_GET['to_date']) ? $_GET['to_date'] : '' ?>">
                    </div>
                    <!-- Search -->
                    <div class="col-md-3 col-sm-3 col-3">
                        <input name="search" type="text" class="w-100"
                               placeholder="Search product/mobile/BDO/BDM"
                               value="<?= isset($_GET['search']) ? $_GET['search'] : '' ?>">
                    </div>
                    <!-- Filter Button -->
                    <div class="col-md-2 col-sm-3 col-3">
                        <button type="submit" class="w-100">Filter</button>
                    </div>
                    <!-- Print Button -->
                    <div class="col-md-2 col-sm-3 col-3">
                        <button class="w-100" type="button" onclick="printTable()">
                            <i class="fa fa-print"></i> Print
                        </button>
                    </div>
                </form>
                                 </div>
                              </div>
                           </div>

                           <script>
flatpickr(".flatpickr-date", {
    dateFormat: "Y-m-d",
    allowInput: true,
});
</script>

<script src="assets/js/custom.min.js"></script>

<!-- MOVE THESE THREE TO LAST -->
<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>




                           <div class="row">
                              <div class="table-responsive">
                                 <div class="modal fade" id="textModal132" tabindex="-1" aria-hidden="true">
                                    <div class="modal-dialog modal-dialog-centered">
                                       <div class="modal-content p-3">
                                          <div class="modal-header">
                                             <h5 class="modal-title">Full Text</h5>
                                             <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                          </div>
                                          <div class="modal-body">
                                             GMB listing verified without phone number. Also give an appeal for number verification with their udhyam aadhar. We committed that we will give  10 reviews from our end.      
                                          </div>
                                       </div>
                                    </div>
                                 </div>
                                 <div class="modal fade" id="textModal109" tabindex="-1" aria-hidden="true">
                                    <div class="modal-dialog modal-dialog-centered">
                                       <div class="modal-content p-3">
                                          <div class="modal-header">
                                             <h5 class="modal-title">Full Text</h5>
                                             <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                          </div>
                                          <div class="modal-body">
                                          </div>
                                       </div>
                                    </div>
                                 </div>
                                 <table class="table table-hover table-responsive-sm" id="ordersTable">
                                    <thead>
                                       <tr>
                                          <th class="td-padding-no" style="width: 10px;">#</th>
                                          <th class="td-padding-no" style="width: 80px;">O.Date</th>
                                          <th class="td-padding-no">P.Cat</th>
                                          <th class="td-padding-no">Customer</th>
                                          <th class="td-padding-no">Mobile No.</th>
                                          <th class="td-padding-no">O.Amt</th>
                                          <th class="td-padding-no">O.Form</th>
                                          <th class="td-padding-no">SRS</th>
                                          <th class="td-padding-no">SRS Text</th>
                                          <th class="td-padding-no">SRS Voice</th>
                                          <th class="td-padding-no">O.Tips</th>
                                          <th class="td-padding-no">Misc</th>
                                          <th class="td-padding-no" style="width: 80px;">D.Date</th>
                                          <th class="td-padding-no">BDO</th>
                                          <th class="td-padding-no">BDM</th>
                                          <th class="td-padding-no">Status</th>
                                          <th class="td-padding-no" style="text-align:center; width: 80px;">Action</th>
                                       </tr>
                                    </thead>
                                    <style>
                                       .status-confirmed {
                                       background-color: #d4edda;
                                       color: #155724!important;
                                       font-weight: bold;
                                       }
                                       .td-padding-no {
                                       padding: 0;
                                       word-wrap: break-word;
                                       white-space: normal;
                                       max-width: 500px; /* adjust as needed */
                                       }
                                    </style>
                                   <tbody>
<?php
$sl = $offset + 1;
while ($row = $results->fetch_assoc()) {
?>
<tr>
    <th class="td-padding-no"><?= $sl++; ?></th>
    <td class="td-padding-no"><?= $row['order_date']; ?></td>
    <td class="td-padding-no"><?= $row['category_name'] ?? '-'; ?></td>
    <td class="td-padding-no"><?= $row['customer_name']; ?></td>
    <td class="td-padding-no"><?= $row['mobile']; ?></td>
    <td class="td-padding-no"><?= number_format($row['order_amt'], 2); ?></td>

    <td class="td-padding-no">
        <a href="<?= $row['order_form']; ?>" target="_blank"><?= $row['order_form'] ? 'File' : ''; ?></a>
    </td>

    <td class="td-padding-no">
        <a href="<?= $row['srs_image']; ?>" target="_blank"><?= $row['srs_image'] ? 'File' : '-'; ?></a>
    </td>

    <td class="td-padding-no" style="max-width:200px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;">
        <span data-bs-toggle="modal" data-bs-target="#textModal<?= $row['id']; ?>" style="cursor:pointer;">
            <?= $row['srs_text']; ?>
        </span>
    </td>

    <!-- Modal for SRS text -->
    <div class="modal fade" id="textModal<?= $row['id']; ?>" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content p-3">
                <div class="modal-header">
                    <h5 class="modal-title">Full Text</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body"><?= $row['srs_text']; ?></div>
            </div>
        </div>
    </div>

    <td class="td-padding-no"><?= $row['srs_voice'] ? 'Voice File' : '-'; ?></td>
    <td class="td-padding-no"><?= $row['order_tips']; ?></td>

    <td class="td-padding-no">
        <a href="<?= $row['misc_file']; ?>" target="_blank"><?= $row['misc_file'] ? 'File' : '-'; ?></a>
    </td>

    <td class="td-padding-no"><?= $row['delivery_date']; ?></td>
    <td class="td-padding-no"><?= $row['bdo']; ?></td>
    <td class="td-padding-no"><?= $row['bdm']; ?></td>

    <td class="td-padding-no"><?= $row['status']; ?></td>

    <td class="td-padding-no" style="text-align:center;">
        <a href="?edit=<?= $row['id']; ?>" class="text-warning me-1"><i class="fa fa-edit"></i></a>
        <a href="?delete=<?= $row['id']; ?>" class="text-danger"
           onclick="return confirm('Are you sure you want to delete this order?');">
            <i class="fa fa-trash"></i>
        </a>
        <a href="#!" data-toggle="modal" data-target="#exampleModalhhh" data-id="<?= $row['id'] ?>" title="Proposal">
                                       <i class="fa fa-file-powerpoint"></i>
                                 </a>
        <!--<a href="workordernew.php?orderid=<?php echo $row['id']; ?>" class="text-primary">-->
        <!--    <i class="fa fa-file-alt"></i>-->
        <!--</a>-->
        
    </td>
</tr>
<?php } ?>
</tbody>

                                 </table>
                              </div>
                           </div>
                           <div class="row">
    <div class="col-md-12">
        
        <nav aria-label="Page navigation">
            <ul class="pagination justify-content-center">

                <!-- Previous Button -->
                <li class="page-item <?= ($page <= 1) ? 'disabled' : '' ?>">
                    <a class="page-link" href="?page=<?= $page - 1 ?>">«</a>
                </li>

                <!-- Page Numbers -->
                <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                    <li class="page-item <?= ($page == $i) ? 'active' : '' ?>">
                        <a class="page-link" href="?page=<?= $i ?>">
                            <?= $i ?>
                        </a>
                    </li>
                <?php endfor; ?>

                <!-- Next Button -->
                <li class="page-item <?= ($page >= $total_pages) ? 'disabled' : '' ?>">
                    <a class="page-link" href="?page=<?= $page + 1 ?>">»</a>
                </li>

            </ul>
        </nav>
    </div>
</div>

                        </div>
                     </div>
                  </div>
               </div>
            </div>
         </div>
         <?php
            $title = "Php Header Footer";                   
            include "footer.php";     
            ?>
      </div>
      
      <?php
      error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
// include "config.php";

// Handle Proposal Form Submit
if ($_SERVER['REQUEST_METHOD'] === 'POST' && 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','crm')";

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

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

    // Update tb_positiveleads
    $sql2 = "UPDATE marketing_order 
             SET bdm1='$bdm',
                 qtnby='$qtnby',
                 proposal_details='$proposal',
                 total_amount='$total_amount',
                 currency='$currency',
                 discount_amount='$discount_amount',
                 proposal_no='$proposal_no',
                 source='$source',
                 remarks1='$remarks',
                
                 cus_type = 'crm'
                 
             WHERE id='$lead_id'";

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

        echo "<script>
                alert('Proposal saved & Positive Lead updated successfully!');
                window.location.href='crm_proposal.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>";
}
 
}

?>
      
      <!-- 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"></textarea>
                  <!--<textarea class="form-control my-2" id="proposaldetails" name="proposaldetails" placeholder=""></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>
<!--<script src="https://cdn.ckeditor.com/ckeditor5/41.4.2/classic/ckeditor.js"></script>-->
<script>
// ClassicEditor
//     .create(document.querySelector('#proposaldetails'))
//     .catch(error => {
//         console.error(error);
//     });
</script>
<!-- CKEditor 4 FULL version (supports paste from Word) -->
<script src="https://cdn.ckeditor.com/4.22.1/full/ckeditor.js"></script>
<script>
// REMOVE the “upgrade to CKEditor 5” warning banner
CKEDITOR.config.removePlugins = 'notification';

CKEDITOR.replace('proposaldetails', {
    extraPlugins: 'pastefromword',
    allowedContent: true,

    // Minimal clean toolbar
    toolbar: [
        { name: 'basicstyles', items: [ 'Bold', 'Italic', 'Underline' ] },
        { name: 'paragraph',   items: [ 'NumberedList', 'BulletedList' ] },
        { name: 'links',       items: [ 'Link' ] },
        { name: 'clipboard',   items: [ 'Undo', 'Redo' ] }
    ],

    // Improve Word paste
    pasteFromWordPromptCleanup: true,
    pasteFromWordRemoveFontStyles: false,
    pasteFromWordRemoveStyles: false
});
</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>
         function updateFileLabel(input, labelId) {
             const label = document.getElementById(labelId);
             label.textContent = input.files.length > 0 ? input.files[0].name : 'No file chosen';
         }
         function printTable() {
             var printWindow = window.open('', '', 'height=600,width=800');
             printWindow.document.write('<html><head><title>Print</title>');
             printWindow.document.write('<link href="assets/vendor/bootstrap-select/dist/css/bootstrap-select.min.css" rel="stylesheet"/>');
             printWindow.document.write('<link href="assets/vendor/bootstrap-datepicker-master/css/bootstrap-datepicker.min.css" rel="stylesheet"/>');
             printWindow.document.write('<style>table {width: 100%; border-collapse: collapse;} th, td {border: 1px solid #333; padding: 8px; text-align:left;} </style>');
             printWindow.document.write('</head><body >');
             printWindow.document.write('<h3>Marketing Orders</h3>');
             printWindow.document.write(document.querySelector('.table-responsive').innerHTML);
             printWindow.document.write('</body></html>');
             printWindow.document.close();
             printWindow.focus();
             printWindow.print();
             printWindow.close();
         }
      </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(); ?>