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

// Handle post-submission (Add/Edit)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = $_POST['id'] ?? null;
    $name = $conn->real_escape_string($_POST['name']);
    $type = $conn->real_escape_string($_POST['connection_type']);
    $printer = $conn->real_escape_string($_POST['printer_name']);
    $ip = $conn->real_escape_string($_POST['ip_address']);
    $is_active = isset($_POST['is_active']) ? 1 : 0;

    if ($id) {
        $conn->query("UPDATE kot_devices SET name='$name', connection_type='$type', printer_name='$printer', ip_address='$ip', is_active=$is_active WHERE id=$id");
    } else {
        $conn->query("INSERT INTO kot_devices (name, connection_type, printer_name, ip_address, is_active) VALUES ('$name', '$type', '$printer', '$ip', $is_active)");
    }

    header("Location: /itrpos/devices.php?success=1");

    exit;
}

// Handle delete
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $conn->query("DELETE FROM kot_devices WHERE id = $id");
    header("Location: kot-devices.php?deleted=1");
    exit;
}
?>

<body>
<div class="main-wrapper">
	<div class="page-wrapper">
		<div class="content">
			<div class="page-header">
				<div class="page-title">
					<h4>KOT/BOT Devices</h4>
					<h6>Manage your kitchen/bar printers</h6>
				</div>
				<div class="page-btn">
					<a href="#" class="btn btn-added" data-bs-toggle="modal" data-bs-target="#deviceModal" onclick="openDeviceForm()">
						<i class="fa fa-plus me-2"></i>Add Device
					</a>
				</div>
			</div>

			<div class="card">
				<div class="card-body">
					<table class="table datatable table-bordered">
						<thead>
							<tr>
								<th>Name</th>
								<th>Type</th>
								<th>Printer</th>
								<th>IP</th>
								<th>Status</th>
								<th>Actions</th>
							</tr>
						</thead>
						<tbody>
							<?php
							$res = $conn->query("SELECT * FROM kot_devices ORDER BY id DESC");
							while ($row = $res->fetch_assoc()):
							?>
							<tr>
								<td><?= $row['name'] ?></td>
								<td><?= strtoupper($row['connection_type']) ?></td>
								<td><?= $row['printer_name'] ?></td>
								<td><?= $row['ip_address'] ?: '-' ?></td>
								<td><?= $row['is_active'] ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-danger">Inactive</span>' ?></td>
								<td>
									<a href="#" class="btn btn-sm btn-warning" data-bs-toggle="modal" data-bs-target="#deviceModal"
										onclick='openDeviceForm(<?= json_encode($row) ?>)'>
										Edit
									</a>
									<a href="kot-devices.php?delete=<?= $row['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Delete this device?')">
										Delete
									</a>
								</td>
							</tr>
							<?php endwhile; ?>
						</tbody>
					</table>
				</div>
			</div>

			<!-- Modal -->
			<div class="modal fade" id="deviceModal" tabindex="-1">
				<div class="modal-dialog">
					<form method="post" class="modal-content">
						<div class="modal-header">
							<h5 class="modal-title">Add/Edit Device</h5>
							<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
						</div>
						<div class="modal-body">
							<input type="hidden" name="id" id="device_id">

							<div class="mb-3">
								<label class="form-label">Name</label>
								<input type="text" name="name" id="device_name" class="form-control" required>
							</div>

							<div class="mb-3">
								<label class="form-label">Connection Type</label>
								<select name="connection_type" id="device_type" class="form-control" required onchange="toggleIPField()">
									<option value="usb">USB</option>
									<option value="lan">LAN</option>
								</select>
							</div>

							<div class="mb-3">
								<label class="form-label">Printer Name</label>
								<input type="text" name="printer_name" id="device_printer" class="form-control" required>
							</div>

							<div class="mb-3" id="ip_group">
								<label class="form-label">IP Address</label>
								<input type="text" name="ip_address" id="device_ip" class="form-control">
							</div>

							<div class="form-check">
								<input class="form-check-input" type="checkbox" name="is_active" id="device_active" checked>
								<label class="form-check-label">Active</label>
							</div>
						</div>
						<div class="modal-footer">
							<button type="submit" class="btn btn-primary">Save</button>
						</div>
					</form>
				</div>
			</div>

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

<?php if (isset($_GET['success'])): ?>
<script>
Swal.fire({
	title: 'Saved!',
	text: 'Device saved successfully.',
	icon: 'success',
	timer: 2000,
	showConfirmButton: false
});
</script>
<?php endif; ?>

<?php if (isset($_GET['deleted'])): ?>
<script>
Swal.fire({
	title: 'Deleted!',
	text: 'Device deleted successfully.',
	icon: 'success',
	timer: 2000,
	showConfirmButton: false
});
</script>
<?php endif; ?>

<<script>
function openDeviceForm(data = {}) {
    $('#device_id').val(data.id || '');
    $('#device_name').val(data.name || '');
    $('#device_type').val(data.connection_type || 'usb');
    $('#device_printer').val(data.printer_name || '');
    $('#device_ip').val(data.ip_address || '');
    $('#device_active').prop('checked', data.is_active == 1 || !data.id);
    toggleIPField();
}

function toggleIPField() {
    const type = $('#device_type').val();
    const ipGroup = $('#ip_group');
    if (type === 'lan') {
        ipGroup.show();
        $('#device_ip').prop('required', true);
    } else {
        ipGroup.hide();
        $('#device_ip').prop('required', false);
    }
}

function isValidIP(ip) {
    const regex = /^(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)){3}$/;
    return regex.test(ip);
}

$(document).ready(function () {
    toggleIPField();

    $('#device_type').change(toggleIPField);

    $('form.modal-content').submit(function (e) {
        const type = $('#device_type').val();
        const ip = $('#device_ip').val().trim();

        if (type === 'lan' && ip && !isValidIP(ip)) {
            e.preventDefault();
            Swal.fire({
                title: 'Invalid IP Address',
                text: 'Please enter a valid IP (e.g., 192.168.1.100)',
                icon: 'error'
            });
            return false;
        }
    });
});
</script>

</body>
</html>
