

<!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>
      <?php
         include "config.php"; // DB connection
         $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
         // Handle Create
         if (isset($_POST['add_customer'])) {
             $company_name   = mysqli_real_escape_string($con, $_POST['company_name']);
             $contact_person = mysqli_real_escape_string($con, $_POST['contact_person']);
             $contact_number = mysqli_real_escape_string($con, $_POST['contact_number']);
             $email          = mysqli_real_escape_string($con, $_POST['email']);
             $gst_details    = mysqli_real_escape_string($con, $_POST['gst_details']);
             $address        = mysqli_real_escape_string($con, $_POST['address']);
         
             // File Upload
             $file_name = "";
             if (!empty($_FILES['upload_file']['name'])) {
                 $file_type = pathinfo($_FILES['upload_file']['name'], PATHINFO_EXTENSION);
                 $allowed_types = ['jpg', 'jpeg', 'png', 'pdf']; // Allowed file types
                 if (in_array($file_type, $allowed_types) && $_FILES['upload_file']['size'] <= 50000) { // 50kb limit
                     $file_name = time() . "_" . basename($_FILES['upload_file']['name']);
                     $target = "uploads/" . $file_name;
                     move_uploaded_file($_FILES['upload_file']['tmp_name'], $target);
                 } else {
                     echo "<script>alert('Invalid file type or size exceeds 50kb.');</script>";
                 }
             }
         
             // First, check if the contact number already exists
            $check_query = "SELECT * FROM tbl_customers WHERE contact_number = '$contact_number'";
            $check_result = mysqli_query($con, $check_query);

            if (mysqli_num_rows($check_result) > 0) {
               // Contact number already exists
               echo "<script>alert('Error: Contact number already exists.');</script>";
            } else {
               // Proceed with insertion
               $query = "INSERT INTO tbl_customers (company_name, contact_person, contact_number, email, gst_details, upload_file, address) 
                        VALUES ('$company_name', '$contact_person', '$contact_number', '$email', '$gst_details', '$file_name', '$address')";
               
               if (!mysqli_query($con, $query)) {
                  echo "<script>alert('Error: " . mysqli_error($con) . "');</script>";
               } else {
                  echo "<script>alert('Data Added Successfully');</script>";
               }
            }
         }
         
         // Handle Delete
         if (isset($_GET['delete'])) {
             $id = (int)$_GET['delete'];
             mysqli_query($con, "DELETE FROM tbl_customers WHERE id='$id'");
              echo "<script>alert('Deleted added. Page=$page');</script>";
         }
         
         // Handle Edit Update
         if (isset($_POST['update_customer'])) {
             $id             = (int)$_POST['id'];
             $company_name   = mysqli_real_escape_string($con, $_POST['company_name']);
             $contact_person = mysqli_real_escape_string($con, $_POST['contact_person']);
             $contact_number = mysqli_real_escape_string($con, $_POST['contact_number']);
             $email          = mysqli_real_escape_string($con, $_POST['email']);
             $gst_details    = mysqli_real_escape_string($con, $_POST['gst_details']);
             $address        = mysqli_real_escape_string($con, $_POST['address']);
         
             // File Upload
             if (!empty($_FILES['upload_file']['name'])) {
                 $file_type = pathinfo($_FILES['upload_file']['name'], PATHINFO_EXTENSION);
                 $allowed_types = ['jpg', 'jpeg', 'png', 'pdf']; // Allowed file types
                 if (in_array($file_type, $allowed_types) && $_FILES['upload_file']['size'] <= 50000) { // 50kb limit
                     $file_name = time() . "_" . basename($_FILES['upload_file']['name']);
                     $target = "uploads/" . $file_name;
                     move_uploaded_file($_FILES['upload_file']['tmp_name'], $target);
                     $query = "UPDATE tbl_customers SET company_name='$company_name', contact_person='$contact_person', contact_number='$contact_number', email='$email', gst_details='$gst_details', upload_file='$file_name', address='$address' WHERE id='$id'";
                 } else {
                     echo "<script>alert('Invalid file type or size exceeds 50kb.');</script>";
                 }
             } else {
                 $query = "UPDATE tbl_customers SET company_name='$company_name', contact_person='$contact_person', contact_number='$contact_number', email='$email', gst_details='$gst_details', address='$address' WHERE id='$id'";
         
             
             }
         
             if (!mysqli_query($con, $query)) {
                 echo "<script>alert('Error: " . mysqli_error($con) . "');</script>";
             }else{
                 echo "<script>alert('Successfully added. Page=$page');</script>";
         
             }
         }
         
         // Fetch All Customers
         // Pagination settings
         // Pagination settings
         $limit = 10; // rows per page
         $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
         if ($page < 1) $page = 1;
         $offset = ($page - 1) * $limit;
         
         // Search filter
         $search = isset($_GET['search']) ? mysqli_real_escape_string($con, $_GET['search']) : "";
         
         // Build query with search condition
         $where = "";
         if (!empty($search)) {
             $where = "WHERE company_name LIKE '%$search%' 
                       OR contact_person LIKE '%$search%' 
                       OR contact_number LIKE '%$search%' 
                       OR email LIKE '%$search%'";
         }
         
         // Count total
         $total_result = mysqli_query($con, "SELECT COUNT(*) AS total FROM tbl_customers $where");
         $total_row = mysqli_fetch_assoc($total_result);
         $total_customers = $total_row['total'];
         $total_pages = ceil($total_customers / $limit);
         
         // Fetch customers
         $customers = mysqli_query($con, "SELECT * FROM tbl_customers $where ORDER BY id DESC LIMIT $offset, $limit");
         
         
         $edit_data = null;
         if (isset($_GET['edit'])) {
             $id = (int)$_GET['edit'];
             $result = mysqli_query($con, "SELECT * FROM tbl_customers WHERE id='$id'");
             $edit_data = mysqli_fetch_assoc($result);
         }
         ?>
      <div class="container-scroller">
      <!-- partial:partials/_navbar.html -->
      <?php include "header.php"; ?>
      <!-- partial -->
      <div class="container-fluid page-body-wrapper">
         <?php include "sidebar.php"; ?>
         <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 Customer</h4>
                           <form class="forms-sample" method="POST" enctype="multipart/form-data">
                              <?php if($edit_data) { ?>
                              <input type="hidden" name="id" value="<?php echo $edit_data['id']; ?>">
                              <?php } ?>
                              <div class="form-group">
                                 <div class="form-floating">
                                    <input type="text" class="form-control" name="company_name" placeholder="Company Name" 
                                       value="<?php echo $edit_data ? htmlspecialchars($edit_data['company_name']) : ''; ?>" required>
                                    <label for="floatingPassword">Company Name</label>
                                 </div>
                              </div>
                              <div class="form-group">
                                 <div class="form-floating">
                                 <input type="text" class="form-control" name="contact_person" placeholder="Contact Person" 
                                    value="<?php echo $edit_data ? htmlspecialchars($edit_data['contact_person']) : ''; ?>" required>
                                    <label for="floatingPassword">Contact Person</label>
                                 </div>
                              </div>
                              <div class="form-group">
                                 <div class="form-floating">
                                 <input type="text" class="form-control" name="contact_number" 
                                    placeholder="Contact Number"
                                    value="<?php echo $edit_data ? htmlspecialchars($edit_data['contact_number']) : ''; ?>"
                                    pattern="^[0-9]{10}$" maxlength="10"
                                    title="Enter a valid 10-digit contact number"
                                    required>
                                    <label for="floatingPassword">Contact Number</label>
                                 </div>
                              </div>
                              <div class="form-group">
                                 <div class="form-floating">
                                 <input type="email" class="form-control" name="email" placeholder="Email Address" 
                                    value="<?php echo $edit_data ? htmlspecialchars($edit_data['email']) : ''; ?>" required>
                                    <label for="floatingPassword">Email Address</label>
                                 </div>
                              </div>
                              <div class="form-group">
                                 <div class="form-floating">
                                 <input type="text" class="form-control" name="gst_details" placeholder="GST Details" 
                                    value="<?php echo $edit_data ? htmlspecialchars($edit_data['gst_details']) : ''; ?>">
                                    <label for="floatingPassword">GST Detail</label>
                                 </div>
                              </div>
                              <div class="form-group">
                                 <div class="form-floating">
                                 <input type="file" class="form-control" name="upload_file">
                                 <?php if($edit_data && $edit_data['upload_file']) { ?>
                                 <small>Current File: 
                                 <a href="uploads/<?php echo $edit_data['upload_file']; ?>" target="_blank">
                                 <?php echo $edit_data['upload_file']; ?>
                                 </a>
                                 </small>
                                 <?php } ?>
                                 <small style="float: right;color: red;font-size: 12px;">*File size up to 50kb</small>
                                    <label for="floatingPassword">Uploads</label>
                                 </div>
                              </div>
                              <div class="form-group">
                                 <div class="form-floating">
                                 <textarea class="form-control" name="address" rows="4" placeholder="Address"><?php echo $edit_data ? htmlspecialchars($edit_data['address']) : ''; ?></textarea>
                                    <label for="floatingPassword">Address</label>
                                 </div>
                              </div>
                              <?php if($edit_data) { ?>
                              <button type="submit" name="update_customer" class="btn btn-gradient-warning w-100">Update Customer</button>
                              <?php } else { ?>
                              <button type="submit" name="add_customer" class="btn btn-gradient-primary w-100">Submit</button>
                              <?php } ?>
                           </form>
                        </div>
                     </div>
                  </div>
                  <div class="col-md-8">
                     <div class="card">
                        <div class="card-body">
                           <div class="div d-flex justify-content-between">
                              <h4 class="card-title">Customer</h4>
                              <form method="GET" class="mb-3 d-flex" style="gap:10px;max-width:400px;">
                                 <input type="text" name="search" class="form-control" 
                                    placeholder="Search customer..." 
                                    value="<?php echo isset($_GET['search']) ? htmlspecialchars($_GET['search']) : ''; ?>">
                                 <button type="submit" class="btn btn-gradient-primary">
                                 <i class="fa fa-search"></i> 
                                 </button>
                                 <a href="customer-register-print.php?search=<?php echo urlencode($search); ?>" 
                                    class="btn btn-danger">
                                 <i class="fa fa-print"></i> 
                                 </a>
                              </form>
                           </div>
                           <div class="table-responsive">
                              <table class="table">
                                 <thead>
                                    <tr>
                                       <th>Co.Name</th>
                                       <th>Co.Person</th>
                                       <th>Co.Phone</th>
                                       <th>Co.Email</th>
                                       <th>GST Details</th>
                                       <th>Uploads</th>
                                       <th>Address</th>
                                       <th>Action</th>
                                    </tr>
                                 </thead>
                                 <tbody>
                                    <?php while($row = mysqli_fetch_assoc($customers)) { ?>
                                    <tr>
                                       <td><?php echo htmlspecialchars($row['company_name']); ?></td>
                                       <td><?php echo htmlspecialchars($row['contact_person']); ?></td>
                                       <td><?php echo htmlspecialchars($row['contact_number']); ?></td>
                                       <td><?php echo htmlspecialchars($row['email']); ?></td>
                                       <td title="<?php echo htmlspecialchars($row['gst_details']); ?>">
                                          <?php echo strlen($row['gst_details']) > 3 ? substr(htmlspecialchars($row['gst_details']), 0, 3) . "..." : htmlspecialchars($row['gst_details']); ?>
                                       </td>
                                       <td>
                                          <?php if($row['upload_file']) { ?>
                                          <div class="hover-preview-container">
                                             <a href="uploads/<?php echo htmlspecialchars($row['upload_file']); ?>" target="_blank"><?php echo htmlspecialchars($row['upload_file']); ?></a>
                                             <img src="uploads/<?php echo htmlspecialchars($row['upload_file']); ?>" alt="Preview" class="hover-image">
                                          </div>
                                          <?php } ?>
                                       </td>
                                       <td title="<?php echo htmlspecialchars($row['address']); ?>">
                                          <?php echo strlen($row['address']) > 15 ? substr(htmlspecialchars($row['address']), 0, 15) . "..." : htmlspecialchars($row['address']); ?>
                                       </td>
                                       <td>
                                          <span style="display:flex;gap: 5px;align-items: center;">
                                          <a href="?edit=<?php echo $row['id']; ?>&page=<?php echo $page;?>"><i class="fa fa-edit text-warning"></i></a>
                                          <a href="?delete=<?php echo $row['id']; ?>" onclick="return confirm('Are you sure?')"><i class="fa fa-trash-o text-danger"></i></a>
                                          </span>
                                       </td>
                                    </tr>
                                    <?php } ?>
                                 </tbody>
                              </table>
                           </div>
                           <nav aria-label="Page navigation example">
                              <ul class="pagination">
                                 <li class="page-item <?php if($page <= 1) echo 'disabled'; ?>">
                                    <a class="page-link" href="?page=<?php echo ($page-1); ?>"><i class="fa fa-angle-left"></i></a>
                                 </li>
                                 <?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; ?>"><?php echo $i; ?></a>
                                 </li>
                                 <?php } ?>
                                 <li class="page-item <?php if($page >= $total_pages) echo 'disabled'; ?>">
                                    <a class="page-link" href="?page=<?php echo ($page+1); ?>"><i class="fa fa-angle-right"></i></a>
                                 </li>
                              </ul>
                           </nav>
                        </div>
                     </div>
                  </div>
               </div>
               <div class="col-md-8"></div>
            </div>
            <?php include "footer.php"; ?>
         </div>
      </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>
      <script src="assets/vendors/js/vendor.bundle.base.js"></script>
      <script src="assets/vendors/chart.js/chart.umd.js"></script>
      <script src="assets/vendors/bootstrap-datepicker/bootstrap-datepicker.min.js"></script>
      <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>
      <script src="assets/js/dashboard.js"></script>
   </body>
</html>


