<?php
include "config.php"; // your DB connection file

$edit_mode = false;
$edit_data = [];

// Handle Edit Request (when clicking edit button)
if (isset($_GET['edit'])) {
    $edit_id = intval($_GET['edit']);
    $result_edit = mysqli_query($con, "SELECT * FROM sales_man WHERE id='$edit_id'");
    if ($result_edit && mysqli_num_rows($result_edit) > 0) {
        $edit_data = mysqli_fetch_assoc($result_edit);
        $edit_mode = true;
    }
}
// Handle Delete Request
if (isset($_GET['delete_id'])) {
    $id = intval($_GET['delete_id']);

    // Get salesman data (to delete photo too)
    $result = mysqli_query($con, "SELECT photo FROM sales_man WHERE id='$id'");
    $data = mysqli_fetch_assoc($result);

    // Delete photo if it exists
    if (!empty($data['photo']) && file_exists($data['photo'])) {
        unlink($data['photo']);
    }

    // Delete record
    $sql = "DELETE FROM sales_man WHERE id='$id'";
    if (mysqli_query($con, $sql)) {
        echo "<script>alert('Salesman deleted successfully!'); window.location='add-sales-man';</script>";
        exit;
    } else {
        echo "Error deleting record: " . mysqli_error($con);
    }
}

// Handle Add or Update Salesman
if (isset($_POST['submit'])) {
    $id = intval($_POST['edit_id']);
    $name = mysqli_real_escape_string($con, $_POST['name']);
    $username = mysqli_real_escape_string($con, $_POST['username']);
    $position = mysqli_real_escape_string($con, $_POST['position']);
    $contact = mysqli_real_escape_string($con, $_POST['contact']);
    $email = mysqli_real_escape_string($con, $_POST['email']);
    $address = mysqli_real_escape_string($con, $_POST['address']);

    // Password
    $password = !empty($_POST['password']) 
        ? password_hash($_POST['password'], PASSWORD_DEFAULT) 
        : null;

    // Handle file upload
    $photo = "";
    if (!empty($_FILES['photo']['name'])) {
        $targetDir = "uploads/";
        if (!is_dir($targetDir)) {
            mkdir($targetDir, 0777, true);
        }
        $photo = $targetDir . basename($_FILES['photo']['name']);

        if (!move_uploaded_file($_FILES['photo']['tmp_name'], $photo)) {
            $photo = "";
        }
    }

    if ($id > 0) {
        // UPDATE mode
        $update_query = "UPDATE sales_man SET 
            name='$name',
            username='$username',
            position='$position',
            contact='$contact',
            email='$email',
            address='$address'";

        if (!empty($photo)) {
            $update_query .= ", photo='$photo'";
        }
        if (!empty($password)) {
            $update_query .= ", password='$password'";
        }

        $update_query .= " WHERE id='$id'";

        if (mysqli_query($con, $update_query)) {
            echo "<script>alert('Salesman updated successfully!'); window.location='add_sm.php';</script>";
        } else {
            echo "Error updating: " . mysqli_error($con);
        }
    } else {
        // INSERT mode
        $sql = "INSERT INTO sales_man (name, username, position, contact, email, address, photo, password)
                VALUES ('$name', '$username', '$position', '$contact', '$email', '$address', '$photo', '$password')";

        if (mysqli_query($con, $sql)) {
            echo "<script>alert('Salesman added successfully!'); window.location='add_sm.php';</script>";
        } else {
            echo "Error: " . mysqli_error($con);
        }
    }
}
    
// Search + Pagination handling
$search = "";
$limit =15; // number of rows per page
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
$offset = ($page - 1) * $limit;

if (isset($_GET['search'])) {
    $search = mysqli_real_escape_string($con, $_GET['search']);
    $total_query = "SELECT COUNT(*) as total FROM sales_man WHERE name LIKE '%$search%'";
    $result = mysqli_query($con, "SELECT * FROM sales_man WHERE name LIKE '%$search%' ORDER BY id DESC LIMIT $offset, $limit");
} else {
    $total_query = "SELECT COUNT(*) as total FROM sales_man";
    $result = mysqli_query($con, "SELECT * FROM sales_man ORDER BY id DESC LIMIT $offset, $limit");
}

$total_result = mysqli_query($con, $total_query);
$total_row = mysqli_fetch_assoc($total_result);
$total_records = $total_row['total'];
$total_pages = ceil($total_records / $limit);

?>



<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Pipscart</title>
    <!-- plugins:css -->
    <link rel="stylesheet" href="assets/vendors/mdi/css/materialdesignicons.min.css">
    <link rel="stylesheet" href="assets/vendors/ti-icons/css/themify-icons.css">
    <link rel="stylesheet" href="assets/vendors/css/vendor.bundle.base.css">
    <link rel="stylesheet" href="assets/vendors/font-awesome/css/font-awesome.min.css">
    <!-- endinject -->
    <!-- Plugin css for this page -->
    <link rel="stylesheet" href="assets/vendors/font-awesome/css/font-awesome.min.css" />
    <link rel="stylesheet" href="assets/vendors/bootstrap-datepicker/bootstrap-datepicker.min.css">
    <!-- End plugin css for this page -->
    <!-- inject:css -->
    <!-- endinject -->
    <!-- Layout styles -->
    <link rel="stylesheet" href="assets/css/style.css">
    <!-- End layout styles -->
    <!-- <link rel="shortcut icon" href="assets/images/favicon.png" /> -->
  </head>
  <body>
    <div class="container-scroller">
      <!-- partial:partials/_navbar.html -->
      <!-- partial:partials/_navbar.html -->
         <?php
            $title = "Php Header Footer";
            include "header.php";
            ?>
         <!-- partial -->
         <div class="container-fluid page-body-wrapper">
            <!-- partial:partials/_sidebar.html -->
            <?php
               $title = "Php Header Footer";
               include "sidebar.php";
               ?>
            <!-- partial -->
        <!-- partial -->
        <div class="main-panel">
          <div class="content-wrapper">
            <div class="row g-1">
              <div class="col-md-4">
                <div class="card">
                  <div class="card-body">
                    <!-- <h4 class="card-title">Add Sales Man</h4> -->
                    <h4 class="card-title"><?php echo $edit_mode ? "Edit Sales Man" : "Add Sales Man"; ?></h4>
                      <form class="forms-sample" method="POST" enctype="multipart/form-data">
                        <input type="hidden" name="edit_id" value="<?php echo $edit_mode ? $edit_data['id'] : 0; ?>">
                        <div class="form-group">
                          <div class="form-floating">
                          <input type="text" name="name" class="form-control" placeholder="Name"
                                value="<?php echo $edit_mode ? $edit_data['name'] : ''; ?>" required>
                    <label for="floatingPassword">Name</label>
                    </div>
                        </div>
                        <div class="form-group">
                          <div class="form-floating">
                          <input type="text" name="username" class="form-control" placeholder="Username"
                                value="<?php echo $edit_mode ? $edit_data['username'] : ''; ?>" required>
                    <label for="floatingPassword">Username</label>
                    </div>
                        </div>
                        <div class="form-group">
                          <div class="form-floating">
                          <input type="text" name="position" class="form-control" placeholder="Position"
                                value="<?php echo $edit_mode ? $edit_data['position'] : ''; ?>">
                    <label for="floatingPassword">Position</label>
                    </div>
                        </div>
                        <div class="form-group">
                          <div class="form-floating">
                          <input type="text" 
                                 name="contact" 
                                 class="form-control" 
                                 placeholder="Contact Number" 
                                 maxlength="10" 
                                 pattern="[0-9]{10}" 
                                 title="Enter a valid 10-digit contact number"
                                 value="<?php echo $edit_mode ? htmlspecialchars($edit_data['contact']) : ''; ?>" 
                                 required>
                    <label for="floatingPassword">Contact Number</label>
                    </div>
                        </div>

                        <div class="form-group">
                          <div class="form-floating">
                          <input type="email" name="email" class="form-control" placeholder="Email Address"
                                value="<?php echo $edit_mode ? $edit_data['email'] : ''; ?>">
                    <label for="floatingPassword">Email Address</label>
                    </div>
                        </div>
                        <div class="form-group">
                          <div class="form-floating">
                          <textarea name="address" class="form-control" rows="4" placeholder="Address"><?php echo $edit_mode ? $edit_data['address'] : ''; ?></textarea>
                    <label for="floatingPassword">Address</label>
                    </div>
                        </div>
                        <div class="form-group">
                          <div class="form-floating">
                          <input type="file" name="photo" class="form-control">
                          <?php if ($edit_mode && !empty($edit_data['photo'])) { ?>
                            <p>Current: <a href="<?php echo $edit_data['photo']; ?>" target="_blank">View</a></p>
                          <?php } ?>
                    <label for="floatingPassword">Photo</label>
                    </div>
                        </div>
                        <div class="form-group">
                          <div class="form-floating">
                          <input type="password" name="password" class="form-control" placeholder="Enter Password (Leave blank to keep same)">
                    <label for="floatingPassword">Enter Password (Leave blank to keep same)</label>
                    </div>
                        </div>
                        <button type="submit" name="submit" class="btn btn-gradient-primary w-100">
                          <?php echo $edit_mode ? "Update" : "Submit"; ?>
                        </button>
                      </form>
                  </div>
                </div>
              </div>
              <div class="col-md-8">
                <div class="card">
                  <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                    <h4 class="card-title">Sales Man</h4>
                       <!-- Search Form -->
                    <form method="GET" class="d-flex align-items-center me-2">
                    <!-- Search Input -->
                    <input type="text" name="search" 
                          class="form-control form-control-sm" 
                          placeholder="Search by Name" 
                          value="<?php echo htmlspecialchars($search); ?>" 
                          style="width:160px; margin-right:8px;">

                    <!-- Search Button -->
                    <button type="submit" class="btn btn-sm btn-gradient-primary d-flex align-items-center me-2">
                      <i class="mdi mdi-magnify me-1"></i> 
                    </button>

                    <!-- Print Button -->
                    <a href="salesman-register-print.php<?php echo !empty($search) ? '?search=' . urlencode($search) : ''; ?>" 
                      class="btn btn-sm btn-gradient-info d-flex align-items-center">
                      <i class="mdi mdi-printer me-1"></i> 
                    </a>
                  </form>


                    
                    </div>
                  </div>
               
                   <div class="table-responsive">
                      <table class="table">
                        <thead>
                          <tr>
                            <th>Name</th>
                            <th>Username</th>
                            <th>Position</th>
                            <th>Contact Number</th>
                            <th>Email Address</th>
                            <th>Address</th>
                            <th>Uploads</th>
                            <!--<th>Password</th>-->
                            <th>Action</th>
                          </tr>
                        </thead>
                        <tbody>
                           <?php while ($row = mysqli_fetch_assoc($result)) { ?>
                      <tr>
                        <td><?php echo htmlspecialchars($row['name']); ?></td>
                        <td><?php echo htmlspecialchars($row['username']); ?></td>
                        <td><?php echo htmlspecialchars($row['position']); ?></td>
                        <td><?php echo htmlspecialchars($row['contact']); ?></td>
                        <td><?php echo htmlspecialchars($row['email']); ?></td>
                        <td title="<?php echo htmlspecialchars($row['address']); ?>">
                          <?php echo substr($row['address'], 0, 15) . '...'; ?>
                        </td>
                        <td>
                          <?php if (!empty($row['photo'])) { ?>
                            <a href="<?php echo $row['photo']; ?>" target="_blank"><?php echo basename($row['photo']); ?></a>
                          <?php } else { echo "No Image"; } ?>
                        </td>
                        
                        <td>
                          <a href="?edit=<?php echo $row['id']; ?>"><i class="fa fa-edit text-warning"></i></a>
                          <a href="?delete_id=<?php echo $row['id']; ?>" 
                            onclick="return confirm('Delete this record?')">
                          <i class="fa fa-trash-o text-danger"></i>
                          </a>
                        </td>
                      </tr>
                      <?php } ?>
                        </tbody>
                      </table>
                    </div>
              

<nav aria-label="Page navigation example">
  <ul class="pagination">
    <!-- Previous Button -->
    <li class="page-item <?php if ($page <= 1) echo 'disabled'; ?>">
      <a class="page-link" 
         href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>">
         <i class="fa fa-angle-left"></i>
      </a>
    </li>

    <!-- Page Numbers -->
    <?php for ($i = 1; $i <= $total_pages; $i++) { ?>
      <li class="page-item <?php if ($i == $page) echo 'active'; ?>">
        <a class="page-link" 
           href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>">
           <?php echo $i; ?>
        </a>
      </li>
    <?php } ?>

    <!-- Next Button -->
    <li class="page-item <?php if ($page >= $total_pages) echo 'disabled'; ?>">
      <a class="page-link" 
         href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>">
         <i class="fa fa-angle-right"></i>
      </a>
    </li>
  </ul>
</nav>

                  </div>
                </div>
              </div>
            </div>
        </div>
          </div>
          <!-- content-wrapper ends -->
          <!-- partial:partials/_footer.html -->
          <?php
         $title = "Php Header Footer";
         include "footer.php";
         ?>
          <!-- partial -->
        </div>
        <!-- main-panel ends -->
      </div>
      <!-- page-body-wrapper ends -->
    </div>
    <style>
    .hover-preview-container {
      position: relative;
      display: inline-block;
    }
.table th img, .table td img {
    width: 36px;
    height: 36px;
    border-radius: 0!important;
}
    .hover-image {
      display: none;
      position: absolute;
      bottom: 100%; /* puts image above the link */
      left: 0;
      margin-bottom: 10px;
      width: 200px;
      border: 1px solid #ccc;
      background: #fff;
      box-shadow: 0 0 10px rgba(0,0,0,0.2);
      z-index: 1000;
    }

    .hover-preview-container:hover .hover-image {
      display: block;
    }
  </style>
    <!-- container-scroller -->
    <!-- plugins:js -->
    <script src="assets/vendors/js/vendor.bundle.base.js"></script>
    <!-- endinject -->
    <!-- Plugin js for this page -->
    <script src="assets/vendors/chart.js/chart.umd.js"></script>
    <script src="assets/vendors/bootstrap-datepicker/bootstrap-datepicker.min.js"></script>
    <!-- End plugin js for this page -->
    <!-- inject:js -->
    <script src="assets/js/off-canvas.js"></script>
    <script src="assets/js/misc.js"></script>
    <script src="assets/js/settings.js"></script>
    <script src="assets/js/todolist.js"></script>
    <script src="assets/js/jquery.cookie.js"></script>
    <!-- endinject -->
    <!-- Custom js for this page -->
    <script src="assets/js/dashboard.js"></script>
    <!-- End custom js for this page -->
  </body>
</html>