<?php 
include 'db.php'; 
include 'auth.php';
require_right('Access POS');

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add':
                $name = trim($_POST['name']);
                $employee_id = trim($_POST['employee_id']);
                $phone = trim($_POST['phone']);
                $email = trim($_POST['email']);
                $commission_rate = floatval($_POST['commission_rate']);
                $password = trim($_POST['password']);
                
                // Check if employee_id already exists
                $check = $conn->prepare("SELECT id FROM order_takers WHERE employee_id = ?");
                $check->bind_param("s", $employee_id);
                $check->execute();
                if ($check->get_result()->num_rows > 0) {
                    $error = "Employee ID already exists!";
                } else {
                    // Hash the password
                    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                    $stmt = $conn->prepare("INSERT INTO order_takers (name, employee_id, phone, email, commission_rate, password) VALUES (?, ?, ?, ?, ?, ?)");
                    $stmt->bind_param("ssssds", $name, $employee_id, $phone, $email, $commission_rate, $hashed_password);
                    if ($stmt->execute()) {
                        $success = "Order taker added successfully!";
                    } else {
                        $error = "Error adding order taker: " . $conn->error;
                    }
                }
                break;
                
            case 'edit':
                $id = intval($_POST['id']);
                $name = trim($_POST['name']);
                $employee_id = trim($_POST['employee_id']);
                $phone = trim($_POST['phone']);
                $email = trim($_POST['email']);
                $commission_rate = floatval($_POST['commission_rate']);
                $is_active = intval($_POST['is_active']);
                $password = trim($_POST['password']);
                
                // Check if employee_id exists for other records
                $check = $conn->prepare("SELECT id FROM order_takers WHERE employee_id = ? AND id != ?");
                $check->bind_param("si", $employee_id, $id);
                $check->execute();
                if ($check->get_result()->num_rows > 0) {
                    $error = "Employee ID already exists!";
                } else {
                    if (!empty($password)) {
                        // Hash the new password
                        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                        $stmt = $conn->prepare("UPDATE order_takers SET name = ?, employee_id = ?, phone = ?, email = ?, commission_rate = ?, is_active = ?, password = ? WHERE id = ?");
                        $stmt->bind_param("ssssdssi", $name, $employee_id, $phone, $email, $commission_rate, $is_active, $hashed_password, $id);
                    } else {
                        // Don't update password if empty
                        $stmt = $conn->prepare("UPDATE order_takers SET name = ?, employee_id = ?, phone = ?, email = ?, commission_rate = ?, is_active = ? WHERE id = ?");
                        $stmt->bind_param("ssssdii", $name, $employee_id, $phone, $email, $commission_rate, $is_active, $id);
                    }
                    if ($stmt->execute()) {
                        $success = "Order taker updated successfully!";
                    } else {
                        $error = "Error updating order taker: " . $conn->error;
                    }
                }
                break;
                
            case 'delete':
                $id = intval($_POST['id']);
                $stmt = $conn->prepare("DELETE FROM order_takers WHERE id = ?");
                $stmt->bind_param("i", $id);
                if ($stmt->execute()) {
                    $success = "Order taker deleted successfully!";
                } else {
                    $error = "Error deleting order taker: " . $conn->error;
                }
                break;
        }
    }
}

// Get all order takers
$order_takers = $conn->query("SELECT * FROM order_takers ORDER BY name");
?>

<?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>Order Takers Management</h4>
					<h6>Manage your order takers and commission rates</h6>
				</div>
				<div class="page-btn">
					<a href="#" class="btn btn-added" data-bs-toggle="modal" data-bs-target="#addOrderTakerModal">
						<i class="fa fa-plus me-2"></i>Add Order Taker
					</a>
				</div>
			</div>

			<?php if (isset($success)): ?>
				<div class="alert alert-success alert-dismissible fade show" role="alert">
					<?= htmlspecialchars($success) ?>
					<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
				</div>
			<?php endif; ?>

			<?php if (isset($error)): ?>
				<div class="alert alert-danger alert-dismissible fade show" role="alert">
					<?= htmlspecialchars($error) ?>
					<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
				</div>
			<?php endif; ?>

			<!-- Order Takers Table -->
			<div class="card">
				<div class="card-body">
					<div class="table-responsive">
						<table class="table datatable table-bordered">
							<thead>
								<tr>
									<th>ID</th>
									<th>Name</th>
									<th>Employee ID</th>
									<th>Phone</th>
									<th>Email</th>
									<th>Commission Rate</th>
									<th>Status</th>
									<th>Actions</th>
								</tr>
							</thead>
							<tbody>
								<?php while ($taker = $order_takers->fetch_assoc()): ?>
								<tr>
									<td><?= $taker['id'] ?></td>
									<td><?= htmlspecialchars($taker['name']) ?></td>
									<td><?= htmlspecialchars($taker['employee_id']) ?></td>
									<td><?= htmlspecialchars($taker['phone']) ?></td>
									<td><?= htmlspecialchars($taker['email']) ?></td>
									<td><?= $taker['commission_rate'] ?>%</td>
									<td>
										<span class="badge bg-<?= $taker['is_active'] ? 'success' : 'danger' ?>">
											<?= $taker['is_active'] ? 'Active' : 'Inactive' ?>
										</span>
									</td>
									<td>
										<a href="#" class="btn btn-sm btn-primary" onclick="editOrderTaker(<?= htmlspecialchars(json_encode($taker)) ?>)">
											<i class="fas fa-edit"></i> Edit
										</a>
										<a href="#" class="btn btn-sm btn-danger" onclick="deleteOrderTaker(<?= $taker['id'] ?>, '<?= htmlspecialchars($taker['name']) ?>')">
											<i class="fas fa-trash"></i> Delete
										</a>
									</td>
								</tr>
								<?php endwhile; ?>
							</tbody>
						</table>
					</div>
				</div>
			</div>
            			<!-- Add Order Taker Modal -->
			<div class="modal fade" id="addOrderTakerModal" tabindex="-1">
				<div class="modal-dialog">
					<div class="modal-content">
						<div class="modal-header">
							<h5 class="modal-title">Add Order Taker</h5>
							<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
						</div>
						<form method="POST">
							<div class="modal-body">
								<input type="hidden" name="action" value="add">
								
								<div class="mb-3">
									<label for="add_name" class="form-label">Name *</label>
									<input type="text" class="form-control" id="add_name" name="name" autocomplete="name" required>
								</div>
								
								<div class="mb-3">
									<label for="add_employee_id" class="form-label">Employee ID *</label>
									<input type="text" class="form-control" id="add_employee_id" name="employee_id" autocomplete="off" required>
								</div>
								
								<div class="mb-3">
									<label for="add_phone" class="form-label">Phone</label>
									<input type="tel" class="form-control" id="add_phone" name="phone" autocomplete="tel">
								</div>
								
								<div class="mb-3">
									<label for="add_email" class="form-label">Email</label>
									<input type="email" class="form-control" id="add_email" name="email" autocomplete="email">
								</div>
								
								<div class="mb-3">
									<label for="add_commission_rate" class="form-label">Commission Rate (%)</label>
									<input type="number" class="form-control" id="add_commission_rate" name="commission_rate" min="0" max="100" step="0.01" value="0" autocomplete="off">
								</div>
								
								<div class="mb-3">
									<label for="add_password" class="form-label">Password *</label>
									<input type="password" class="form-control" id="add_password" name="password" autocomplete="new-password" required>
									<small class="form-text text-muted">Password will be used for tablet login</small>
								</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">Add Order Taker</button>
							</div>
						</form>
					</div>
				</div>
			</div>

			<!-- Edit Order Taker Modal -->
			<div class="modal fade" id="editOrderTakerModal" tabindex="-1">
				<div class="modal-dialog">
					<div class="modal-content">
						<div class="modal-header">
							<h5 class="modal-title">Edit Order Taker</h5>
							<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
						</div>
						<form method="POST">
							<div class="modal-body">
								<input type="hidden" name="action" value="edit">
								<input type="hidden" name="id" id="edit_id">
								
								<div class="mb-3">
									<label for="edit_name" class="form-label">Name *</label>
									<input type="text" class="form-control" name="name" id="edit_name" autocomplete="name" required>
								</div>
								
								<div class="mb-3">
									<label for="edit_employee_id" class="form-label">Employee ID *</label>
									<input type="text" class="form-control" name="employee_id" id="edit_employee_id" autocomplete="off" required>
								</div>
								
								<div class="mb-3">
									<label for="edit_phone" class="form-label">Phone</label>
									<input type="tel" class="form-control" name="phone" id="edit_phone" autocomplete="tel">
								</div>
								
								<div class="mb-3">
									<label for="edit_email" class="form-label">Email</label>
									<input type="email" class="form-control" name="email" id="edit_email" autocomplete="email">
								</div>
								
								<div class="mb-3">
									<label for="edit_commission_rate" class="form-label">Commission Rate (%)</label>
									<input type="number" class="form-control" name="commission_rate" id="edit_commission_rate" min="0" max="100" step="0.01" autocomplete="off">
								</div>
								
								<div class="mb-3">
									<label for="edit_password" class="form-label">Password</label>
									<input type="password" class="form-control" name="password" id="edit_password" autocomplete="new-password">
									<small class="form-text text-muted">Leave empty to keep current password</small>
								</div>
								
								<div class="mb-3">
									<label for="edit_is_active" class="form-label">Status</label>
									<select class="form-select" name="is_active" id="edit_is_active">
										<option value="1">Active</option>
										<option value="0">Inactive</option>
									</select>
								</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 Order Taker</button>
							</div>
						</form>
					</div>
				</div>
			</div>

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

<script>
	function editOrderTaker(taker) {
		document.getElementById('edit_id').value = taker.id;
		document.getElementById('edit_name').value = taker.name;
		document.getElementById('edit_employee_id').value = taker.employee_id;
		document.getElementById('edit_phone').value = taker.phone;
		document.getElementById('edit_email').value = taker.email;
		document.getElementById('edit_commission_rate').value = taker.commission_rate;
		document.getElementById('edit_is_active').value = taker.is_active;
		
		new bootstrap.Modal(document.getElementById('editOrderTakerModal')).show();
	}
	
	function deleteOrderTaker(id, name) {
		Swal.fire({
			title: 'Delete Order Taker?',
			text: `Are you sure you want to delete "${name}"?`,
			icon: 'warning',
			showCancelButton: true,
			confirmButtonColor: '#d33',
			cancelButtonColor: '#3085d6',
			confirmButtonText: 'Yes, delete!'
		}).then((result) => {
			if (result.isConfirmed) {
				const form = document.createElement('form');
				form.method = 'POST';
				form.innerHTML = `
					<input type="hidden" name="action" value="delete">
					<input type="hidden" name="id" value="${id}">
				`;
				document.body.appendChild(form);
				form.submit();
			}
		});
	}
</script>
