<?php

require 'db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_receiver']) && !empty($_POST['id'])) {
    $deleteId = (int) $_POST['id'];
    $stmt = $pdo->prepare("DELETE FROM receivers WHERE id = ?");
    $stmt->execute([$deleteId]);
    header("Location: receivers.php");
    exit;
}
include 'header.php';

// Handle receiver update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_receiver'])) {
    $stmt = $pdo->prepare("UPDATE receivers SET name = ?, type = ?, tcpport = ?, enabled = ? WHERE id = ?");
    $stmt->execute([
        $_POST['name'],
        $_POST['type'],
        $_POST['tcpport'],
        isset($_POST['enabled']) ? 1 : 0,
        $_POST['id']
    ]);
    $message = t('Receiver updated successfully.');
}

// Handle add receiver
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_receiver'])) {
    $stmt = $pdo->prepare("INSERT INTO receivers (name, type, tcpport, enabled) VALUES (?, ?, ?, ?)");
    $stmt->execute([
        $_POST['name'],
        $_POST['type'],
        $_POST['tcpport'],
        isset($_POST['enabled']) ? 1 : 0
    ]);
    $message = t('Receiver added successfully.');
}

// Get all receivers
$receivers = $pdo->query("SELECT * FROM receivers")->fetchAll(PDO::FETCH_ASSOC);

function isPortOpen(string $host, int $port, int $timeout = 1): bool {
    $connection = @fsockopen($host, $port, $errno, $errstr, $timeout);
    if (is_resource($connection)) {
        fclose($connection);
        return true;
    }
    return false;
}

?>



<h2><?= t('Receivers') ?>
    <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#addReceiverModal"><?= t('Add receiver') ?></button>
</h2>

<?php if (!empty($message)): ?>
    <div class="alert alert-success"><?= htmlspecialchars($message) ?></div>
<?php endif; ?>

<table id="receiverTable" class="table table-hover" style="cursor:pointer;">
    <thead>
        <tr>
            <th><?= t('Name') ?></th>
            <th><?= t('Protocol') ?></th>
            <th><?= t('Port') ?></th>
            <th><?= t('Enabled') ?></th>
            <th><?= t('status') ?></th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($receivers as $receiver): ?>
            <tr data-bs-toggle="modal" data-bs-target="#editReceiverModal"
                data-id="<?= $receiver['id'] ?>"
                data-name="<?= htmlspecialchars($receiver['name']) ?>"
                data-type="<?= $receiver['type'] ?>"
                data-port="<?= $receiver['tcpport'] ?>"
                data-enabled="<?= $receiver['enabled'] ?>">
                <td><?= htmlspecialchars($receiver['name']) ?></td>
                <td><?= $receiver['type'] ?></td>
                <td><?= $receiver['tcpport'] ?></td>
                <td><?= $receiver['enabled'] ? t('Yes') : t('No') ?></td>
                <td id="status-<?= $receiver['id'] ?>">
                  <?= $statusText ?> <!-- Initial status -->
                </td>
            </tr>
        <?php endforeach; ?>
    </tbody>
</table>

<!-- Edit Receiver Modal -->
<div class="modal fade" id="editReceiverModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <form method="post" class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"><?= t('Edit Receiver') ?></h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" name="id" id="edit-id">
        <div class="mb-3">
          <label class="form-label"><?= t('Name') ?></label>
          <input type="text" name="name" id="edit-name" class="form-control" required>
        </div>
        <div class="mb-3">
          <label class="form-label"><?= t('Protocol') ?></label>
          <select name="type" id="edit-type" class="form-select">
            <option value="SIA-DC09">SIA-DC09</option>
          </select>
        </div>
        <div class="mb-3">
          <label class="form-label"><?= t('Port') ?></label>
          <input type="number" name="tcpport" id="edit-port" class="form-control" required>
        </div>
        <div class="form-check">
          <input type="checkbox" name="enabled" id="edit-enabled" class="form-check-input">
          <label class="form-check-label" for="edit-enabled"><?= t('Enabled') ?></label>
        </div>
      </div>
      <div class="modal-footer">
          <button type="submit" name="update_receiver" class="btn btn-success"><?= t('Update Receiver') ?></button>
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?= t('Cancel') ?></button>
          <button type="submit" name="delete_receiver" id="deleteReceiverBtn" class="btn btn-danger"><?= t('Delete Receiver') ?></button>
    </div>
</div>
    </form>
  </div>
</div>

<!-- Add Receiver Modal -->
<div class="modal fade" id="addReceiverModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <form method="post" class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"><?= t('Add Receiver') ?></h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="mb-3">
          <label class="form-label"><?= t('Name') ?></label>
          <input type="text" name="name" class="form-control" required>
        </div>
        <div class="mb-3">
          <label class="form-label"><?= t('Protocol') ?></label>
          <select name="type" class="form-select">
            <option value="SIA-DC09">SIA-DC09</option>
          </select>
        </div>
        <div class="mb-3">
          <label class="form-label"><?= t('Port') ?></label>
          <input type="number" name="tcpport" class="form-control" required>
        </div>
        <div class="form-check">
          <input type="checkbox" name="enabled" class="form-check-input" checked>
          <label class="form-check-label"><?= t('Enabled') ?></label>
        </div>
      </div>
      <div class="modal-footer">
        <button type="submit" name="add_receiver" class="btn btn-success"><?= t('Add Receiver') ?></button>
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?= t('Cancel') ?></button>
      </div>
    </form>
  </div>
</div>

<script>
document.querySelectorAll('tr[data-bs-toggle="modal"]').forEach(row => {
    row.addEventListener('click', () => {
        const id = row.dataset.id;
        const name = row.dataset.name;
        const type = row.dataset.type;
        const port = row.dataset.port;
        const enabled = row.dataset.enabled;

        document.getElementById('edit-id').value = id;
        document.getElementById('edit-name').value = name;
        document.getElementById('edit-type').value = type;
        document.getElementById('edit-port').value = port;
        document.getElementById('edit-enabled').checked = (enabled === '1');

        // Disable the delete button if receiver is enabled
        document.getElementById('deleteReceiverBtn').disabled = (enabled === '1');

        // Show the modal (optional if data-bs-toggle="modal" does this automatically)
        // new bootstrap.Modal(document.getElementById('editReceiverModal')).show();
    });
});

</script>
<script>
function updateStatuses() {
  fetch('receiver_status.php')
    .then(response => response.json())
    .then(data => {
      data.forEach(receiver => {
        const el = document.getElementById('status-' + receiver.id);
        if (el) {
          el.textContent = receiver.status === 'up' ? 'Online' : 'Offline';
          el.className = receiver.status === 'up' ? 'text-success' : 'text-danger';
        }
      });
    })
    .catch(error => console.error('Status update failed:', error));
}

// First run
updateStatuses();

// Repeat every 5 seconds
setInterval(updateStatuses, 5000);
</script>


<?php include 'footer.php'; ?>
