<?php
defined(page_security_key) or exit;

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

$page = 'profiles';
//Check if allowed
if (isAllowed($page,$_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) {

    include dirname(__FILE__).'/settings/settingsviews.php';

    $html = '';
    $value = htmlspecialchars(trim($value, '\''), ENT_QUOTES);
    
    $profile_contents = explode(',',$value);
  
    foreach ($all_views as $view){
    $html .= '<div>';
      if (in_array($view, $profile_contents)){
        $html .= '<input type="checkbox" id="'.$key .'" name="'.$key .'[]" value="'.$view.'" checked> '.$view;
      } else {
        $html .= '<input type="checkbox" id="'.$key .'" name="'.$key .'[]" value="'.$view.'"> '.$view;
      }
      $html .= '</div>';
    } 
      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">Each tab represents a profile. Each element in a profile represents a view and or API access.';
    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)) {
    //remove submit from POST
    unset($_POST['submit']);

    //Make POST ready for save into definition
    foreach($_POST as $profile_name => $profile_views){

        $view_input = '';
        foreach($profile_views as $profile_view){
            $view_input .= $profile_view.',';
        }
        $view_input = "'".substr($view_input,0,-1)."'";
        // Update the configuration file with the new keys and values
        $contents = preg_replace('/define\(\'' . $profile_name . '\'\, ?(.*?)\)/s', 'define(\'' . $profile_name . '\',' . $view_input . ')', $contents);

    }
    //SAVE TO FILE
    file_put_contents($file, $contents);

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


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

template_header('Profiles', 'profiles');

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

    <div class="content-title responsive-flex-wrap responsive-pad-bot-3">
        <h2 class="responsive-width-100">Profiles</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> 
';

//Output
echo $view;

template_footer();

?>