<?php
include('../config/config.php');
include('../config/session_check.php'); 
$branch_id = $_SESSION['branch_id'];

// Fetch Active Customers
$result = $conn->query("SELECT id, customer_code, customer_name, address, city, pincode, contact_person, phone FROM customers WHERE status='active' && branch_id='$branch_id' ");
?>

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta content="width=device-width, initial-scale=1.0" name="viewport">

  <title>Customer Master</title>
  <meta content="" name="description">
  <meta content="" name="keywords">

  <!-- Favicons -->
  <link href="../assets/img/favicon.png" rel="icon">
  <link href="../assets/img/apple-touch-icon.png" rel="apple-touch-icon">

  <!-- Google Fonts -->
  <link href="https://fonts.gstatic.com" rel="preconnect">
  <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Nunito:300,300i,400,400i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet">

  <!-- Vendor CSS Files -->
  <link href="../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <link href="../assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
  <link href="../assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet">
  <link href="../assets/vendor/quill/quill.snow.css" rel="stylesheet">
  <link href="../assets/vendor/quill/quill.bubble.css" rel="stylesheet">
  <link href="../assets/vendor/remixicon/remixicon.css" rel="stylesheet">
  <link href="../assets/vendor/simple-datatables/style.css" rel="stylesheet">

  <!-- Template Main CSS File -->
  <link href="../assets/css/style.css" rel="stylesheet">


</head>

<body>

  <!-- ======= Header ======= -->
<?php include('../config/header.php'); ?> // Include the header

  <!-- ======= Sidebar ======= -->

<?php include('../config/sidebar.php'); ?>
  <main id="main" class="main">

    <div class="pagetitle">
      <h1>Data Tables</h1>
      <nav>
        <ol class="breadcrumb">
          <li class="breadcrumb-item"><a href="index.html">Home</a></li>
          <li class="breadcrumb-item">Tables</li>
          <li class="breadcrumb-item active">Data</li>
        </ol>
      </nav>
    </div><!-- End Page Title -->

    <section class="section">
      <div class="row">
        <div class="col-lg-12">

          <div class="card">
            <div class="card-body">
                
               
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Customer Master</title>
    <link href="../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
       <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
    @media (max-width: 768px) {
        table thead { display: none; }
        table tbody tr { display: block; margin-bottom: 1rem; border: 1px solid #ccc; padding: 1rem; }
        table tbody td { display: flex; justify-content: space-between; padding: .5rem 0; border-bottom: 1px solid #ddd; }
        table tbody td:last-child { border-bottom: none; }
        table td::before { content: attr(data-label); font-weight: bold; }
    }
    </style>
    
    <script src="../assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<div class="container mt-5">
    <h2>Customer Management</h2>
    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addCustomerModal">Add Customer</button>
     <table class="table datatable">
       <thead>
                  <tr>
                    <th>Customer Code</th>
                    <th>Customer Name</th>
                    <th>Address</th>
                    <th>City</th>
                    <th>Pincode</th>
                    <th>Contact Person</th>
                    <th>Phone</th>
                    <th>Actions</th>
                  </tr>
                </thead>
                <tbody>
                  <?php while($row = $result->fetch_assoc()): ?>
                  <tr>
  <td data-label="Customer Code"><?php echo htmlspecialchars($row['customer_code']); ?></td>
  <td data-label="Customer Name"><?php echo htmlspecialchars($row['customer_name']); ?></td>
  <td data-label="Address"><?php echo htmlspecialchars($row['address']); ?></td>
  <td data-label="City"><?php echo htmlspecialchars($row['city']); ?></td>
  <td data-label="Pincode"><?php echo htmlspecialchars($row['pincode']); ?></td>
  <td data-label="Contact Person"><?php echo htmlspecialchars($row['contact_person']); ?></td>
  <td data-label="Phone"><?php echo htmlspecialchars($row['phone']); ?></td>
  <td data-label="Actions">
    <button onclick="editCustomer(<?php echo $row['id']; ?>)" class="btn btn-warning btn-sm">Edit</button>
    <button onclick="deleteCustomer(<?php echo $row['id']; ?>)" class="btn btn-danger btn-sm">Delete</button>
  </td>
</tr>

                  <?php endwhile; ?>
                </tbody>
    </table>
</div>

<!-- Add Customer Modal -->
<div class="modal fade" id="addCustomerModal" tabindex="-1" aria-labelledby="addCustomerModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addCustomerModalLabel">Add New Customer</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="addCustomerForm">
                    <div class="mb-3">
                        <label for="customer_code" class="form-label">Customer Code</label>
                        <input type="text" class="form-control" id="customer_code" name="customer_code" required>
                    </div>
                    <div class="mb-3">
                        <label for="customer_name" class="form-label">Customer Name</label>
                        <input type="text" class="form-control" id="customer_name" name="customer_name" required>
                    </div>
                    <div class="mb-3">
                        <label for="address" class="form-label">Address</label>
                        <input type="text" class="form-control" id="address" name="address" required>
                    </div>
                    <div class="mb-3">
                        <label for="city" class="form-label">City</label>
                        <input type="text" class="form-control" id="city" name="city" required>
                    </div>
                    <div class="mb-3">
                        <label for="pincode" class="form-label">Pincode</label>
                        <input type="text" class="form-control" id="pincode" name="pincode" required>
                    </div>
                    <div class="mb-3">
                        <label for="contact_person" class="form-label">Contact Person</label>
                        <input type="text" class="form-control" id="contact_person" name="contact_person" required>
                    </div>
                    <div class="mb-3">
                        <label for="phone" class="form-label">Phone</label>
                        <input type="text" class="form-control" id="phone" name="phone" required>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                 <button class="btn btn-primary" onclick="submitAddCustomerForm()">Save</button>
            </div>
        </div>
    </div>
</div>

<!-- Edit Customer Modal -->
<div class="modal fade" id="editCustomerModal" tabindex="-1" aria-labelledby="editCustomerModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editCustomerModalLabel">Edit Customer</h5>
                <button type="button" the="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="editCustomerForm">
                   <div class="mb-3">
                        <label for="customer_code" class="form-label">Customer Code</label>
                        <input type="hidden" class="form-control" id="edit_id" name="id" required>
                        <input type="text" class="form-control" id="editcustomer_code" name="customer_code" required>
                    </div>
                    <div class="mb-3">
                        <label for="customer_name" class="form-label">Customer Name</label>
                        <input type="text" class="form-control" id="editcustomer_name" name="customer_name" required>
                    </div>
                    <div class="mb-3">
                        <label for="address" class="form-label">Address</label>
                        <input type="text" class="form-control" id="editaddress" name="address" required>
                    </div>
                    <div class="mb-3">
                        <label for="city" class="form-label">City</label>
                        <input type="text" class="form-control" id="editcity" name="city" required>
                    </div>
                    <div class="mb-3">
                        <label for="pincode" class="form-label">Pincode</label>
                        <input type="text" class="form-control" id="editpincode" name="pincode" required>
                    </div>
                    <div class="mb-3">
                        <label for="contact_person" class="form-label">Contact Person</label>
                        <input type="text" class="form-control" id="editcontact_person" name="contact_person" required>
                    </div>
                    <div class="mb-3">
                        <label for="phone" class="form-label">Phone</label>
                        <input type="text" class="form-control" id="editphone" name="phone" required>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                 <button class="btn btn-primary" onclick="submitEditCustomerForm()">Update Custome</button>
              
            </div>
        </div>
    </div>
</div>



            </div>  
          </div>

        </div>
      </div>
    </section>

  </main><!-- End #main -->
  
  
  
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script>
// Function to handle Add Customer form submission

function submitAddCustomerForm() {
    $.ajax({
        type: "POST",
        url: "add_customer.php",
        data: $("#addCustomerForm").serialize() + "&action=add",
        success: function(response) {
            alert(response);
            $('#addCustomerModal').modal('hide'); // Close modal
            location.reload(); // Reload page to update data
        },
        error: function(xhr, status, error) {
            console.error("AJAX Error:", status, error);
            alert("Error saving customer.");
        }
    });
}

// Function to submit Edit Customer form
function submitEditCustomerForm() {
    let form = document.getElementById("editCustomerForm");
    let formData = new FormData(form);

    let xhr = new XMLHttpRequest();
    xhr.open("POST", "edit_customer.php", true);
    
    xhr.onload = function() {
        if (xhr.status === 200) {
            alert(xhr.responseText); // Show success message
            document.getElementById("editCustomerModal").classList.remove("show"); // Close modal
            location.reload(); // Reload page to update data
        } else {
            console.error("AJAX Error:", xhr.statusText);
            alert("Error updating customer.");
        }
    };

    xhr.onerror = function() {
        alert("Request failed.");
    };

    xhr.send(formData); // Send form data
}



// Fetch Customer Data for Editing
function editCustomer(id) {
    $.getJSON("fetch_customer.php", { id: id }, function(data) {
        if (data) {
             $("#edit_id").val(data.id);
            $("#editcustomer_code").val(data.customer_code);
            $("#editcustomer_name").val(data.customer_name);
            $("#editaddress").val(data.address);
            $("#editcity").val(data.city);
            $("#editpincode").val(data.pincode);
            $("#editcontact_person").val(data.contact_person);
            $("#editphone").val(data.phone);
            $('#editCustomerModal').modal('show'); // Show the edit modal
        } else {
            alert("No customer data found!");
        }
    }).fail(function(xhr, textStatus, errorThrown) {
        alert("Request failed: " + textStatus + " - " + errorThrown);
    });
}

// Handle Customer Deletion
function deleteCustomer(id) {
    if (confirm("Are you sure you want to delete this customer?")) {
        $.ajax({
            type: "POST",
            url: "customer_master.php",
            data: { action: "delete", id: id },
            success: function(response) {
                alert(response);
                location.reload();
            },
            error: function() {
                alert("Error deleting customer.");
            }
        });
    }
}

</script>
  <!-- ======= Footer ======= -->
  

  <a href="#" class="back-to-top d-flex align-items-center justify-content-center"><i class="bi bi-arrow-up-short"></i></a>

  <!-- Vendor JS Files -->
  <script src="../assets/vendor/apexcharts/apexcharts.min.js"></script>
  <script src="../assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
  <script src="../assets/vendor/chart.js/chart.umd.js"></script>
  <script src="../assets/vendor/echarts/echarts.min.js"></script>
  <script src="../assets/vendor/quill/quill.js"></script>
  <script src="../assets/vendor/simple-datatables/simple-datatables.js"></script>
  <script src="../assets/vendor/tinymce/tinymce.min.js"></script>
  <script src="../assets/vendor/php-email-form/validate.js"></script>

  <!-- Template Main JS File -->
  <script src="../assets/js/main.js"></script>
<?php include '../config/footer.php'; ?>
</body>

</html>