<?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>Supplier List</h4>
					<h6>Manage your suppliers</h6>
				</div>
				<div class="page-btn">
					<a href="#" class="btn btn-added" data-bs-toggle="modal" data-bs-target="#addSupplierModal"><i class="fa fa-plus me-2"></i>Add Supplier</a>
				</div>
			</div>

			<div class="card">
				<div class="card-body">
					<table class="table datatable table-bordered">
						<thead>
							<tr>
								<th>Name</th>
								<th>Contact</th>
								<th>Email</th>
								<th>Address</th>
								<th>Status</th>
								<th>Created At</th>
								<th>Actions</th>
							</tr>
						</thead>
						<tbody>
							<?php
							$res = $conn->query("SELECT * FROM vendors ORDER BY id DESC");
							while ($row = $res->fetch_assoc()) {
								$status_class = $row['is_active'] ? 'badge-success' : 'badge-danger';
								$status_text = $row['is_active'] ? 'Active' : 'Inactive';
								
								echo "<tr>
									<td>{$row['name']}</td>
									<td>{$row['contact_number']}</td>
									<td>{$row['email']}</td>
									<td>{$row['address']}</td>
									<td><span class='badge {$status_class}'>{$status_text}</span></td>
									<td>{$row['created_at']}</td>
									<td>
										<button type='button' class='btn btn-sm btn-primary edit-supplier' 
												data-id='{$row['id']}' 
												data-name='{$row['name']}' 
												data-contact='{$row['contact_number']}' 
												data-email='{$row['email']}' 
												data-address='{$row['address']}'
												data-active='{$row['is_active']}'
												data-bs-toggle='modal' 
												data-bs-target='#editSupplierModal'>
											<i class='fa fa-edit'></i> Edit
										</button>
									</td>
								</tr>";
							}
							?>
						</tbody>
					</table>
				</div>
			</div>

			<!-- Add Supplier Modal -->
			<div class="modal fade" id="addSupplierModal" tabindex="-1">
				<div class="modal-dialog">
					<form method="POST" action="add_supplier.php" class="modal-content">
						<div class="modal-header">
							<h5 class="modal-title">Add Supplier</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>Contact Number</label>
								<input type="text" name="contact_number" 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>Status</label>
								<select name="is_active" class="form-control">
									<option value="1">Active</option>
									<option value="0">Inactive</option>
								</select>
							</div>
						</div>
						<div class="modal-footer">
							<button type="submit" class="btn btn-primary">Save Supplier</button>
						</div>
					</form>
				</div>
			</div>
			<!-- End Modal -->

			<!-- Edit Supplier Modal -->
			<div class="modal fade" id="editSupplierModal" tabindex="-1">
				<div class="modal-dialog">
					<form method="POST" action="edit_supplier.php" class="modal-content">
						<div class="modal-header">
							<h5 class="modal-title">Edit Supplier</h5>
							<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
						</div>
						<div class="modal-body">
							<input type="hidden" name="supplier_id" id="edit_supplier_id">
							<div class="mb-2">
								<label>Name</label>
								<input type="text" name="name" id="edit_name" class="form-control" required>
							</div>
							<div class="mb-2">
								<label>Contact Number</label>
								<input type="text" name="contact_number" id="edit_contact_number" class="form-control">
							</div>
							<div class="mb-2">
								<label>Email</label>
								<input type="email" name="email" id="edit_email" class="form-control">
							</div>
							<div class="mb-2">
								<label>Address</label>
								<textarea name="address" id="edit_address" class="form-control"></textarea>
							</div>
							<div class="mb-2">
								<label>Status</label>
								<select name="is_active" id="edit_is_active" class="form-control">
									<option value="1">Active</option>
									<option value="0">Inactive</option>
								</select>
							</div>
						</div>
						<div class="modal-footer">
							<button type="submit" class="btn btn-primary">Update Supplier</button>
						</div>
					</form>
				</div>
			</div>
			<!-- End Edit Modal -->

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

<script>
// JavaScript to populate edit modal with supplier data
document.addEventListener('DOMContentLoaded', function() {
    const editButtons = document.querySelectorAll('.edit-supplier');
    
    editButtons.forEach(button => {
        button.addEventListener('click', function() {
            const id = this.getAttribute('data-id');
            const name = this.getAttribute('data-name');
            const contact = this.getAttribute('data-contact');
            const email = this.getAttribute('data-email');
            const address = this.getAttribute('data-address');
            const active = this.getAttribute('data-active');
            
            // Populate the edit modal fields
            document.getElementById('edit_supplier_id').value = id;
            document.getElementById('edit_name').value = name;
            document.getElementById('edit_contact_number').value = contact;
            document.getElementById('edit_email').value = email;
            document.getElementById('edit_address').value = address;
            document.getElementById('edit_is_active').value = active;
        });
    });
});
</script>

</body>
</html>
<?php if (isset($_GET['success']) && $_GET['success'] == 1): ?>
<script>
Swal.fire({
  title: 'Supplier Added',
  text: 'Supplier 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; ?>

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

<?php if (isset($_GET['error'])): ?>
<script>
let errorMessage = 'An error occurred.';
switch('<?php echo $_GET['error']; ?>') {
    case 'name_required':
        errorMessage = 'Supplier name is required.';
        break;
    case 'invalid_email':
        errorMessage = 'Please enter a valid email address.';
        break;
    case 'supplier_not_found':
        errorMessage = 'Supplier not found.';
        break;
    case 'update_failed':
        errorMessage = 'Failed to update supplier. Please try again.';
        break;
}
Swal.fire({
  title: 'Error',
  text: errorMessage,
  icon: 'error',
  timer: 3000,
  showConfirmButton: false
});
if (window.location.search.includes('error=')) {
  history.replaceState({}, document.title, window.location.pathname);
}
</script>
<?php endif; ?>