<?php
require_once '../../config.php';

$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$recordsPerPage = isset($_GET['recordsPerPage']) ? (int)$_GET['recordsPerPage'] : 10; // Default to 10 records per page
$offset = ($page - 1) * $recordsPerPage;

// Fetch total record count
$total_query = "SELECT COUNT(*) AS total FROM evp_dnsbl";
$total_result = $db->select($total_query);
$total_records = $total_result->fetch_assoc()['total'];

// Fetch paginated records
$query = "SELECT id, name, dnszone, type, is_active, last_verified FROM evp_dnsbl ORDER BY id DESC";

if ($recordsPerPage > 0) {
    $query .= " LIMIT $offset, $recordsPerPage";
}

$result = $db->select($query);

$table = '<table class="table table-bordered table-striped">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>DNS Zone</th>
                    <th>Type</th>
                    <th>Active</th>
                    <th>Last Verified</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>';

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        // Format date from database (YYYY-MM-DD) to MM/DD/YYYY
        $date = DateTime::createFromFormat('Y-m-d', $row['last_verified']);
        $formatted_date = $date ? $date->format('m/d/Y') : $row['last_verified'];
        
        $table .= '<tr>
                    <td>' . htmlspecialchars($row['name']) . '</td>
                    <td>' . htmlspecialchars($row['dnszone']) . '</td>
                    <td>' . htmlspecialchars($row['type']) . '</td>
                    <td>' . ($row['is_active'] ? 'Yes' : 'No') . '</td>
                    <td>' . htmlspecialchars($formatted_date) . '</td>
                    <td>
                        <button class="btn btn-primary editDnsblRow" data-id="' . $row['id'] . '">Edit</button>
                        <button class="btn btn-danger deleteDnsblRow" data-id="' . $row['id'] . '">Delete</button>
                    </td>
                  </tr>';
    }
} else {
    $table .= '<tr><td colspan="6" class="text-center">No DNSBL records found.</td></tr>';
}

$table .= '</tbody></table>';

echo json_encode(['table' => $table, 'totalRecords' => $total_records]);
?>
