<?php
/* --- PHP LOGIC AT THE TOP --- */
$output_json = "";
$json_data = null;
$cmd_used = "";
$error_msg = "";

// Valid DNS record types supported by dnspython
$valid_types = [
 'A','A6','AAAA','AFSDB','ANY','APL','AVC','CAA','CDNSKEY','CDS','CERT',
 'CNAME','CSYNC','DHCID','DNAME','DNSKEY','DS','DSYNC','EUI48','EUI64',
 'GPOS','HINFO','HIP','HTTPS','IPSECKEY','ISDN','KEY','KX','L32','L64',
 'LOC','LP','MB','MD','MF','MG','MINFO','MR','MX','NAPTR','NID','NINFO',
 'NS','NSAP','NSEC','NSEC3','NSEC3PARAM','NXT','OPENPGPKEY','PTR','PX',
 'RP','RRSIG','RT','SIG','SMIMEA','SOA','SPF','SRV','SSHFP','SVCB',
 'TLSA','TXT','URI','WKS','X25','ZONEMD'
];

function is_safe_input($str) {
 return !preg_match('/[|&;`$<>()\\\\\'"!#]/', $str);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
 $host_raw = $_POST['host'] ?? '';
 if (!is_safe_input($host_raw)) {
 $error_msg = "Invalid characters in hostname.";
 } else {
 $host = preg_replace('/[^a-zA-Z0-9\.\-_]/', '', $host_raw);
 if (strlen($host) === 0) {
 $error_msg = "Hostname is required.";
 }
 }

 if (empty($error_msg)) {
 if (!empty($_POST['custom_type'])) {
 $type_raw = $_POST['custom_type'] ?? '';
 if (!is_safe_input($type_raw)) {
 $error_msg = "Invalid characters in record type.";
 } else {
 $type = strtoupper(preg_replace('/[^a-zA-Z0-9\-]/', '', $type_raw));
 if (!in_array($type, $valid_types)) {
 $error_msg = "Unsupported or unknown record type: " . htmlspecialchars($type) . ". Must be a valid dnspython type.";
 }
 }
 } else {
 $type = strtoupper(preg_replace('/[^a-zA-Z0-9\-]/', '', $_POST['type'] ?? 'A'));
 if (!in_array($type, $valid_types)) {
 $error_msg = "Invalid record type selected.";
 }
 }
 }

 if (empty($error_msg) && !empty($host) && !empty($type)) {
 $cmd_used = "LITS-DNS-Query.py " . escapeshellarg($host) . " " . escapeshellarg($type);
 $output_json = shell_exec($cmd_used . " 2>/dev/null");

 if (!empty($output_json)) {
 $json_data = json_decode($output_json, true);
 if (json_last_error() !== JSON_ERROR_NONE) {
 $error_msg = "Failed to parse JSON output from query script.";
 $json_data = null;
 }
 if (isset($json_data['error'])) {
 $error_msg = $json_data['error'];
 $json_data = null;
 }
 } else {
 $error_msg = "No output returned from query script. Check that the script is installed and executable.";
 }
 }
}

function majority_answer($results) {
 $tally = [];
 foreach ($results as $group => $sections) {
 foreach ($sections as $section => $data) {
 if (isset($data['answer'])) {
 $key = implode(',', $data['answer']);
 $tally[$key] = ($tally[$key] ?? 0) + 1;
 } elseif (is_array($data)) {
 foreach ($data as $row) {
 if (isset($row['answer'])) {
 $key = implode(',', $row['answer']);
 $tally[$key] = ($tally[$key] ?? 0) + 1;
 }
 }
 }
 }
 }
 if (empty($tally)) return null;
 arsort($tally);
 return array_key_first($tally);
}

function render_answer_row($provider, $location, $ip_used, $answer, $ttl, $majority) {
 $answer_str = implode(', ', $answer);
 $answer_key = implode(',', $answer);
 $ttl_str = $ttl !== null ? $ttl . 's' : '—';

 if ($answer_key !== $majority && $majority !== null) {
 $row_style = 'background-color: #fff3cd; color: #856404;';
 } else {
 $row_style = '';
 }

 echo "<tr style=\"{$row_style}\">";
 echo "<td>" . htmlspecialchars($provider) . "</td>";
 echo "<td>" . htmlspecialchars($location) . "</td>";
 echo "<td style='font-family: monospace;'>" . htmlspecialchars($ip_used) . "</td>";
 echo "<td style='font-family: monospace;'>" . htmlspecialchars($answer_str) . "</td>";
 echo "<td style='text-align: right;'>" . htmlspecialchars($ttl_str) . "</td>";
 echo "</tr>\n";
}

function render_error_row($section, $message = "No response from any provider") {
 echo "<tr style='background-color: #f8d7da; color: #721c24;'>";
 echo "<td colspan='5' style='padding: 4px 8px; font-family: monospace;'>";
 echo htmlspecialchars($section) . ": " . htmlspecialchars($message);
 echo "</td></tr>\n";
}
?>
<html>
    <head>
        <title>Lucas IT Services - Global DNS Propagation</title>
        <link rel="icon" href="../images/favicon.ico" sizes="16x16 24x24 32x32 48x48 64x64" type="image/vnd.microsoft.icon"/>
        <link href="../css/tools.css" rel="stylesheet" type="text/css">
        <meta charset="UTF-8" />
        <meta name="google" content="notranslate" />
        <meta http-equiv="Content-Language" content="en_US" />
        <style>
            table { border-collapse: collapse; width: 100%; table-layout: fixed; }
            col.col-provider { width: 38%; }
            col.col-location { width: 22%; }
            col.col-server   { width: 13%; }
            col.col-answer   { width: 18%; }
            col.col-ttl      { width:  9%; }
            th {
                background-color: rgb(45, 147, 231);
                color: white;
                padding: 5px 8px;
                text-align: left;
                font-family: Arial, Helvetica, sans-serif;
                overflow: hidden;
                white-space: nowrap;
            }
            td {
                font-size: 0.9em;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                padding: 4px 8px;
            }
            tr:nth-child(even) { background-color: rgba(0,0,0,0.04); }
            .group-header {
                font-size: 1.2em;
                font-weight: bold;
                margin: 18px 0 4px 0;
                color: #1a5276;
                border-bottom: 2px solid rgb(45, 147, 231);
                padding-bottom: 2px;
            }
            .section-label {
                font-size: 0.85em;
                font-weight: bold;
                color: #555;
                padding: 6px 0 2px 0;
                font-family: Arial, Helvetica, sans-serif;
            }
            #type-other-box { display: none; margin-top: 6px; }

            /* Shared Button Class */
            .button {
                background-color: rgb(45, 147, 231);
                color: white;
                border: none;
                padding: 0 15px;
                height: 32px;
                border-radius: 3px;
                font-family: Arial, Helvetica, sans-serif;
                font-size: 13.3px;
                cursor: pointer;
                text-decoration: none;
                display: inline-flex;
                align-items: center;
                justify-content: center;
                box-sizing: border-box;
                transition: background-color 0.2s;
            }
            .button:hover {
                background-color: #1a7ab9;
            }
        </style>
        <script>
            function toggleCustomType() {
                var sel = document.getElementById('type-select');
                var box = document.getElementById('type-other-box');
                box.style.display = (sel.value === 'OTHER') ? 'block' : 'none';
            }
        </script>
    </head>
    <body>
        <img src="../images/Logo.png" width="96" height="96"/>
        <p><font size="+4">Global DNS Propagation</font></p>

        <form method="POST">
            <div style="margin-bottom: 10px; display: flex; align-items: center;">
                <input type="text" name="host" class="input-field" placeholder="Hostname (example.com)"
                    value="<?= htmlspecialchars($_POST['host'] ?? '') ?>"
                    style="width: 260px;" autocomplete="off">
                &nbsp;
                <select name="type" id="type-select" onchange="toggleCustomType()" 
                    class="input-field" style="width: auto;">
                     <?php
                        $types = ['A', 'MX', 'TXT', 'CNAME', 'NS', 'SOA', 'OTHER'];
                        $selected_type = strtoupper($_POST['type'] ?? 'A');
                        foreach ($types as $t) {
                            $sel = ($selected_type === $t) ? 'selected' : '';
                            echo "<option value=\"$t\" $sel>$t</option>";
                        }
                    ?>
                </select>
                &nbsp;
                <a href="javascript:void(0)" onclick="this.closest('form').submit();">
                    <div class="button">Run Query</div>
                </a>
                &nbsp;
                <a href="./">
                    <div class="button">Reset</div>
                </a>
            </div>
    
            <div id="type-other-box" style="<?= ($selected_type === 'OTHER') ? 'display:block;' : 'display:none;' ?>">
                <input type="text" name="custom_type" class="input-field" placeholder="Record type (e.g. PTR, SRV, CAA)"
                    value="<?= htmlspecialchars($_POST['custom_type'] ?? '') ?>"
                    style="width: 220px;">
            </div>
        </form>

        <?php if (!empty($error_msg)): ?>
            <div class="redboxed"><?= htmlspecialchars($error_msg) ?></div>
        <?php endif; ?>

        <?php if ($json_data && isset($json_data['results'])): ?>
            <?php
                $majority = majority_answer($json_data['results']);
                $host_display = htmlspecialchars($json_data['host'] ?? '');
                $type_display = htmlspecialchars($json_data['type'] ?? '');
            ?>
            <p><strong>Results for:</strong> <?= $host_display ?> &nbsp; <strong>Type:</strong> <?= $type_display ?></p>

            <?php foreach ($json_data['results'] as $group => $sections): ?>
                <div class="group-header"><?= htmlspecialchars($group) ?></div>
                <div class="boxed">
                    <?php foreach ($sections as $section => $data): ?>
                        <?php
                            $is_list = isset($data[0]) && is_array($data[0]);
                            $is_error = isset($data['error']);
                        ?>

                        <?php if ($group !== $section): ?>
                            <div class="section-label"><?= htmlspecialchars($section) ?></div>
                        <?php endif; ?>

                        <table><colgroup><col class="col-provider"><col class="col-location"><col class="col-server"><col class="col-answer"><col class="col-ttl"></colgroup>
                            <?php if ($is_error): ?>
                                <?php render_error_row($section, $data['error']); ?>
                            <?php elseif ($is_list): ?>
                                <tr>
                                    <th>Provider</th>
                                    <th>Location</th>
                                    <th>Server IP</th>
                                    <th>Answer</th>
                                    <th>TTL</th>
                                </tr>
                                <?php foreach ($data as $row): ?>
                                    <?php render_answer_row($row['provider'], $row['location'], $row['ip_used'], $row['answer'], $row['ttl'], $majority); ?>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <th>Provider</th>
                                    <th>Location</th>
                                    <th>Server IP</th>
                                    <th>Answer</th>
                                    <th>TTL</th>
                                </tr>
                                <?php render_answer_row($data['provider'], $data['location'], $data['ip_used'], $data['answer'], $data['ttl'], $majority); ?>
                            <?php endif; ?>
                        </table>
                        <br>
                    <?php endforeach; ?>
                </div>
            <?php endforeach; ?>

            <p><small>Command: <code><?= htmlspecialchars($cmd_used) ?></code></small></p>
        <?php endif; ?>

        <?php if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$json_data && empty($error_msg)): ?>
            <p><em>No results returned.</em></p>
        <?php endif; ?>

        <script>
            toggleCustomType();
    </script>
        
        <p><a href="index.phps">View Source</a> | <a href="../">Back to Tools</a></p>
    </body>
</html>