<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/inc/auth.php");
require_once($_SERVER['DOCUMENT_ROOT'] . "/inc/languages/" . HTML_LANG . ".php");
require_once($_SERVER['DOCUMENT_ROOT'] . "/inc/idfilter.php");

$sSQL = "SELECT * FROM subnets WHERE id= ?";
$subnet_info = get_record_sql($db_link, $sSQL, [ $id ]);

if (getPOST("s_save") !== null) {
    $new = [];

    // === INPUT CLEANING =====================================================================================
    $new['subnet']              = trim(getPOST("s_subnet", null, $subnet_info['subnet']));

    // === CIDR / RANGE PROCESSING ============================================================================
    $range = cidrToRange($new['subnet']);
    $first_ip = $range[0];
    $last_ip  = $range[1];
    $cidr     = $range[2] ?? null;

    // Формируем корректный CIDR
    if ($cidr !== null && $cidr < 32) {
            $new['subnet'] = "$first_ip/$cidr";
        } else {
            $range = cidrToRange($first_ip.'/24');
            $first_ip = $range[0];
            $last_ip  = $range[1];
            $cidr     = $range[2] ?? null;
            if ($cidr !== null && $cidr < 32) {
                $new['subnet'] = "$first_ip/$cidr";
                } else {
                //abort
                header("Location: " . $_SERVER["REQUEST_URI"]);
                exit;
                }
        }

    $new['vlan_tag']            = normalize_vlan(getPOST("s_vlan", null, 1));
    $new['office']              = intval_or_zero(getPOST("s_office", null, 0));
    $new['hotspot']             = intval_or_zero(getPOST("s_hotspot", null, 0));
    $new['vpn']                 = intval_or_zero(getPOST("s_vpn", null, 0));
    $new['free']                = intval_or_zero(getPOST("s_free", null, 0));
    $new['dhcp']                = intval_or_zero(getPOST("s_dhcp", null, 0));
    $new['dhcp_lease_time']     = intval_or_zero(getPOST("s_lease_time", null, 0));
    $new['static']              = intval_or_zero(getPOST("s_static", null, 0));
    $new['discovery']           = intval_or_zero(getPOST("s_discovery", null, 0));
    $new['notify']              = intval_or_zero(getPOST("s_notify", null, 0));
    $new['dhcp_update_hostname']= intval_or_zero(getPOST("s_dhcp_update", null, 0));
    $new['description']         = trim(getPOST("s_description", null, ''));

    $new['ip_int_start']        = ip2long($first_ip);
    $new['ip_int_stop']         = ip2long($last_ip);

    // === GATEWAY ============================================================================================
    $gateway_fallback = ip2long($range[5]);
    $new['gateway'] = get_dhcp_gateway(getPOST("s_gateway", null, ''), $gateway_fallback);

    // === GATEWAY VALIDATION =================================================================================
    if (!$new['gateway'] || $new['gateway'] <= $new['ip_int_start'] || $new['gateway'] >= $new['ip_int_stop']) {
        $new['gateway'] = $gateway_fallback;
    }

    // === DHCP RANGE VALIDATION =============================================================================
    $dhcp_start = ip2long(trim(getPOST("s_dhcp_start", null, $range[3])));
    $dhcp_stop  = ip2long(trim(getPOST("s_dhcp_stop", null, $range[4])));

    if (!validate_dhcp_range($dhcp_start, $dhcp_stop, $new['ip_int_start'], $new['ip_int_stop'])) {
        // fallback пул
        $dhcp_start = ip2long($range[3]);
        $dhcp_stop  = ip2long($range[4]);
    }

    $new['dhcp_start'] = $dhcp_start;
    $new['dhcp_stop']  = $dhcp_stop;

    // === MODE DEPENDENCY RULES =============================================================================

    if ($dhcp_start === $dhcp_stop ) {
        $new['dhcp'] = 0;
        }

    if ($new['hotspot']) {
        $new['dhcp_update_hostname'] = 0;
        $new['discovery'] = 0;
        $new['vpn'] = 0;
    }

    if ($new['vpn']) {
        $new['discovery'] = 0;
        $new['dhcp'] = 0;
    }

    if ($new['office']) {
        $new['free'] = 0;
    }

    if (!$new['office']) {
        $new['discovery'] = 0;
        $new['dhcp'] = 0;
        $new['static'] = 0;
        $new['dhcp_update_hostname'] = 0;
        $new['gateway'] = 0;
        $new['dhcp_start'] = 0;
        $new['dhcp_stop'] = 0;
    }

    update_record($db_link, "subnets", "id = ?", $new, [$id]);

    header("Location: /admin/customers/index-subnets.php");
    exit;
}

unset($_POST);
require_once($_SERVER['DOCUMENT_ROOT'] . "/inc/header.php");
print_control_submenu($page_url);

?>

<div id="cont">
    <?php if (!empty($_SESSION[$page_url]['msg'])): ?>
        <div id="msg"><?php echo $_SESSION[$page_url]['msg']; ?></div>
        <?php unset($_SESSION[$page_url]['msg']); ?>
    <?php endif; ?>
    
    <br>
    
    <form name="def" action="editsubnet.php?id=<?php echo $id; ?>" method="post">
        <input type="hidden" name="id" value="<?php echo $id; ?>">
        
        <table class="data">
            <tr>
                <td></td>
                <td><b><?php echo WEB_network_subnet; ?></b></td>
                <td class="data">
                    <input type="text" name="s_subnet" value="<?php echo $subnet_info['subnet']; ?>" size="18" class='full-width'>
                </td>
                <td>
                    <button name="s_save" value="save"><?php echo WEB_btn_save; ?></button>
                </td>
            </tr>
            
            <tr>
                <td></td>
                <td><b><?php echo WEB_cell_description; ?></b></td>
                <td colspan="2" class="data">
                    <input type="text" name="s_description" value="<?php echo $subnet_info['description']; ?>" class='full-width'>
                </td>
            </tr>
            
            <tr>
                <td></td>
                <td><b><?php echo WEB_network_vlan; ?></b></td>
                <td colspan="2" class="data">
                    <input type="text" name="s_vlan" value="<?php echo $subnet_info['vlan_tag']; ?>" pattern="^(409[0-6]|(40[0-8]|[1-3]\d\d|[1-9]\d|[1-9])\d|[1-9])$">
                </td>
            </tr>
            
            <tr>
                <td></td>
                <td><b><?php echo WEB_network_gateway; ?></b></td>
                <?php
                $cell_disabled = '';
                $cl = 'data';
                if ($subnet_info['office'] and !$subnet_info['vpn']) {
                    $default_range = cidrToRange($subnet_info['subnet']);
                    if (!isset($subnet_info['dhcp_start']) or !($subnet_info['dhcp_start'] > 0)) {
                        $subnet_info['dhcp_start'] = ip2long($default_range[3]);
                    }
                    if (!isset($subnet_info['dhcp_stop']) or !($subnet_info['dhcp_stop'] > 0)) {
                        $subnet_info['dhcp_stop'] = ip2long($default_range[4]);
                    }
                } else {
                    $cell_disabled = 'readonly';
                    $cl = 'down';
                }
                ?>
                <td colspan="2" class="<?php echo $cl; ?>">
                    <input type="text" name="s_gateway" value="<?php echo long2ip($subnet_info['gateway']); ?>" size="15" <?php echo $cell_disabled; ?>>
                </td>
            </tr>
            
            <tr>
                <td></td>
                <td><b><?php echo WEB_network_use_dhcp; ?></b></td>
                <td colspan="2" class="<?php echo $subnet_info['dhcp'] ? 'up' : 'data'; ?>">
                    <?php print_qa_select("s_dhcp", $subnet_info['dhcp']); ?>
                </td>
            </tr>
            
            <tr>
                <td></td>
                <td><b><?php echo WEB_network_static; ?></b></td>
                <td colspan="2" class="<?php echo $subnet_info['static'] ? 'up' : 'data'; ?>">
                    <?php print_qa_select("s_static", $subnet_info['static']); ?>
                </td>
            </tr>
            
            <tr>
                <td></td>
                <td><b><?php echo WEB_network_dhcp_first; ?></b></td>
                <td colspan="2" class="data">
                    <input type="text" name="s_dhcp_start" value="<?php echo long2ip($subnet_info['dhcp_start']); ?>" size="15" <?php echo $cell_disabled; ?>>
                </td>
            </tr>
            
            <tr>
                <td></td>
                <td><b><?php echo WEB_network_dhcp_last; ?></b></td>
                <td colspan="2" class="data">
                    <input type="text" name="s_dhcp_stop" value="<?php echo long2ip($subnet_info['dhcp_stop']); ?>" size="15" <?php echo $cell_disabled; ?>>
                </td>
            </tr>
            
            <tr>
                <td></td>
                <td><b><?php echo WEB_network_dhcp_leasetime; ?></b></td>
                <td colspan="2" class="data">
                    <input type="text" name="s_lease_time" value="<?php echo $subnet_info['dhcp_lease_time']; ?>" size="3" <?php echo $cell_disabled; ?>>
                </td>
            </tr>
            
            <tr>
                <td></td>
                <td><b><?php echo WEB_network_office_subnet; ?></b></td>
                <?php
                $row_cl = $subnet_info['office'] ? 'data' : 'down';
                $cl = $subnet_info['office'] ? 'up' : 'data';
                ?>
                <td colspan="2" class="<?php echo $cl; ?>">
                    <?php print_qa_select("s_office", $subnet_info['office']); ?>
                </td>
            </tr>
            
            <tr>
                <td></td>
                <td><b><?php echo WEB_network_hotspot; ?></b></td>
                <?php
                $cl = ($row_cl === 'data' and $subnet_info['hotspot']) ? 'up' : $row_cl;
                ?>
                <td colspan="2" class="<?php echo $cl; ?>">
                    <?php print_qa_select_ext("s_hotspot", $subnet_info['hotspot'], !$subnet_info['office']); ?>
                </td>
            </tr>
            
            <tr>
                <td></td>
                <td><b><?php echo WEB_network_vpn; ?></b></td>
                <?php
                $cl = ($row_cl === 'data' and $subnet_info['vpn']) ? 'up' : $row_cl;
                ?>
                <td colspan="2" class="<?php echo $cl; ?>">
                    <?php print_qa_select_ext("s_vpn", $subnet_info['vpn'], !$subnet_info['office']); ?>
                </td>
            </tr>
            
            <tr>
                <td></td>
                <td><b><?php echo WEB_network_free; ?></b></td>
                <td colspan="2" class="<?php echo $subnet_info['free'] ? 'up' : $row_cl; ?>">
                    <?php print_qa_select("s_free", $subnet_info['free']); ?>
                </td>
            </tr>
            
            <tr>
                <td></td>
                <td><b><?php echo WEB_network_dyndns; ?></b></td>
                <?php
                $cl = ($row_cl === 'data' and $subnet_info['dhcp_update_hostname']) ? 'up' : $row_cl;
                ?>
                <td colspan="2" class="<?php echo $cl; ?>">
                    <?php print_qa_select_ext("s_dhcp_update", $subnet_info['dhcp_update_hostname'], !$subnet_info['office']); ?>
                </td>
            </tr>
            
            <tr>
                <td></td>
                <td><b><?php echo WEB_network_discovery; ?></b></td>
                <?php
                $cl = ($row_cl === 'data' and $subnet_info['discovery']) ? 'up' : $row_cl;
                ?>
                <td colspan="2" class="<?php echo $cl; ?>">
                    <?php print_qa_select_ext("s_discovery", $subnet_info['discovery'], !$subnet_info['office']); ?>
                </td>
            </tr>

            <tr>
                <td></td>
                <td><b><?php echo WEB_network_notify; ?></b></td>
                <td colspan="2" class="data">
                    <?php print renderNotifyCombobox("s_notify", $subnet_info['notify']); ?>
                </td>
            </tr>

        </table>
        
        <?php if (isset($msg_error) && $msg_error): ?>
            <div id="msg"><b><?php echo $msg_error; ?></b></div>
        <?php endif; ?>
    </form>

<?php require_once($_SERVER['DOCUMENT_ROOT'] . "/inc/footer.php"); ?>
