<?php
// ----------------------------------------------------------------------------
// Copyright (C) 2013, Vinos de Frutas Tropicales
// Created expressly for PB Publishing, xcountryski-vermont.com.
// ----------------------------------------------------------------------------
function sort_sidebars($a, $b) {
  if ($a['sort'] == $b['sort']) {
    return 0;
  }
  return ($a['sort'] < $b['sort']) ? -1 : 1;
}

function compare_db_items($a, $b) {
  return strcasecmp($a, $b);
}

$dbMain = parse_ini_file(DB_MAIN, true);
if ($dbMain === false) {
  general_dump2log("Error accessing the main database.  Please contact the site administrator.", '', true);
}

// -----
// Determine if any pre-processing needs to happen, based on the admin's button click ...
//
switch ($action) {
  case 'save_sidebars': {
    if (isset($_POST['insert'])) {
      $dbMain['admin']['sidebar_links'][] = '||N|0';
      $action = 'edit_sidebars';
      
    } elseif (isset($_POST['cancel'])) {
      $action = '';
      
    } else {
      unset($dbMain['admin']['sidebar_links']);
      usort($_POST['sidebar'], 'sort_sidebars');
      $dbMain[ADMIN_NAME]['sidebar_links'] = array();
      if (is_array($_POST['sidebar'])) foreach($_POST['sidebar'] as $currentSidebar) {
        if ($currentSidebar['address'] != '') {
          if ($currentSidebar['new'] != 'N') {
            $currentSidebar['new'] = 'Y';
          }
          $dbMain[ADMIN_NAME]['sidebar_links'][] = $currentSidebar['address'] . '|' . $currentSidebar['text'] . '|' . $currentSidebar['new'] . '|' . $currentSidebar['sort'];
        }
      }
      if (general_safefilerewrite( DB_MAIN, general_create_ini_file ($dbMain, true) ) !== true) {
        general_dump2log("Error updating the main database.  Please contact the site administrator.", '', true);
      }
      $message = 'Database updated successfully.';
      $action = 'edit_sidebars';
    }
    break;
  }
  case 'save_common': {
    if (isset($_POST['cancel'])) {
      $action = '';
    } elseif (isset($_POST['save'])) {
      foreach ($_POST as $key => $value) {
        switch ($key) {
          case 'action':
          case 'save': {
            break;
          }
          default: {
            $dbMain[ADMIN_NAME][$key] = htmlentities ($value, ENT_COMPAT, 'UTF-8', false);
            break;
          }
        }
      }
      if (general_safefilerewrite( DB_MAIN, general_create_ini_file ($dbMain, true) ) !== true) {
        general_dump2log("Error updating the main database.  Please contact the site administrator.", '', true);
      }
      $message = 'Database updated successfully.';
      $action = 'edit_common';
    }
    break;
  }
  case 'save_center': {
    if (isset($_POST['cancel'])) {
      $action = '';
    } else {
      $center = $_POST['center'];
      if (isset($_FILES) && isset($_FILES['new_file']) && $_FILES['new_file']['error'] != 4) {
        $allowedExts = array('gif', 'jpeg', 'jpg', 'png');
        $temp = explode('.', $_FILES['new_file']['name']);
        $extension = end($temp);
        if ( ($_FILES['new_file']['type'] == 'image/gif' || $_FILES['new_file']['type'] == 'image/jpeg' || $_FILES['new_file']['type'] == 'image/jpg' || $_FILES['new_file']['type'] == 'image/pjpeg' || $_FILES['new_file']['type'] == 'image/x-png' || $_FILES['new_file']['type'] == 'image/png') && $_FILES['new_file']['size'] < 20000 && in_array($extension, $allowedExts) ) {
          if ($_FILES['new_file']['error'] > 0) {
            $message = 'File upload error code: ' . $_FILES['new_file']['error'];
          } else {
            move_uploaded_file($_FILES['new_file']['tmp_name'], 'images/centers/' . $_FILES['new_file']['name']);
            $_POST['logo'] = $_FILES['new_file']['name'];
          }
        } else {
          $message = $_FILES['new_file']['name'] . ': Unsupported file type or file size (' . ((int)$_FILES['new_file']['size'] / 1024) . ' kB) is too large.  Please try again.';
        }
      }
      $adding = (isset($_POST['add']));
      if ($adding) {
        if ($center == '') {
          $message = 'You need to supply an ID for this new center.';
        } elseif (array_key_exists($center, $dbMain)) {
          $message = 'The "Center ID" you specified already exists.';
        } elseif ($_POST['name'] == '') {
          $message = 'Please enter the name for this center';
        } elseif ($_POST['password'] == '') {
          $message = 'Please enter the password for this center.';
        } elseif ($_POST['address'] == '') {
          $message = 'Please enter the address for this center.';
        }
      }
      
      if ($message == '') {
        unset($dbMain[$center], $_POST['save'], $_POST['action'], $_POST['center'], $_POST['add']);
        $dbMain[$center] = $_POST;
        ksort($dbMain);
        $dbMain[$center]['name'] = htmlentities($dbMain[$center]['name'], ENT_COMPAT, 'UTF-8', false);
        $dbMain[$center]['banner_ad_top'] = htmlentities($dbMain[$center]['banner_ad_top'], ENT_COMPAT, 'UTF-8', false);
        $dbMain[$center]['banner_ad_bottom'] = htmlentities($dbMain[$center]['banner_ad_bottom'], ENT_COMPAT, 'UTF-8', false);
        $dbMain[$center]['special_content'] = htmlentities($dbMain[$center]['special_content'], ENT_COMPAT, 'UTF-8', false);
        $dbMain[$center]['meta_description'] = htmlentities($dbMain[$center]['meta_description'], ENT_COMPAT, 'UTF-8', false);
        $dbMain[$center]['meta_keywords'] = htmlentities($dbMain[$center]['meta_keywords'], ENT_COMPAT, 'UTF-8', false);
        if (general_safefilerewrite( DB_MAIN, general_create_ini_file ($dbMain, true) ) !== true) {
          general_dump2log("Error updating the main database.  Please contact the site administrator.", '', true);
        }
        $message = 'Database updated successfully.';
        if ($adding) {
          $newCenter = array(
            'km_open' => 0,
            'surface_type' => ':',
            'base_from' => 0,
            'base_to' => 0,
            'new_from' => 0,
            'new_to' => 0,
            'comment' => '',
            'description' => '',
            'timestamp' => time(),
            'lessons' => "No",
            'rentals' => "No",
            'snowshoe' => "No",
            'backcountry' => "No",
            'km_track' => "0",
            'km_skate' => "0",
            'grooming' => "No",
            'surface_comment' => '',
            'extra_facilities' => array( '|', '|', '|', '|', '|' ),
            'extra_fields' => array( '|', '|', '|', '|', '|' )
          );
          if (general_safefilerewrite( DB_PATH . $center . '.ini', general_create_ini_file ($newCenter) ) !== true) {
            general_dump2log("Error creating the center's database.  Please contact the site administrator.", '', true);
          }
          unset($newCenter);
          $message .= ' You still need to "Edit Details" for the newly-created center!';
        }
      }
      $action = (isset($_POST['add'])) ? 'add_center' : 'edit_center';
    }
    break;
  }
  case 'admin_actions': {
    if (isset($_POST['sidebar_edit'])) {
      $action = 'edit_sidebars';
      
    } elseif (isset($_POST['common_edit'])) {
      $action = 'edit_common';
      
    } elseif (isset($_POST['add_center'])) {
      $action = 'add_center';
       
    } else {
      $action = '';
    }
    break;
  }
  case 'center_action': {
    $center = $_POST['center'];
    if (isset($_POST['details'])) {
      general_redirect('xcsadmin.php?camefrom=center_admin.php&amp;center=' . $_POST['center']);
      
    } elseif (isset($_POST['edit'])) {
      $action = 'edit_center';
      
    } elseif (isset($_POST['delete'])) {
      $action = 'confirm_delete';
    
    } else {
      $action = '';
    }
    break;
  }
  case 'delete_confirmed': {
    $center = $_POST['center'];
    if (isset($_POST['no'])) {
      $message = 'Delete for center "' . $center . '" was cancelled.';
    } else {
      unset($dbMain[$center]);
      if (general_safefilerewrite( DB_MAIN, general_create_ini_file ($dbMain, true) ) !== true) {
        general_dump2log("Error updating the main database.  Please contact the site administrator.", '', true);
      }
      chmod(DB_PATH . $center . '.ini', 0666);
      unlink(DB_PATH . $center . '.ini');
      $message = 'The center "' . $center . '" was successfully deleted.';
    }
    $action = '';
    break;
  }
  default: {
    break;
  }
}
// -----
// Now, sort the $dbMain array's keys (the center "id") without case-sensitivity.
//
uksort($dbMain, 'compare_db_items');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Master Admin Control Center</title>
<style type="text/css">
<!--
body { font-family: Arial, Helvetica; font-size: 12pt; width: 75%; margin: 0 auto; }
table { width: 100%; margin: 0 auto; border-collapse: collapse}
td { padding: 5px; }
td.head { font-weight: bold; }
h1 { font-family: Arial, Helvetica; font-size: 16pt; text-align: center }
textarea, .w100 { width: 100%; }
.centered { text-align: center; }
.left { text-align: left; }
.right { text-align: right; }
.wyn { width: 2em; }
#msg { color: green; }
.missing { color: red; font-weight: bold; }
.smallText { font-size: smaller; }
.odd {background-color: #d2d2d2; }
-->
</style>
</head>

<body>
  <h1>Master Admin Control Center</h1>
  <div class="centered">
    <div id="msg"><?php echo ($message == '') ? '&nbsp;' : ($message . '<br />'); ?></div>
<?php
switch ($action) {
  case 'edit_sidebars': {
?>
    <h2>Edit Sidebar Links for xcountryski-vermont.com</h2>
    <ul class="left">
      <li>Remember to add the <b>http://</b> before any external link!</li>
      <li>Specify the <em>Link Address</em> as <b>%%LINKS%%</b> to include the centers' list selection at a particular point.</li>
      <li>Specify the <em>Line Address</em> as index.php for the home-page link.</li>
    </ul>
    <form id="sidebar_form" action="xcsadmin.php" method="post">
      <input type="hidden" name="action" value="save_sidebars" />
      <table border="0">
        <tr>
          <th>Link Address</th>
          <th>Link Text</th>
          <th>Sort Order</th>
          <th class="center">Open in a new window?</th>
        </tr>
<?php
    $i = 0;
    foreach ($dbMain['admin']['sidebar_links'] as $currentSidebar) {
      $sidebarValues = explode('|', $currentSidebar);
      if (!isset($sidebarValues[3])) {
        $sidebarValues[3] = 0;
      }
?>
        <tr>
          <td><input class="w100" name="sidebar[<?php echo $i; ?>][address]" value="<?php echo $sidebarValues[0]; ?>" /></td>
          <td><input class="w100" name="sidebar[<?php echo $i; ?>][text]" value="<?php echo $sidebarValues[1]; ?>" /></td>
          <td><input class="wyn" name="sidebar[<?php echo $i; ?>][sort]" value="<?php echo $sidebarValues[3]; ?>" /></td>
          <td class="center"><input class="wyn" name="sidebar[<?php echo $i; ?>][new]" value="<?php echo $sidebarValues[2]; ?>" /></td>
        </tr>
<?php
      $i++;
    }
?>
      </table>
      <input name="save" type="submit" value="Save Sidebar Links" />
      <input name="cancel" type="submit" value="Back" />
      <input name="insert" type="submit" value="Insert New Link" />
    </form>
<?php
    break;
  }  // END edit_sidebars
  case 'edit_common': {
?>
    <h2>Editing Main Page and Common Information for All Centers</h2>
    <form id="common_form" action="xcsadmin.php" method="post">
      <input type="hidden" name="action" value="save_common" />
      <input name="save" type="submit" value="Save Common Information" />
      <input name="cancel" type="submit" value="Back" />
      <br />
      <table border="0">
        <tr>
          <td class="head right">Index Page Top Logo: </td>
          <td class="left"><input name="logo_main" value="<?php echo $dbMain[ADMIN_NAME]['logo_main']; ?>" /></td>
        </tr>
        <tr>
          <td class="head right">Northern Region Centers' Top Logo:</td>
          <td class="left"><input name="logo_northern" value="<?php echo $dbMain[ADMIN_NAME]['logo_northern']; ?>" /></td>
        </tr>
        <tr>
          <td class="head right">Central Region Centers' Top Logo: </td>
          <td class="left"><input name="logo_central" value="<?php echo $dbMain[ADMIN_NAME]['logo_central']; ?>" /></td>
        </tr>
        <tr>
          <td class="head right">Southern Region Centers' Top Logo: </td>
          <td class="left"><input name="logo_southern" value="<?php echo $dbMain[ADMIN_NAME]['logo_southern']; ?>" /></td>
        </tr>
        <tr>
          <td class="head right">Top Content - Main</td>
          <td class="left"><textarea name="content_main_top" rows="5" cols="50"><?php echo $dbMain[ADMIN_NAME]['content_main_top']; ?></textarea><br /><span class="smallText">This is main-page content that appears above the top banner ad.</span></td>
        </tr>
        <tr>
          <td class="head right">Main Content</td>
          <td class="left"><textarea name="content_main" rows="5" cols="50"><?php echo $dbMain[ADMIN_NAME]['content_main']; ?></textarea><br /><span class="smallText">This is main-page content that appears between the two banner ads.</span></td>
        </tr>
        <tr>
          <td class="head right">Default Top Content - Centers</td>
          <td class="left"><textarea name="content_common_top" rows="5" cols="50"><?php echo $dbMain[ADMIN_NAME]['content_common_top']; ?></textarea><br /><span class="smallText">This is the content that appears above the top banner ad on each of the centers' pages unless a center has <em>Special Content</em> specified.</span></td>
        </tr>
         <tr>
          <td class="head right">Banner Ad (Top)</td>
          <td class="left"><textarea name="banner_ad_top" rows="5" cols="50"><?php echo $dbMain[ADMIN_NAME]['banner_ad_top']; ?></textarea><br /><span class="smallText">This is the banner ad that appears at the top of <em>all</em> pages unless a center has its own <em>Banner Ad (Top)</em> defined.</span></td>
        </tr>
        <tr>
          <td class="head right">Banner Ad (Bottom)</td>
          <td class="left"><textarea name="banner_ad_bottom" rows="5" cols="50"><?php echo $dbMain[ADMIN_NAME]['banner_ad_bottom']; ?></textarea><br /><span class="smallText">This is the banner ad that appears at the bottom of <em>all</em> pages unless a center has its own <em>Banner Ad (Top)</em> defined.</span></td>
        </tr>
        <tr>
          <td class="head right">Home Page Meta Description</td>
          <td class="left"><textarea name="meta_description" rows="3" cols="50"><?php echo $dbMain[ADMIN_NAME]['meta_description']; ?></textarea><br /><span class="smallText">This is the content that appears in the home page's <em>description</em> meta tag.</span></td>
        </tr>
        <tr>
          <td class="head right">Home Page Meta Keywords</td>
          <td class="left"><textarea name="meta_keywords" rows="3" cols="50"><?php echo $dbMain[ADMIN_NAME]['meta_keywords']; ?></textarea><br /><span class="smallText">This is the content that appears in the home page's <em>keywords</em> meta tag.</span></td>
        </tr>
      </table>
      <input name="save" type="submit" value="Save Common Information" />
      <input name="cancel" type="submit" value="Back" />
    </form>
<?php
    break;
  }  // END edit_common
  case 'add_center':
  case 'edit_center': {
    if ($action == 'add_center') {
      $requiredFields = explode (',', 'center,name,password,address,phone,email,region,website,logo,banner_ad_top,banner_ad_bottom,special_content,meta_keywords,meta_description');
      foreach ($requiredFields as $currentField) {
        if (!isset($_POST[$currentField])) {
          $_POST[$currentField] = '';
        }
      }
      $contentSource = $_POST;
    } else {
      $contentSource = $dbMain[$center];
    }
?>
    <h2><?php echo ($action == 'add_center') ? 'Add a New Center' : "Editing Center: $center"; ?></h2>
    <form action="xcsadmin.php" method="post" enctype="multipart/form-data">
      <input type="hidden" name="action" value="save_center" />
<?php
    if ($action == 'add_center') {
?>
      <input type="submit" value="Create" name="add" />
<?php
    } else {
?>      
      <input type="submit" value="Update" name="save" />
<?php
    }
?>
      <input type="submit" value="Back" name="cancel" />
<?php
    if ($action != 'add_center') {
?>
      <input type="hidden" name="center" value="<?php echo $center; ?>" />
<?php
    }
?>
      <br />
      <table border="0">
<?php
    if ($action == 'add_center') {
?>
        <tr>
          <td class="head right">Center ID:</td>
          <td class="left"><input name="center" value="<?php echo $_POST['center']; ?>" /></td>
<?php
    }
?>
        <tr>
          <td class="head right">Center Name:</td>
          <td class="left"><input name="name" value="<?php echo $contentSource['name']; ?>" /></td>
        </tr>
        <tr>
          <td class="head right">Password:</td>
          <td class="left"><input name="password" value="<?php echo $contentSource['password']; ?>" /></td>
        </tr>
        <tr>
          <td class="head right">Address:</td>
          <td class="left"><input name="address" value="<?php echo $contentSource['address']; ?>" /></td>
        </tr>
        <tr>
          <td class="head right">Phone:</td>
          <td class="left"><input name="phone" value="<?php echo $contentSource['phone']; ?>" /></td>
        </tr> 
        <tr>
          <td class="head right">E-mail:</td>
          <td class="left"><input name="email" value="<?php echo $contentSource['email']; ?>" /></td>
        </tr>
        <tr>
          <td class="head right">Region:</td>
          <td class="left"><?php echo general_build_select('region', array ( 'northern' => 'Northern', 'central' => 'Central', 'southern' => 'Southern' ), $contentSource['region']); ?></td>
        </tr>
        <tr>
          <td class="head right">Website:</td>
          <td class="left"><input name="website" value="<?php echo $contentSource['website']; ?>" /></td>
        </tr> 
        <tr>
          <td class="head right">Logo:</td>
          <td class="left"><input name="logo" value="<?php echo $contentSource['logo']; ?>" /><input type="file" name="new_file" /></td>
        </tr>
        <tr>
          <td class="head right">Banner Ad (Top):</td>
          <td colspan="3"><textarea name="banner_ad_top" rows="5" cols="50"><?php echo $contentSource['banner_ad_top']; ?></textarea></td>
        </tr>
        <tr>
          <td class="head right">Banner Ad (Bottom):</td>
          <td colspan="3"><textarea name="banner_ad_bottom" rows="5" cols="50"><?php echo $contentSource['banner_ad_bottom']; ?></textarea></td>
        </tr>
        <tr>
          <td class="head right">Special Content:</td>
          <td colspan="3"><textarea name="special_content" rows="3" cols="50"><?php echo $contentSource['special_content']; ?></textarea></td>
        </tr>
        <tr>
          <td class="head right">Center's Meta Description</td>
          <td class="left"><textarea name="meta_description" rows="3" cols="50"><?php echo $contentSource['meta_description']; ?></textarea><br /><span class="smallText">This is the content that appears in the center-specific page's <em>description</em> meta tag.</span></td>
        </tr>
        <tr>
          <td class="head right">Center's Meta Keywords</td>
          <td class="left"><textarea name="meta_keywords" rows="3" cols="50"><?php echo $contentSource['meta_keywords']; ?></textarea><br /><span class="smallText">This is the content that appears in the center-specific page's <em>keywords</em> meta tag.</span></td>
        </tr>
        
      </table>
<?php
    unset($contentSource);
    if ($action == 'add_center') {
?>
      <input type="submit" value="Create" name="add" />
<?php
    } else {
?>      
      <input type="submit" value="Update" name="save" />
<?php
    }
?>
      <input type="submit" value="Back" name="cancel" />
    </form>
<?php
    break;
  }  // END edit_center
  case 'confirm_delete': {
?>
    <form id="confirm_delete_form" action="xcsadmin.php" method="post">
      <input type="hidden" name="action" value="delete_confirmed" />
      <input type="hidden" name="center" value="<?php echo $center; ?>" />
      <div>Are you sure you want to delete the <?php echo $center; ?> center?<div>
      <input type="submit" name="yes" value="Yes" />
      <input type="submit" name="no" value="No" />
    </form>
<?php
    break;
  }  // END confirm_delete
  default: {
?>
    <form id="logoff_form" action="xcsadmin.php" method="post">
      <input type="hidden" name="action" value="logoff" />
      <input type="submit" value="Logoff" />
    </form>
    
    <form id="admin_form" action="xcsadmin.php" method="post">
      <input type="hidden" name="action" value="admin_actions" />
      <input type="submit" name="add_center" value="Add a New Center" />
      <input type="submit" name="sidebar_edit" value="Edit Sidebar Links" />
      <input type="submit" name="common_edit" value="Edit Common Information" />
    </form>
    <table border="1" cellspacing="0" cellpadding="0">
      <tr>
        <th>Center ID</th>
        <th>Center Name</th>
        <th>Region</th>
        <th>Address, Phone &amp; E-mail</th>
        <th>Website</th>
        <th>Logo</th>
        <th>Banner Ads</th>
        <th>Special Content</th>
        <th>Actions</th>
      </tr>
<?php
    $notCenters = array(ADMIN_NAME, 'northern', 'central', 'southern');
    $evenodd = 'even';
    foreach ($dbMain as $center => $centerInfo) {
      if (!in_array($center, $notCenters)) {
?>
      <tr class="<?php echo $evenodd; ?>">
        <td><?php echo $center; ?></td>
        <td><?php echo $centerInfo['name']; ?></td>
        <td><?php echo $centerInfo['region']; ?></td>
        <td><?php echo $centerInfo['address'] . '<br />' . $centerInfo['phone'] . '<br />' . (($centerInfo['email'] == '') ? '<span class="missing">No email address!</span>' : $centerInfo['email']); ?></td>
        <td><?php echo $centerInfo['website']; ?></td>
        <td><?php echo (($centerInfo['logo'] == '') ? '<span class="missing">No logo!</span>' : $centerInfo['logo']); ?></td>
        <td>Top: <?php echo ($centerInfo['banner_ad_top'] == '') ? 'No' : 'Yes'; ?><br />Bottom: <?php echo ($centerInfo['banner_ad_bottom'] == '') ? 'No' : 'Yes'; ?></td>
        <td><?php echo ($centerInfo['special_content'] == '') ? 'No' : 'Yes'; ?></td>
        <td>
          <form action="xcsadmin.php" method="post">
            <input type="hidden" name="center" value="<?php echo $center; ?>" />
            <input type="hidden" name="action" value="center_action" />
            <input type="submit" name="delete" value="Delete" />
            <input type="submit" name="edit" value="Edit" />
            <input type="submit" name="details" value="Edit Details" />
          </form>
        </td>
        
      </tr>
<?php
        $evenodd = ($evenodd == 'even') ? 'odd' : 'even';
      }
    }
?>
      </table>
<?php
    break;
  }  // END default
}  // END switch
?>
  </div>
<?php
echo superglobals_echo();
?>
</body>
</html>