
<?php
// error_reporting(E_ALL);
// ini_set('display_errors', 1);
error_reporting(0);

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';

// Initialize variables
$mobile = $customer_name = $company_name = $segment = $location = $remarks = $status = $category = $followup_date = $next_followup = "";
$edit_id = 0;
$errors = [];
$success_msg = "";
 
// Handle Delete Operation (via GET)
if (isset($_GET['delete_id'])) {
    $delete_id = intval($_GET['delete_id']);
    $stmt = $conn->prepare("DELETE FROM tb_leads WHERE id = ?");
    $stmt->bind_param("i", $delete_id);
    if ($stmt->execute()) {
        $success_msg = "Record deleted successfully.";
    } else {
        $errors[] = "Failed to delete record.";
    }
    $stmt->close();
}

// Handle Edit Form Prefill (via GET)
if (isset($_GET['edit_id'])) {
    $edit_id = intval($_GET['edit_id']);
    $stmt = $conn->prepare("SELECT * FROM tb_leads WHERE id = ?");
    $stmt->bind_param("i", $edit_id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $mobile = $row['mobile'];
        $customer_name = $row['customer_name'];
        $company_name = $row['company_name'];
        $segment = $row['segment'];
        $location = $row['location'];
        $remarks = $row['remarks'];
        $status = $row['status'];
        $category = $row['category'];
        $followup_date = $row['followup_date'];
        $tel_id = $row['tel_id'];
    } else {
        $errors[] = "Record not found for editing.";
        $edit_id = 0;
    }
    $stmt->close();
}

// Handle Add or Update Operation (via POST)
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $edit_id = isset($_POST['edit_id']) ? intval($_POST['edit_id']) : 0;
    $mobile = $_POST['mobile'];
    $customer_name = $_POST['customer_name'];
    $company_name = $_POST['company_name'];
    $segment = $_POST['segment'];
    $location = $_POST['location'];
    $remarks = $_POST['remarks'];
    $status = $_POST['status'];
    $category = $_POST['category'];
    $followup_date = $_POST['followup_date'];
    $tel_id = $_POST['tel_id'];


    // Validate required fields
    if (empty($mobile)) $errors[] = "Mobile No. is required.";
    if (empty($customer_name)) $errors[] = "Customer Name is required.";
    if (empty($company_name)) $errors[] = "Company Name is required.";
    if (empty($segment)) $errors[] = "Segment is required.";
    if (empty($location)) $errors[] = "Location is required.";
    if (empty($status)) $errors[] = "Status is required.";
    if (empty($category)) $errors[] = "Category is required.";
    if (empty($followup_date)) $errors[] = "Follow Up Date is required.";

    if (count($errors) == 0) {
        if ($edit_id > 0) {
            // Update
            $stmt = $conn->prepare("
    UPDATE tb_leads 
    SET mobile=?, customer_name=?, company_name=?, segment=?, location=?, remarks=?, status=?, category=?, followup_date=?, updated_at = NOW() 
    WHERE id=?
");
$stmt->bind_param("sssssssssi", $mobile, $customer_name, $company_name, $segment, $location, $remarks, $status, $category, $followup_date, $edit_id);

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

              if ($status == 'Interested') {
               $stmt2 = $conn->prepare("INSERT INTO tb_positiveleads 
                  (tel_id, mobile, company_name, segment, location, status, created_at) 
                  VALUES (?, ?, ?, ?, ?, ?, NOW())");
               $stmt2->bind_param("isssss", $tel_id, $mobile, $company_name, $segment, $location, $status);
            } else {
               $stmt2 = $conn->prepare("INSERT INTO marketing_order 
                  (tel_id, customer_name, mobile, company_name, segment, location, status, created_at) 
                  VALUES (?, ?, ?, ?, ?, ?, ?, NOW())");
               $stmt2->bind_param("issssss", $tel_id, $customer_name, $mobile, $company_name, $segment, $location, $status);
            }


                if ($stmt2->execute()) {
                    $deleteStmt = $conn->prepare("DELETE FROM tb_leads WHERE id = ?");
                    $deleteStmt->bind_param("i", $edit_id);
                    $deleteStmt->execute();
                    $deleteStmt->close();
                    $success_msg .= " Record inserted into " . ($status == 'Interested' ? 'tb_positiveleads' : 'marketing_order') . " successfully.";
                } else {
                    $errors[] = "Error inserting record: " . $stmt2->error;
                }
                $stmt2->close();
            } else {
                $errors[] = "Failed to update record.";
            }
            $stmt->close();
        } else {
            // Insert new
            $stmt = $conn->prepare("INSERT INTO tb_leads (mobile, customer_name, company_name, segment, location, remarks, status, category, followup_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("sssssssss", $mobile, $customer_name, $company_name, $segment, $location, $remarks, $status, $category, $followup_date);
            if ($stmt->execute()) {
                $success_msg = "Record added successfully.";
                $mobile = $customer_name = $company_name = $segment = $location = $remarks = $status = $category = $followup_date = "";
            } else {
                $errors[] = "Failed to add record.";
            }
            $stmt->close();
        }
    }
}
// Handle filters
$filter_from_date = $_GET['from_date'];
$filter_to_date = $_GET['to_date'];
$filter_status = $_GET['filter_status'];

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

$lead_sql = "SELECT * FROM tb_leads";
$count_sql = "SELECT COUNT(*) as total FROM tb_leads";
$params = [];
$count_params = [];
$types = "";
$count_types = "";
$filter_conditions = [];

if (!empty($filter_from_date) && !empty($filter_to_date)) {
    $filter_conditions[] = "followup_date BETWEEN ? AND ?";
    $types .= "ss";
    $params[] = $filter_from_date;
    $params[] = $filter_to_date;
    $count_types .= "ss";
    $count_params[] = $filter_from_date;
    $count_params[] = $filter_to_date;
}

if (!empty($filter_status)) {
    $filter_conditions[] = "status = ?";
    $types .= "s";
    $params[] = $filter_status;
    $count_types .= "s";
    $count_params[] = $filter_status;
}

if (count($filter_conditions) > 0) {
    $lead_sql .= " WHERE " . implode(" AND ", $filter_conditions);
    $count_sql .= " WHERE " . implode(" AND ", $filter_conditions);
}
$lead_sql .= " ORDER BY id DESC LIMIT ? OFFSET ?";
$types .= "ii";
$params[] = $limit;
$params[] = $offset;

// Count total records
$count_stmt = $conn->prepare($count_sql);
if (!empty($count_params)) {
    $count_stmt->bind_param($count_types, ...$count_params);
}
$count_stmt->execute();
$count_result = $count_stmt->get_result();
$total_row = $count_result->fetch_assoc();
$total_records = $total_row['total'];
$count_stmt->close();

// Fetch leads
$stmt = $conn->prepare($lead_sql);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$leads_result = $stmt->get_result();
$total_pages = ceil($total_records / $limit);
?>


<!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" />
      <style>
        /* Improved print styles to only show the leads table */
        @media print {
          body * {
            visibility: hidden;
          }
          /* Show main wrapper and all descendants of .table-responsive */
          #main-wrapper, #main-wrapper * {
            visibility: visible;
          }
          /* Hide everything inside main-wrapper except table-responsive and its content */
          #main-wrapper > *:not(.content-body) {
            display: none !important;
          }
          #main-wrapper .content-body > .container-fluid > .row > .col-xl-4 {
            display: none !important; /* Hide form section */
          }
          #main-wrapper .content-body > .container-fluid > .row > .col-xl-8 {
            display: block !important; /* Show leads table */
          }
          .table-responsive {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: auto;
            overflow: visible !important;
          }
          /* Optional: Remove background colors and box shadows for printing */
          table, th, td {
            background: none !important;
            box-shadow: none !important;
            color: black !important;
          }
        }
      </style>
   </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-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">Leads</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="row">
                              <div class="col-xl-12">
                                 <div class="card">
                                    <div class="card-body">
                                       <div class="basic-form">
                                          <?php if (!empty($errors)): ?>
                                          <div class="alert alert-danger">
                                             <ul>
                                                <?php foreach($errors as $error): ?>
                                                <li><?php echo htmlspecialchars($error); ?></li>
                                                <?php endforeach; ?>
                                             </ul>
                                          </div>
                                          <?php endif; ?>
                                          <?php if ($success_msg): ?>
                                          <div class="alert alert-success"><?php echo htmlspecialchars($success_msg); ?></div>
                                          <?php endif; ?>
                                          <form method="POST" action="">
                                             <input type="hidden" name="edit_id" value="<?php echo $edit_id; ?>" />
                                             <input type="hidden" name="tel_id" value="<?php echo $tel_id; ?>" />
                                             <div class="row">
                                                <div class="mb-2 col-md-12">
                                                   <input type="text" name="mobile" class="form-control" placeholder="Mobile No." value="<?php echo $mobile; ?>" required />
                                                </div>
                                                <div class="mb-2 col-md-12">
                                                   <input type="text" name="customer_name" class="form-control" placeholder="Customer Name" value="<?php echo $customer_name; ?>" required />
                                                </div>
                                                <div class="mb-2 col-md-12">
                                                   <input type="text" name="company_name" class="form-control" placeholder="Company Name" value="<?php echo $company_name; ?>" required />
                                                </div>
                                                <div class="mb-2 col-md-12">
                                                   <select id="inputState" class="default-select form-control wide" name="segment" required>
                                                      <option disabled>Select Segment</option>
                                                      <?php
                                                        $segments = $conn->query("SELECT segment_name FROM segments ORDER BY segment_name ASC");
                                                        while ($row = $segments->fetch_assoc()) {
                                                            $selected = ($segment == $row['segment_name']) ? "selected" : "";
                                                            echo '<option value="'.htmlspecialchars($row['segment_name']).'" '.$selected.'>'.htmlspecialchars($row['segment_name']).'</option>';
                                                        }
                                                      ?>
                                                   </select>
                                                </div>
                                                <div class="mb-2 col-md-12">
                                                   <input type="text" name="location" class="form-control" placeholder="Location" value="<?php echo $location; ?>" required />
                                                </div>
                                                <div class="mb-2 col-md-12">
                                                   <textarea name="remarks" class="form-control" placeholder="Remarks"><?php echo $remarks; ?></textarea>
                                                </div>
                                                <div class="mb-2 col-md-12">
                                                   <select id="inputStatus" class="default-select form-control wide" name="status" required>
                                                      <option disabled>Select Status</option>
                                                      <?php
                                                      $statuses = ['Interested', 'Future', 'Quotation Submitted', 'Order Received'];
                                                      foreach ($statuses as $s) {
                                                        $selected = ($status == $s) ? 'selected' : '';
                                                        echo "<option value=\"$s\" $selected>$s</option>";
                                                      }
                                                      ?>
                                                   </select>
                                                </div>
                                                <div class="mb-2 col-md-12">
                                                   <select id="inputCategory" class="default-select form-control wide" name="category" required>
                                                      <option disabled>Select Category</option>
                                                      <?php
                                                        $categories = $conn->query("SELECT name FROM categories ORDER BY name ASC");
                                                        while ($row = $categories->fetch_assoc()) {
                                                            $selected = ($category == $row['name']) ? "selected" : "";
                                                            echo '<option value="'.htmlspecialchars($row['name']).'" '.$selected.'>'.htmlspecialchars($row['name']).'</option>';
                                                        }
                                                      ?>
                                                   </select>
                                                </div>
                                                <div class="mb-2 col-md-12">
                                                   <input placeholder="Follow Up Date" name="followup_date" class="form-control" type="text" onfocus="(this.type='date')" onblur="(this.type='text')" value="<?php echo htmlspecialchars($followup_date); ?>" />
                                                </div>
                                             </div>
                                             <button type="submit" class="btn btn-primary w-100"><?php echo ($edit_id > 0) ? "Update" : "Submit"; ?></button>
                                          </form>
                                       </div>
                                    </div>
                                 </div>
                              </div>
                           </div>
                        </div>
                        <div class="col-xl-8">
                           <div class="row">
                              <div class="row w-100 mb-2 float-right">
                                 <div class="col-md-12">
                                    <form method="GET" id="searchform" class="row g-0" style="gap: 5px;">
                                       <div class="col-md-2 col-sm-3 col-3">
                                          <input name="from_date" placeholder="From" class="w-100" onfocus="(this.type='date')" type="text" onblur="(this.type='text')" value="<?php echo htmlspecialchars($filter_from_date); ?>" />
                                       </div>
                                       
                                       <div class="col-md-2 col-sm-3 col-3">
                                          <input name="to_date" placeholder="To" class="w-100" onfocus="(this.type='date')" type="text" onblur="(this.type='text')" value="<?php echo htmlspecialchars($filter_to_date); ?>" />
                                       </div>
                                       <div class="col-md-2 col-sm-3 col-3">
                                          <select name="filter_status" class="w-100">
                                             <option value="" <?php echo $filter_status == '' ? 'selected' : ''; ?>>Select Status</option>
                                             <?php foreach(['Interested', 'Not Interested', 'Future', 'Quotation Submitted', 'Order Received'] as $s): ?>
                                                <option value="<?php echo $s; ?>" <?php echo $filter_status == $s ? 'selected' : ''; ?>><?php echo $s; ?></option>
                                             <?php endforeach; ?>
                                          </select>
                                       </div>
                                       <div class="col-md-1 col-sm-3 col-3">
                                          <button type="submit" class="w-100" style="height: 100%; padding: 0; display: flex; align-items: center; justify-content: center;">
                                             <i class="fa fa-search"></i>
                                          </button>
                                       </div>
                                       <div class="col-md-2 col-sm-3 col-3">
                                          <button type="button" onclick="printBtn()" class="w-100" style="height: 100%;">
                                          <i class="fa fa-print"></i> Print</button>
                                       </div>
                                    </form>
                                 </div>
                              </div>

<script>
function printBtn() {
    const fromDate = document.querySelector('[name="from_date"]').value;
    const toDate = document.querySelector('[name="to_date"]').value;
    const status = document.querySelector('[name="filter_status"]').value;

    // if (!fromDate || !toDate) {
    //     alert("Please select both From and To dates.");
    //     return;
    // }

    const xhr = new XMLHttpRequest();
    xhr.open("POST", "leads-print.php", true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    xhr.onload = function () {
        if (xhr.status === 200) {
            window.open("leads-print.php", "_blank");
        } else {
            alert("Something went wrong while preparing print data.");
        }
    };

    const params = `from_date=${encodeURIComponent(fromDate)}&to_date=${encodeURIComponent(toDate)}&status=${encodeURIComponent(status)}`;
    xhr.send(params);
}
</script>



                              <div class="table-responsive">
                                 <table class="table table-hover table-responsive-sm">
                                    <thead>
                                       <tr>
                                          <th class="td-padding-no">#</th>
                                          <th class="td-padding-no">Mobile No.</th>
                                          <th class="td-padding-no">Cu.Name</th>
                                          <th class="td-padding-no">Co.Name</th>
                                          <th class="td-padding-no">Segment</th>
                                          <th class="td-padding-no">Location</th>
                                          <th class="td-padding-no">Remarks</th>
                                          <th class="td-padding-no">Status</th>
                                          <th class="td-padding-no">Category</th>
                                          <th class="td-padding-no">FUD</th>
                                          <th class="td-padding-no">Action</th>
                                       </tr>
                                    </thead>
                                    <tbody>
                                       <?php if ($leads_result && $leads_result->num_rows > 0):
                                          $count = $counter = $total_records - $offset;;
                                          while ($lead = $leads_result->fetch_assoc()):
                                              $segment_id = $lead['segment'];
                                                // Get segment name
                                                $seg_query = mysqli_query($conn, "SELECT segment_name FROM segments WHERE id='$segment_id'");
                                                $seg = mysqli_fetch_assoc($seg_query);
                                                $segment_name = $seg['segment_name'] ?? 'N/A';
                                       ?>
                                       <tr>
                                          <th class="td-padding-no"><?php echo $count++; ?></th>
                                          <td class="td-padding-no"><?php echo htmlspecialchars($lead['mobile']); ?></td>
                                          <td class="td-padding-no"><?php echo htmlspecialchars($lead['customer_name']); ?></td>
                                          <td class="td-padding-no"><?php echo htmlspecialchars($lead['company_name']); ?></td>
                                          <td class="td-padding-no"><?php echo htmlspecialchars($segment_name); ?></td>
                                          <td class="td-padding-no"><?php echo htmlspecialchars($lead['location']); ?></td>
                                          <td class="td-padding-no"><?php echo htmlspecialchars($lead['remarks']); ?></td>
                                          <td class="td-padding-no"><?php echo htmlspecialchars($lead['status']); ?></td>
                                          <td class="td-padding-no"><?php echo htmlspecialchars($lead['category']); ?></td>
                                          <td class="td-padding-no"><?php echo htmlspecialchars($lead['followup_date']); ?></td>
                                          <td class="td-padding-no" style="text-align:center;">
                                             <span style="gap:5px;display:flex;justify-content:center;">
                                                <a href="leads.php?edit_id=<?php echo $lead['id']; ?>" class="text-warning"><i class="fa fa-edit"></i></a>
                                                <a href="leads.php?delete_id=<?php echo $lead['id']; ?>" class="text-danger" onclick="return confirm('Are you sure you want to delete this record?');"><i class="fa fa-trash"></i></a>
                                             </span>
                                          </td>
                                       </tr>
                                       <?php endwhile; else: ?>
                                       <tr><td colspan="12" class="text-center">No records found.</td></tr>
                                       <?php endif; ?>
                                    </tbody>
                                 </table>
                              </div>
                              <!-- Pagination controls -->
                              <?php if ($total_pages > 1): ?>
                              <nav aria-label="Page navigation">
                                  <ul class="pagination justify-content-center">
                                      <!-- Previous button -->
                                      <li class="page-item <?php if ($page <= 1) echo 'disabled'; ?>">
                                          <a class="page-link" href="<?php echo '?page=' . ($page - 1) . '&from_date=' . urlencode($filter_from_date) . '&to_date=' . urlencode($filter_to_date) . '&filter_status=' . urlencode($filter_status); ?>" aria-label="Previous">
                                              <span aria-hidden="true">&laquo;</span>
                                          </a>
                                      </li>

                                      <!-- Page numbers -->
                                      <?php
                                      // To avoid showing too many page links, show max 5 pages around current page
                                      $start_page = max(1, $page - 2);
                                      $end_page = min($total_pages, $page + 2);
                                      for ($i = $start_page; $i <= $end_page; $i++):
                                          $active = ($i == $page) ? 'active' : '';
                                      ?>
                                          <li class="page-item <?php echo $active; ?>">
                                              <a class="page-link" href="<?php echo '?page=' . $i . '&from_date=' . urlencode($filter_from_date) . '&to_date=' . urlencode($filter_to_date) . '&filter_status=' . urlencode($filter_status); ?>"><?php echo $i; ?></a>
                                          </li>
                                      <?php endfor; ?>

                                      <!-- Next button -->
                                      <li class="page-item <?php if ($page >= $total_pages) echo 'disabled'; ?>">
                                          <a class="page-link" href="<?php echo '?page=' . ($page + 1) . '&from_date=' . urlencode($filter_from_date) . '&to_date=' . urlencode($filter_to_date) . '&filter_status=' . urlencode($filter_status); ?>" aria-label="Next">
                                              <span aria-hidden="true">&raquo;</span>
                                          </a>
                                      </li>
                                  </ul>
                              </nav>
                              <?php endif; ?>
                           </div>
                        </div>
                     </div>
                  </div>
               </div>
            </div>
         </div>
         <?php
            $title = "Php Header Footer";                   
            include "footer.php";     
         ?>
      </div>

      <!-- Required vendors -->
      <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 $stmt->close(); $conn->close(); ?>


