<?php include 'db.php'; ?>
<?php include 'layout.php'; ?>

<body>
<div class="main-wrapper">
	<div class="page-wrapper">
		<div class="content">
			<div class="page-header">
				<div class="page-title">
					<h4>Customer List</h4>
					<h6>Manage your customers</h6>
				</div>
				<div class="page-btn">
					<a href="#" class="btn btn-added" data-bs-toggle="modal" data-bs-target="#addCustomerModal"><i class="fa fa-plus me-2"></i>Add Customer</a>
				</div>
			</div>

			<div class="card">
				<div class="card-body">
					<table class="table datatable table-bordered">
						<thead>
  <tr>
    <th>Name</th>
    <th>Phone</th>
    <th>Email</th>
    <th>Address</th>
    <th>Province</th>
    <th>Status</th>
    <th>Category</th>
    <th>Discount</th>
    <th>Actions</th> 
  </tr>
</thead>

						<tbody>
							<?php
$res = $conn->query("SELECT customers.*, customer_categories.category_name FROM customers LEFT JOIN customer_categories ON customers.category_id = customer_categories.id ORDER BY customers.id DESC");
while ($row = $res->fetch_assoc()) {
    $discount_display = ($row['discount_applied'] == 'Y') ? $row['discount_rate'] . '%' : 'No';
    echo "<tr>
        <td>{$row['name']}</td>
        <td>{$row['phone']}</td>
        <td>{$row['email']}</td>
        <td>{$row['address']}</td>
        <td>{$row['province']}</td>
        <td>" . ($row['active'] ? 'Active' : 'Inactive') . "</td>
        <td>{$row['category_name']}</td>
        <td>{$discount_display}</td>
        <td>
            <button type='button' class='btn btn-sm btn-primary edit-customer-btn' data-customer-id='{$row['id']}' data-bs-toggle='modal' data-bs-target='#editCustomerModal'>
                <i class='fas fa-edit'></i> Edit
            </button>
        </td>
    </tr>";
}
?>

						</tbody>
					</table>
				</div>
			</div>

			<!-- Add Customer Modal -->
			<div class="modal fade" id="addCustomerModal" tabindex="-1">
				<div class="modal-dialog">
					<form method="POST" action="add_customer.php" class="modal-content">
						<div class="modal-header">
							<h5 class="modal-title">Add Customer</h5>
							<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
						</div>
						<div class="modal-body">
							<div class="mb-2"><label>Name</label><input type="text" name="name" class="form-control" required></div>
							<div class="mb-2"><label>Phone</label><input type="text" name="phone" class="form-control"></div>
							<div class="mb-2"><label>Email</label><input type="email" name="email" class="form-control"></div>
							<div class="mb-2"><label>Address</label><textarea name="address" class="form-control"></textarea></div>
							<div class="mb-2"><label>NTN</label><input type="text" name="ntn" class="form-control"></div>
							<div class="mb-2"><label>Province</label><input type="text" name="province" class="form-control" value="Punjab"></div>
							<div class="mb-2"><label>Category</label>
								<select name="category_id" class="form-control">
									<option value="">Select</option>
									<?php
									$cats = $conn->query("SELECT * FROM customer_categories");
									while ($cat = $cats->fetch_assoc()) {
										echo "<option value='{$cat['id']}'>{$cat['category_name']}</option>";
									}
									?>
								</select>
							</div>
							<div class="form-check mb-2">
								<input class="form-check-input" type="checkbox" name="is_walk_in" id="walkIn">
								<label class="form-check-label" for="walkIn">Is Walk-in?</label>
							</div>
							<div class="form-check mb-2">
								<input class="form-check-input" type="checkbox" name="active" id="active" checked>
								<label class="form-check-label" for="active">Active</label>
							</div>
							<div class="form-check mb-2">
								<input class="form-check-input" type="checkbox" name="discount_applied" id="discount_applied">
								<label class="form-check-label" for="discount_applied">Apply Discount</label>
							</div>
							<div class="mb-2">
								<label>Discount Rate (%)</label>
								<input type="number" name="discount_rate" class="form-control" min="0" max="100" step="0.01" placeholder="0.00">
							</div>
						</div>
						<div class="modal-footer"><button type="submit" class="btn btn-primary">Save Customer</button></div>
					</form>
				</div>
			</div>

			<!-- Edit Customer Modal -->
			<div class="modal fade" id="editCustomerModal" tabindex="-1">
				<div class="modal-dialog">
					<form id="editCustomerForm" class="modal-content">
						<div class="modal-header">
							<h5 class="modal-title">Edit Customer</h5>
							<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
						</div>
						<div class="modal-body">
							<input type="hidden" id="edit_customer_id" name="id">
							<div class="mb-2"><label>Name</label><input type="text" id="edit_name" name="name" class="form-control" required></div>
							<div class="mb-2"><label>Phone</label><input type="text" id="edit_phone" name="phone" class="form-control"></div>
							<div class="mb-2"><label>Email</label><input type="email" id="edit_email" name="email" class="form-control"></div>
							<div class="mb-2"><label>Address</label><textarea id="edit_address" name="address" class="form-control"></textarea></div>
							<div class="mb-2"><label>NTN</label><input type="text" id="edit_ntn" name="ntn" class="form-control"></div>
							<div class="mb-2"><label>Province</label><input type="text" id="edit_province" name="province" class="form-control"></div>
							<div class="mb-2"><label>Category</label>
								<select id="edit_category_id" name="category_id" class="form-control">
									<option value="">Select</option>
									<?php
									$cats = $conn->query("SELECT * FROM customer_categories");
									while ($cat = $cats->fetch_assoc()) {
										echo "<option value='{$cat['id']}'>{$cat['category_name']}</option>";
									}
									?>
								</select>
							</div>
							<div class="form-check mb-2">
								<input class="form-check-input" type="checkbox" id="edit_is_walk_in" name="is_walk_in">
								<label class="form-check-label" for="edit_is_walk_in">Is Walk-in?</label>
							</div>
							<div class="form-check mb-2">
								<input class="form-check-input" type="checkbox" id="edit_active" name="active">
								<label class="form-check-label" for="edit_active">Active</label>
							</div>
							<div class="form-check mb-2">
								<input class="form-check-input" type="checkbox" id="edit_discount_applied" name="discount_applied">
								<label class="form-check-label" for="edit_discount_applied">Apply Discount</label>
							</div>
							<div class="mb-2">
								<label>Discount Rate (%)</label>
								<input type="number" id="edit_discount_rate" name="discount_rate" class="form-control" min="0" max="100" step="0.01" placeholder="0.00">
							</div>
						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
							<button type="submit" class="btn btn-primary">Update Customer</button>
						</div>
					</form>
				</div>
			</div>

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

<script>
$(document).ready(function() {
    // Handle edit customer button click
    $('.edit-customer-btn').click(function() {
        var customerId = $(this).data('customer-id');
        
        // Fetch customer data via AJAX
        $.ajax({
            url: 'ajax/get_customer.php',
            type: 'GET',
            data: { id: customerId },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    var customer = response.customer;
                    
                    // Populate modal fields
                    $('#edit_customer_id').val(customer.id);
                    $('#edit_name').val(customer.name);
                    $('#edit_phone').val(customer.phone);
                    $('#edit_email').val(customer.email);
                    $('#edit_address').val(customer.address);
                    $('#edit_ntn').val(customer.ntn);
                    $('#edit_province').val(customer.province);
                    $('#edit_category_id').val(customer.category_id);
                    $('#edit_is_walk_in').prop('checked', customer.is_walk_in == 1);
                    $('#edit_active').prop('checked', customer.active == 1);
                    $('#edit_discount_applied').prop('checked', customer.discount_applied == 'Y');
                    $('#edit_discount_rate').val(customer.discount_rate);
                } else {
                    alert('Error loading customer data');
                }
            },
            error: function() {
                alert('Error loading customer data');
            }
        });
    });

    // Handle edit customer form submission
    $('#editCustomerForm').submit(function(e) {
        e.preventDefault();
        
        var formData = $(this).serialize();
        formData += '&action=update'; // Add the missing action parameter
        
        $.ajax({
            url: 'ajax/update_customer.php',
            type: 'POST',
            data: formData,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    $('#editCustomerModal').modal('hide');
                    Swal.fire({
                        title: 'Success',
                        text: 'Customer updated successfully!',
                        icon: 'success',
                        timer: 2000,
                        showConfirmButton: false
                    }).then(function() {
                        location.reload();
                    });
                } else {
                    alert('Error updating customer: ' + response.message);
                }
            },
            error: function() {
                alert('Error updating customer');
            }
        });
    });
});
</script>

</body>
</html>

<?php if (isset($_GET['success']) && $_GET['success'] == 1): ?>
<script>
Swal.fire({
  title: 'Customer Added',
  text: 'Customer added successfully!',
  icon: 'success',
  timer: 2000,
  showConfirmButton: false
});
if (window.location.search.includes('success=1')) {
  history.replaceState({}, document.title, window.location.pathname);
}
</script>
<?php endif; ?>
