<?php
$title = 'Blacklist Monitor';
include '../templates/backend/members/header.php';
Session::Check_auth();
if($blacklist_check == 'false'){
	header("Location:$a_url");
	exit();
}
$user_id = $_SESSION['id'];
$ip = $_SERVER['SERVER_ADDR'];
?>

<!-- Page Heading -->
<div class="page-header">
 <div class="pull-right">
    <button class="d-sm-inline-block btn btn-sm btn-primary shadow-sm" id="manageDnsbl">Manage DNSBL's</button>
</div>
<div class="row">
	<div class="col-md-6 col-sm-12">
		<div class="title">
			<h4><?php _e($title);?></h4>
		</div>
		<nav aria-label="breadcrumb" role="navigation">
			<ol class="breadcrumb">
				<li class="breadcrumb-item"><a href="index.php"><?php _e('Dashboard');?></a></li>
				<li class="breadcrumb-item active" aria-current="page"><?php _e($title);?></li>
			</ol>
		</nav>
	</div>
</div>
</div>

<div class="pd-20 card-box mb-30">

		<div class="bl-valid">
				<form id="blacklistForm" action="javascript:void(0);">
					<div class="bl-vf-control">
						<label for="bl-validator">IP or Domain Name</label>
						<input type="text" class="form-control" aria-label="IP or Domain Name" id="bl-validator" name="bl-validator" value="<?php echo $ip;?>">
					</div>
					<button class="btn btn-primary bl-vf-btn" id="formSubmit">Submit</button>
				</form>
		</div>

		<!-- Modal for DNSBL Management -->
		<div class="modal fade" id="dnsblModal" tabindex="-1" aria-labelledby="dnsblModalLabel" aria-hidden="true">
			<div class="modal-dialog modal-xl">
				<div class="modal-content">
					<div class="modal-header">
						<h5 class="modal-title" id="dnsblModalLabel">Manage DNSBL Records</h5>
						<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
					</div>
					<div class="modal-body">
							<div class="d-flex justify-content-between align-items-center mb-3">
								<button class="btn btn-success" id="addDnsblRecord">Add New Record</button>
								<div class="d-flex align-items-center">
									<select id="recordsPerPage" class="form-select form-select-sm me-2">
										<option value="10" selected>10</option>
										<option value="25">25</option>
										<option value="50">50</option>
										<option value="0">All</option>
									</select>
									<nav>
										<ul class="pagination" id="dnsblPagination">
											<!-- Pagination links will be dynamically added here -->
										</ul>
									</nav>
								</div>
							</div>
							<div id="dnsblTableContainer" class="table-responsive">
								<!-- AJAX-loaded table will be inserted here -->
							</div>
					</div>
				</div>
			</div>
		</div>

		<div id="results-count" style="display:none">
			<h3 class="h5 text-center mb-4" id="results-table"></h3>
		</div>
		<div class="blt" style="display:none">
			<div class="bl-ti">
				<div class="bl-tfs">
					<h3 class="h4">Filter</h3>
					<ul>
						<li>
							<div class="bl-tf">
								<input type="checkbox" name="field-incomplete" id="field-incomplete">
								<label for="field-incomplete">
									<span class="bl-tf-icon">
										<svg width="10" height="10" viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg">
											<g fill="none" fill-rule="evenodd">
												<path d="M1.377 5.018c.719.548 1.438 1.067 2.156 1.587C5.06 4.614 6.617 2.653 8.143.69c.63.433 1.228.865 1.857 1.327A1746.043 1746.043 0 003.982 9.69C2.665 8.711 1.317 7.758 0 6.777c.449-.577.898-1.154 1.377-1.76v.001z" fill="#FFF"></path>
											</g>
										</svg>
									</span>
									<div class="bs"><i class="status-incidator is-incomplete"></i><span>incomplete</span></div>
									&nbsp;<p id="incomplete-count" class="count-class">(0)</p> 
								</label>
							</div>
						</li>
						<li>
							<div class="bl-tf">
								<input type="checkbox" name="is-not-listed" id="field-notlisted">
								<label for="field-notlisted">
									<span class="bl-tf-icon">
										<svg width="10" height="10" viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg">
											<g fill="none" fill-rule="evenodd">
												<path d="M1.377 5.018c.719.548 1.438 1.067 2.156 1.587C5.06 4.614 6.617 2.653 8.143.69c.63.433 1.228.865 1.857 1.327A1746.043 1746.043 0 003.982 9.69C2.665 8.711 1.317 7.758 0 6.777c.449-.577.898-1.154 1.377-1.76v.001z" fill="#FFF"></path>
											</g>
										</svg>
									</span>
									<div class="bs"><i class="status-incidator is-not-listed"></i><span>Not Listed</span></div>
									&nbsp; <p id="is-not-listed" class="count-class">(0)</p> 
								</label>
							</div>
						</li>
						<li>
							<div class="bl-tf">
								<input type="checkbox" name="is-listed" id="field-listed">
								<label for="field-listed">
									<span class="bl-tf-icon">
										<svg width="10" height="10" viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg">
											<g fill="none" fill-rule="evenodd">
												<path d="M1.377 5.018c.719.548 1.438 1.067 2.156 1.587C5.06 4.614 6.617 2.653 8.143.69c.63.433 1.228.865 1.857 1.327A1746.043 1746.043 0 003.982 9.69C2.665 8.711 1.317 7.758 0 6.777c.449-.577.898-1.154 1.377-1.76v.001z" fill="#FFF"></path>
											</g>
										</svg>
									</span>
									<div class="bs">
									<i class="status-incidator is-listed"></i><span>Listed</span>
									</div>
									&nbsp; <p id="is-listed" class="count-class">(0)</p>
								</label>
							</div>
						</li>
						<li>
							<div class="bl-tf">
								<input type="checkbox" name="field-other" id="field-other">
								<label for="field-other">
									<span class="bl-tf-icon">
										<svg width="10" height="10" viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg">
											<g fill="none" fill-rule="evenodd">
												<path d="M1.377 5.018c.719.548 1.438 1.067 2.156 1.587C5.06 4.614 6.617 2.653 8.143.69c.63.433 1.228.865 1.857 1.327A1746.043 1746.043 0 003.982 9.69C2.665 8.711 1.317 7.758 0 6.777c.449-.577.898-1.154 1.377-1.76v.001z" fill="#FFF"></path>
											</g>
										</svg>
									</span>
									<div class="bs">
										<i class="status-incidator is-other">
											<svg width="12" height="12" viewBox="0 0 12 12" xmlns="http://www.w3.org/2000/svg">
												<g fill-rule="nonzero" fill="none">
													<path d="M5.916 5.982h6c0 3.198-2.706 5.838-6 5.838a6.137 6.137 0 01-2.94-.75l2.94-5.088z" fill="#0e76c9"></path>
													<path d="M6 5.898l-3 5.196C.234 9.492-.696 5.832.948 2.982A6.17 6.17 0 013.066.81L6 5.898z" fill="#03a9f4"></path>
													<path d="M6.048 5.982l-3-5.196C5.82-.816 9.456.216 11.1 3.06c.516.888.798 1.896.822 2.916H6.048v.006z" fill="#1a8dea"></path>
												</g>
											</svg>
										</i>
										<span>other</span>
									</div>
									&nbsp; <p id="other-count" class="count-class">(0)</p>
								</label>
							</div>
						</li>
						<li>
							<div class="bl-tf">
								<input type="checkbox" name="is-whitelisted" id="field-whitelisted">
								<label for="field-whitelisted">
									<span class="bl-tf-icon">
										<svg width="10" height="10" viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg">
											<g fill="none" fill-rule="evenodd">
												<path d="M1.377 5.018c.719.548 1.438 1.067 2.156 1.587C5.06 4.614 6.617 2.653 8.143.69c.63.433 1.228.865 1.857 1.327A1746.043 1746.043 0 003.982 9.69C2.665 8.711 1.317 7.758 0 6.777c.449-.577.898-1.154 1.377-1.76v.001z" fill="#FFF"></path>
											</g>
										</svg>
									</span>
									<div class="bs"><i class="status-incidator"></i><span>whitelisted</span></div>
									&nbsp; <p id="is-whitelisted" class="count-class">(0)</p>
								</label>
							</div>
						</li>
					</ul>
				</div>
				<div class="bl-t_c">
					<div class="bl-th">
						<div class="bl-tr">
							<div class="bl-tc cs1"><strong>Name</strong></div>
							<div class="bl-tc cs2"><strong>DNS</strong></div>
							<div class="bl-tc cs3"><strong>URL</strong></div>
							<div class="bl-tc cs4"><strong>Status</strong></div>
						</div>
					</div>
					<div class="bl-tb" id="bl-tb">
					</div>
				</div>
			</div>
		</div>
</div>

<script>
(function() {
    'use strict';

    let host = '', totalCount = 0, count = 0;
    let listedCount = 0, notListedCount = 0, otherCount = 0, whitelistedCount = 0, incompleteCount = 0;

    $(document).on('click', '#formSubmit', function() {
        resetResults();
        host = $('#bl-validator').val().trim(); // Trim whitespace from input
        if (host !== '') {
            $.post('../lib/bl_monitor/prep_dns.php', { host: host }, function(data) {
                data = JSON.parse(data);
                if (data.success) {
                    if (data.result.length > 0) {
                        totalCount = data.result.length;
                        processRows(data.result);
                    } else {
                        $("#results-table").html('No DNSBL zones found for the given host.');
                    }
                } else {
                    alert(data.message || 'An error occurred while processing.');
                }
            });
        } else {
            alert('Please enter a valid IP or domain name.');
        }
    });

    function resetResults() {
        count = 0;
        listedCount = 0;
        notListedCount = 0;
        otherCount = 0;
        whitelistedCount = 0;
        incompleteCount = 0;
        $("#results-table").html('Completed 0 of 0');
        $("#bl-tb").html('');
        $("#results-count").hide();
        $(".blt").hide();
        $("#is-listed").html('(0)');
        $("#is-not-listed").html('(0)');
        $("#other-count").html('(0)');
        $("#is-whitelisted").html('(0)');
        $("#incomplete-count").html('(0)');
    }

    function processRows(rows) {
        rows.forEach(function(row) {
            $.post('../lib/bl_monitor/prep_dns.php', { host: host, dnsZone: row.dnszone }, function(response) {
                response = JSON.parse(response);
                if (response.success) {
                    appendResult(response.result);
                }
            });
        });
    }

    function appendResult(result) {
        count++;
        $("#results-table").html('Completed ' + count + ' of ' + totalCount);

        const iconClass = result.listed === "Listed" ? "is-listed" :
                          result.listed === "Not Listed" ? "is-not-listed" :
                          result.listed === "Whitelisted" ? "is-whitelisted" : "is-other";
        const rData = result.a_r ? "show_rdata" : '';
        const dns_a = result.a_r || '';
        const dns_txt = result.txt_r || '';

        // Update counts based on status
        if (result.listed === "Listed") {
            listedCount++;
            $("#is-listed").html('(' + listedCount + ')');
        } else if (result.listed === "Not Listed") {
            notListedCount++;
            $("#is-not-listed").html('(' + notListedCount + ')');
        } else if (result.listed === "Whitelisted") {
            whitelistedCount++;
            $("#is-whitelisted").html('(' + whitelistedCount + ')');
        } else {
            otherCount++;
            $("#other-count").html('(' + otherCount + ')');
        }

        // Increment incomplete count only if no data is available and not already categorized
        if (!result.a_r && !result.txt_r && result.listed === "Incomplete") {
            incompleteCount++;
            $("#incomplete-count").html('(' + incompleteCount + ')');
        }

        let html = `<div class="bl-tr tb ${iconClass}">
                        <div class="bl-tc cs1 rbl_name"><p>${result.name}</p></div>
                        <div class="bl-tc cs2 rbl_dns"><p>${result.host}</p></div>
                        <div class="bl-tc cs3 rbl_url"><a href="${result.url}" target="_blank"><p>${result.url}</p></a></div>
                        <div class="bl-tc cs4">
                            <div class="bs">
                                <i class="status-incidator ${iconClass}"></i>
                                <span class="${rData}" data-type-a="${dns_a}" data-type-txt="${dns_txt}">${result.listed}</span>
                            </div>
                        </div>
                    </div>`;

        // Append rows with "Listed" status to the top, others to the bottom
        if (result.listed === "Listed") {
            $("#bl-tb").prepend(html);
        } else {
            $("#bl-tb").append(html);
        }

        $("#results-count").show();
        $(".blt").show();

        // Attach click event for show_rdata
        $(document).on('click', '.show_rdata', function() {
            const dns_a = $(this).data('type-a');
            const dns_txt = $(this).data('type-txt');
            Swal.fire({
                html: `<div class="bl_res">
                            <b>Response Code:</b><br>
                            <div class="bl_rdata">${dns_a || 'N/A'}</div>
                            <b>Response Text:</b><br>
                            <div class="bl_rdata">${dns_txt || 'N/A'}</div>
                       </div>`,
                showCloseButton: true,
                showConfirmButton: false,
                focusConfirm: false,
                heightAuto: false
            });
        });
    }

    let currentPage = 1;
    let recordsPerPage = 10; // Default to 10 records per page

    // Open DNSBL modal and load data
    $(document).on('click', '#manageDnsbl', function() {
        $('#dnsblModal').modal('show');
        loadDnsblTable(currentPage, recordsPerPage);
    });

    // Ensure modal close button works
    $(document).on('click', '.btn-close', function() {
        $('#dnsblModal').modal('hide');
    });

    // Load DNSBL table via AJAX with pagination
    function loadDnsblTable(page, recordsPerPage) {
        $.ajax({
            url: '../lib/bl_monitor/load_dnsbl.php',
            method: 'GET',
            data: { page, recordsPerPage },
            success: function(response) {
                try {
                    const data = JSON.parse(response);
                    $('#dnsblTableContainer').html(data.table);
                    updatePagination(data.totalRecords, page, recordsPerPage);

                    // Edit button functionality
                    $(document).on('click', '.editDnsblRow', function() {
                        const row = $(this).closest('tr');
                        const id = $(this).data('id');

                        // Store original values for potential cancellation
                        const originalValues = {
                            name: row.find('td:eq(0)').text(),
                            dnszone: row.find('td:eq(1)').text(),
                            type: row.find('td:eq(2)').text(),
                            is_active: row.find('td:eq(3)').text(),
                            last_verified: row.find('td:eq(4)').text()
                        };

                        // Function to format date as MM/DD/YYYY
                        function formatDate(dateString) {
                            const date = new Date(dateString);
                            const month = String(date.getMonth() + 1).padStart(2, '0');
                            const day = String(date.getDate()).padStart(2, '0');
                            const year = date.getFullYear();
                            return `${month}/${day}/${year}`;
                        }

                        // Transform cells into editable inputs
                        row.find('td:eq(0)').html('<input type="text" name="name" value="' + originalValues.name + '">');
                        row.find('td:eq(1)').html('<input type="text" name="dnszone" value="' + originalValues.dnszone + '">');
                        row.find('td:eq(2)').html('<select name="type"><option value="IP">IP</option><option value="Host">Host</option></select>');
                        row.find('td:eq(2) select').val(originalValues.type);
                        row.find('td:eq(3)').html('<input type="checkbox" name="is_active">');
                        row.find('td:eq(3) input').prop('checked', originalValues.is_active === 'Yes');

                        // Format the date before setting the value
                        const formattedLastVerified = formatDate(originalValues.last_verified);
                        row.find('td:eq(4)').html('<input type="text" class="last-verified-picker" name="last_verified" value="' + formattedLastVerified + '">');

                        // Initialize datepicker
                        row.find('.last-verified-picker').datepicker({
                            format: 'mm/dd/yyyy',
                            autoclose: true,
                            todayHighlight: true,
                            language: 'en'
                        }).on('changeDate', function(e) {
                            const selectedDate = $(this).datepicker('getDate');
                            const month = String(selectedDate.getMonth() + 1).padStart(2, '0');
                            const day = String(selectedDate.getDate()).padStart(2, '0');
                            const year = selectedDate.getFullYear();
                            const formattedDate = `${month}/${day}/${year}`;
                            $(this).val(formattedDate);
                        });

                        // Replace Edit button with Save and Cancel buttons
                        row.find('td:eq(5)').html(
                            '<button class="btn btn-success saveInlineEdit" data-id="' + id + '">Save</button>' +
                            '<button class="btn btn-secondary cancelInlineEdit" data-id="' + id + '">Cancel</button>'
                        );

                        // Cancel inline editing
                        $(document).on('click', '.cancelInlineEdit', function() {
                            row.find('td:eq(0)').text(originalValues.name);
                            row.find('td:eq(1)').text(originalValues.dnszone);
                            row.find('td:eq(2)').text(originalValues.type);
                            row.find('td:eq(3)').text(originalValues.is_active);
                            row.find('td:eq(4)').text(originalValues.last_verified);

                            // Restore Edit and Delete buttons
                            row.find('td:eq(5)').html(
                                '<button class="btn btn-primary editDnsblRow" data-id="' + id + '">Edit</button>' +
                                '<button class="btn btn-danger deleteDnsblRow" data-id="' + id + '">Delete</button>'
                            );
                        });
                    });

                    // Save inline edited DNSBL record
                    $(document).on('click', '.saveInlineEdit', function() {
                        const row = $(this).closest('tr');
                        const id = $(this).data('id');
                        const name = row.find('input[name="name"]').val();
                        const dnszone = row.find('input[name="dnszone"]').val();
                        const type = row.find('select[name="type"]').val();
                        const is_active = row.find('input[name="is_active"]').is(':checked') ? 1 : 0;
                        const last_verified = row.find('input[name="last_verified"]').val();

                        $.ajax({
                            url: '../lib/bl_monitor/edit_dnsbl.php',
                            method: 'POST',
                            data: { id, name, dnszone, type, is_active, last_verified },
                            success: function(response) {
                                const res = JSON.parse(response);
                                alert(res.message);
                                if (res.success) {
                                    loadDnsblTable(currentPage, recordsPerPage);
                                }
                                $(document).off('click', '.saveInlineEdit'); // Unbind the click event
                            },
                            error: function() {
                                alert('Failed to save changes.');
                            }
                        });
                    });
                } catch (error) {
                    console.error('Invalid JSON response:', response);
                    alert('An error occurred while processing the data. Please try again.');
                }
            },
            error: function(xhr, status, error) {
                console.error('AJAX Error:', status, error);
                alert('Failed to load DNSBL data.');
            }
        });
    }

    // Update pagination links
    function updatePagination(totalRecords, currentPage, recordsPerPage) {
        const totalPages = recordsPerPage === 0 ? 1 : Math.ceil(totalRecords / recordsPerPage);
        let paginationHtml = '';

        for (let i = 1; i <= totalPages; i++) {
            paginationHtml += `<li class="page-item ${i === currentPage ? 'active' : ''}">
                                   <a class="page-link" href="javascript:void(0);" data-page="${i}">${i}</a>
                               </li>`;
        }

        $('#dnsblPagination').html(paginationHtml);
    }

    // Handle pagination click
    $(document).on('click', '#dnsblPagination .page-link', function() {
        const page = $(this).data('page');
        currentPage = page;
        loadDnsblTable(page, recordsPerPage);
    });

    // Handle records per page change
    $('#recordsPerPage').on('change', function() {
        recordsPerPage = parseInt($(this).val());
        currentPage = 1; // Reset to the first page
        loadDnsblTable(currentPage, recordsPerPage);
    });

    // Add new DNSBL record row at the top of the table
    $('#addDnsblRecord').on('click', function() {
        const newRow = `
            <tr class="new-record-row">
                <td><input type="text" class="form-control" placeholder="Name"></td>
                <td><input type="text" class="form-control" placeholder="DNS Zone"></td>
                <td>
                    <select class="form-control">
                        <option value="IP">IP</option>
                        <option value="Host">Host</option>
                    </select>
                </td>
                <td><input type="checkbox" class="form-check-input"></td>
                <td><input type="text" class="form-control last-verified-picker" placeholder="MM/DD/YYYY"></td>
                <td><button class="btn btn-success saveDnsblRow">Save</button></td>
            </tr>`;
        if ($('#dnsblTableContainer table tbody').length > 0) {
            $('#dnsblTableContainer table tbody').prepend(newRow);
            $('.last-verified-picker').datepicker({
                format: 'mm/dd/yyyy',
                autoclose: true,
                todayHighlight: true,
                language: 'en'
            }).on('changeDate', function(e) {
                const selectedDate = $(this).datepicker('getDate');
                const month = String(selectedDate.getMonth() + 1).padStart(2, '0');
                const day = String(selectedDate.getDate()).padStart(2, '0');
                const year = selectedDate.getFullYear();
                const formattedDate = `${month}/${day}/${year}`;
                $(this).val(formattedDate);
            });
        } else {
            alert('Table not loaded yet. Please wait for the table to load.');
        }
    });

    // Save or update DNSBL record
    $(document).on('click', '.saveDnsblRow', function() {
        const row = $(this).closest('tr');
        const name = row.find('input[placeholder="Name"]').val();
        const dnszone = row.find('input[placeholder="DNS Zone"]').val();
        const type = row.find('select').val();
        const is_active = row.find('input[type="checkbox"]').is(':checked') ? 1 : 0;
        const last_verified = row.find('.last-verified-picker').val();

        // Validate the last_verified date format
        const dateRegex = /^\d{2}\/\d{2}\/\d{4}$/;
        if (!last_verified.match(dateRegex)) {
            alert('Invalid date format. Use MM/DD/YYYY.');
            return;
        }

        $.ajax({
            url: '../lib/bl_monitor/save_dnsbl.php',
            method: 'POST',
            data: { name, dnszone, type, is_active, last_verified },
            success: function(response) {
                try {
                    const res = JSON.parse(response); // Ensure response is valid JSON
                    alert(res.message);
                    if (res.success) {
                        loadDnsblTable(currentPage, recordsPerPage);
                    }
                } catch (error) {
                    console.error('Invalid JSON response:', response);
                    alert('An error occurred while saving the data. Please try again.');
                }
            },
            error: function(xhr, status, error) {
                console.error('AJAX Error:', status, error);
                alert('Failed to save DNSBL record.');
            }
        });
    });

    // Delete DNSBL record
    $(document).on('click', '.deleteDnsblRow', function() {
        const id = $(this).data('id');
        if (confirm('Are you sure you want to delete this record?')) {
            $.ajax({
                url: '../lib/bl_monitor/delete_dnsbl.php',
                method: 'POST',
                data: { id },
                success: function(response) {
                    const res = JSON.parse(response);
                    alert(res.message);
                    if (res.success) {
                        loadDnsblTable(currentPage, recordsPerPage);
                    }
                },
                error: function() {
                    alert('Failed to delete DNSBL record.');
                }
            });
        }
    });
});
</script>

<?php
 include '../templates/backend/members/footer.php'; 
?>