<?php
defined(page_security_key) or exit;

//=============================
// Configuration file
//=============================
$domain = getDomainName($_SERVER['SERVER_NAME']);
$file = ((file_exists(dirname(__FILE__).'/custom/'.$domain.'/settings/'.$domain.'_config.php')) ? dirname(__FILE__).'/custom/'.$domain.'/settings/'.$domain.'_config.php' : dirname(__FILE__).'/settings/config.php');

//Check if allowed
if (isAllowed('settings',$_SESSION['profile'],$_SESSION['permission'],'R') === 0){
    header('location: index.php');
    exit;
}
// Open the configuration file for reading
$contents = file_get_contents($file);
//empty view
$view = '';

// Format key function
function format_key($key) {
    $key = str_replace(
        ['_', 'url', 'db ', ' pass', ' user', 'ipn', 'paypal'], 
        [' ', 'URL', 'Database ', ' Password', ' Username', 'IPN', 'PayPal'], 
        strtolower($key)
    );
    return ucwords($key);
}
// Format HTML output function
function format_var_html($key, $value) {
    $html = '';
    $type = 'text';
    $value = htmlspecialchars(trim($value, '\''), ENT_QUOTES);
    $type = str_contains($key, 'pw') !== false ? 'password' : $type;
    $type = in_array(strtolower($value), ['true', 'false']) ? 'checkbox' : $type;
    $checked = strtolower($value) == 'true' ? ' checked' : '';
    
    if ($key == '4'){
        $html .= '<label for="' . $key . '">' . format_key($key) . ' - Admin+</label>';
    }
    elseif ($key == '3'){
        $html .= '<label for="' . $key . '">' . format_key($key) . ' - Admin</label>';
    }
    elseif ($key == '2'){
        $html .= '<label for="' . $key . '">' . format_key($key) . ' - Super User</label>';
    }
    elseif ($key == '1'){
        $html .= '<label for="' . $key . '">' . format_key($key) . ' - Create & Update</label>';
    }
    elseif ($key == '0'){
        $html .= '<label for="' . $key . '">' . format_key($key) . ' - Readonly</label>';
    }
    else {
    $html .= '<label for="' . $key . '">' . format_key($key) . '</label>';
    }
    if ($type == 'checkbox') {
        $html .= '<input type="hidden" name="' . $key . '" value="false">';
    }
    $html .= '<input type="' . $type . '" name="' . $key . '" id="' . $key . '" value="' . $value . '" placeholder="' . format_key($key) . '"' . $checked . '>';
    return $html;
}
// Format tabs
function format_tabs($contents) {
    $rows = explode("\n", $contents);
    $tab = '<div class="tabs">';
    $tab .= '<a href="#" class="active">General</a>';
    for ($i = 0; $i < count($rows); $i++) {
        preg_match('/\/\*(.*?)\*\//', $rows[$i], $match);
        if ($match) {
            $tab .= '<a href="#">' . $match[1] . '</a>';
        }
    }
    $tab .= '</div>';
    return $tab;
}
// Format form
function format_form($contents) {
    $rows = explode("\n", $contents);
    $form = '<div class="tab-content active">';
    for ($i = 0; $i < count($rows); $i++) {
        preg_match('/\/\*(.*?)\*\//', $rows[$i], $match);
        if ($match) {
            $form .= '</div><div class="tab-content">';
        }
        preg_match('/define\(\'(.*?)\', ?(.*?)\)/', $rows[$i], $match);
        if ($match) {
            $form .= format_var_html($match[1], $match[2]);
        }
    }  
    $form .= '</div>';

    return $form;
}
if (isset($_POST['submit']) && !empty($_POST)) {
    // Update the configuration file with the new keys and values
    foreach ($_POST as $k => $v) {
        $v = in_array(strtolower($v), ['true', 'false']) ? strtolower($v) : '\'' . $v . '\'';
        $contents = preg_replace('/define\(\'' . $k . '\'\, ?(.*?)\)/s', 'define(\'' . $k . '\',' . $v . ')', $contents);
    }
    file_put_contents($file, $contents);

    

    //Return succesmessage
    header('Location: index.php?page=settings&success_msg=1');
    exit;
}

if (isset($_POST['geoupdate'])){
    //GEOLOCATION UPDATE 
    geolocationUpdate($_SESSION['userkey']); 
}

if (isset($_POST['updatecartest'])){
    //GEOLOCATION UPDATE 
    convertCartest();
}

// Handle success messages
if (isset($_GET['success_msg'])) {
    if ($_GET['success_msg'] == 1) {
        $success_msg = 'Settings updated successfully!';
    }
}



template_header('Settings', 'settings');

$view .= '
<form action="" method="post">

    <div class="content-title responsive-flex-wrap responsive-pad-bot-3">
        <h2 class="responsive-width-100">Settings</h2>
        <input type="submit" name="submit" value="Save" class="btn">
    </div>
';

if (isset($success_msg)){
    $view .= ' <div class="msg success">
                 <i class="fas fa-check-circle"></i>
                <p>'.$success_msg.'</p>
                 <i class="fas fa-times"></i>
        </div>';
}
   
$view .= format_tabs($contents);
$view .= '<div class="content-block">
        <div class="form responsive-width-100">
            ';
$view .= format_form($contents);

$view .= '
        </div>
    </div>
</form> 


<script>
document.querySelectorAll("input[type=\'checkbox\']").forEach(checkbox => {
    checkbox.onclick = () => checkbox.value = checkbox.checked ? "true" : "false";
});
</script>
';

//Output
echo $view;

template_footer();

?>