<?php

// defines if this script requires to be logged in
define( "PRIVATE", true );

require_once('../lib/inc-common.php');
require_once('../lib/inc-admin.php');
require_once(FS_PATH."/etc/locale/".LANG_PACK."/inc-admin_md-edit.php");

// ** Usage : netjuke/md-edit.php?do=view|edit&type=ge|ar|al&id=numeric_id

// Sanity checking
ensure_defined_REQUEST('do');
ensure_defined_REQUEST('type');
ensure_defined_REQUEST('id');
ensure_defined_REQUEST('gr_do');
ensure_defined_REQUEST('dl_cnt_reset');
ensure_defined_REQUEST('gr_com_do');
ensure_defined_REQUEST('gr_lic_do');
ensure_defined_REQUEST('gr_img_do');

$checked = '';

#echo '<pre>';
#print_r ($_REQUEST);
#echo '</pre>';

switch ($_REQUEST['type']) {

  case 'ge':
    $table = 'netjuke_genres';
    $header = MDEDIT_HEADER_GE;
    $name = MDEDIT_FORM_NAME_GE;
    $img_header = MDEDIT_FORM_IMAGE_GE;
    $id = 'ge_id';
    $xml = 'show.genres';
    break;

  case 'ar':
    $table = 'netjuke_artists';
    $header = MDEDIT_HEADER_AR;
    $name = MDEDIT_FORM_NAME_AR;
    $img_header = MDEDIT_FORM_IMAGE_AR;
    $id = 'ar_id';
    $xml = 'show.artists';
    break;

  case 'al':
    $table = 'netjuke_albums';
    $header = MDEDIT_HEADER_AL;
    $name = MDEDIT_FORM_NAME_AL;
    $img_header = MDEDIT_FORM_IMAGE_AL;
    $id = 'al_id';
    $xml = 'show.albums';
    break;

  default:
    $table = '';
    break;

}
if (! $_REQUEST['do'] || ! $_REQUEST['type'] || ! $_REQUEST['id'] || ! $table) {

  // Throw error and redirect
  header("Location: ".WEB_PATH."/index.php");

}

##
# REFRESH ALL TRACKS IN THIS GROUP
#
if ($_REQUEST['do'] == 'refresh') {

  $sql = "select id, location from netjuke_tracks where ".$id." = ".$_REQUEST['id'];
  $tr_rs = $dbconn->Execute ($sql);
  while (! $tr_rs->EOF) {

    $location = rawurldecode($tr_rs->fields[1]);
    $temp_id3 = ReadFileID3($location, str_replace( '//', '/', MUSIC_DIR.'/'.$location ));
    UpdateTrackInfo ($tr_rs->fields[0], $temp_id3);
    $tr_rs->MoveNext();

  }

  $tr_rs->Close();

  javascript("alert('".MDEDIT_EDITED_MSG."');");
  exit;

}
##
# DELETE ALL TRACKS IN THIS GROUP AND THEN DELETE SELF
#
elseif ($_REQUEST['do'] == 'delete') {

    $track_cache = array();

    // First remove all the tracks
    $sql = "select location, ar_id, ge_id, al_id from netjuke_tracks where location not like '%://%' and ".$id." = ".$_REQUEST['id'];
    $tr_rs = $dbconn->Execute ($sql);
    while (! $tr_rs->EOF) {

      $track_cache['netjuke_artists'][$tr_rs->fields[1]]++;
      $track_cache['netjuke_genres'][$tr_rs->fields[2]]++;
      $track_cache['netjuke_albums'][$tr_rs->fields[3]]++;

      if (EDIT_MEDIA == 't')
        MoveToTrash ($tr_rs->fields[0]);
      $tr_rs->MoveNext ();

    }

    $sql = "delete from netjuke_tracks where ".$id." = ".$_REQUEST['id'];
    $dbconn->Execute ($sql);

    $sql = "delete from ".$table." where id = ".$_REQUEST['id'];
    $dbconn->Execute ($sql);

    track_cache_batch('decrement', $track_cache);
    CacheCleanUp ();
    javascript("alert('".MDEDIT_DELETED_MSG."');self.close();");
    exit;

}
##
# SAVE METADATA
#
elseif ($_REQUEST['do'] == 'save') {

  // Maintain an array of affected tracks for ID3-writeback
  $ids = array ();

  // Get the tracks that will be affected by changes to this group
  $sql = "select id from netjuke_tracks where ".$id." = ".$_REQUEST['id'];
  $tr_rs = $dbconn->Execute ($sql);
  while (! $tr_rs->EOF) {
    $ids[] = $tr_rs->fields[0];
    $tr_rs->MoveNext();
  }
  $tr_rs->Close();

  // ARTIST/ALBUM/GENRE NAME
  if (abs($_REQUEST['gr_do']) == 1) {

    if ($_REQUEST['gr_name'] != '') {
      // See if this new name is unique
      $sql = "select id from ".$table." where name = '".raw_to_db($_REQUEST['gr_name'])."'";
      $ex_rs = $dbconn->Execute ($sql);

      // If this is a unique name, just change the name of this id
      if ($ex_rs->RecordCount() < 1) {
        $cols[] = " name = '".raw_to_db($_REQUEST['gr_name'])."' ";
      } else {
        // This name already exists, move all tracks to the existing id
        // and delete our own id from the table
        if ($_REQUEST['id'] != $ex_rs->fields[0]) {
                $sql = "update netjuke_tracks set ".$id." = ".$ex_rs->fields[0]." where ".$id." = ".$_REQUEST['id'];
                $dbconn->Execute ($sql);
                $cnt = $dbconn->Affected_Rows ();

                $sql = "update ".$table." set track_cnt = track_cnt + ".$cnt." where id = ".$ex_rs->fields[0];
                $sql = "delete from ".$table." where id = ".$_REQUEST['id'];
                $dbconn->Execute ($sql);
                $_REQUEST['id'] = $ex_rs->fields[0];
        } else {
                // Handle changes in capitalization -- same id, new name...
                $sql = "update ".$table." set name = '".raw_to_db($_REQUEST['gr_name'])."' where id = ".$_REQUEST['id'];
                $dbconn->Execute ($sql);
        }

      }

      $ex_rs->Close();

    } else {
      // User selected an item from the drop down
      // switch tracks to the id and then delete self
      $sql = "update netjuke_tracks set ".$id." = ".$_REQUEST['gr_id']." where ".$id." = ".$_REQUEST['id'];
      $dbconn->Execute ($sql);
      $cnt = $dbconn->Affected_Rows ();

      $sql = "update ".$table." set track_cnt = track_cnt + ".$cnt." where id = ".$_REQUEST['gr_id'];
      $dbconn->Execute ($sql);
      $sql = "delete from ".$table." where id = ".$_REQUEST['id'];
      $dbconn->Execute ($sql);
      $_REQUEST['id'] = $_REQUEST['gr_id'];
    }

  }

  $sql ='';

  // SUB-GENRE ID
  if ($id == 'ge_id') {
    if (abs ($_REQUEST['sub_do']) == 1) {

      if ($_REQUEST['sub_name'] != '') {
        list($sub_id,$errors) = Find_Id_TrBatchEdit('netjuke_genres',$_REQUEST['sub_name']);
      } else {
        $sub_id = $_REQUEST['sub_id'];
      }

      $cols[] = " parent_id = ".$sub_id;

    }
  }

  // listener count
  if ( abs($_REQUEST['dl_cnt_reset']) == 1 ) {
    $cols[] = " dl_cnt = 0 ";
  }

  // comments
  if ( (abs($_REQUEST['gr_com_do']) == 1) ) {
    $cols[] = " comments = '".raw_to_db($_REQUEST['gr_com'])."' ";
  }

  // license
  if ( (abs($_REQUEST['gr_lic_do']) == 1) ) {
    $cols[] = " license = '".raw_to_db($_REQUEST['gr_lic'])."' ";
  }

  // exclude
  if ( (abs($_REQUEST['gr_exclude']) == 1) )
    $cols[] = " exclude = 't' ";
  else
    $cols[] = " exclude = 'f' ";

  // save the data back to the table
  if (count($cols) > 0) {

    $sql  = " update ".$table." set "
          . " ".implode(", ",$cols)." "
          . " where id = ".$_REQUEST['id'];

    $dbconn->Execute($sql);

  }

  // image
  if ( abs($_REQUEST['gr_img_do']) == 1 ) {
    Update_Image($_REQUEST['type'], $_REQUEST['gr_id'], $_REQUEST['gr_img']);
  }

  // Write tags back to the affected files
  if (EDIT_MEDIA == 't') {
    WriteTags ($ids);
  }

  // write tags back to affected files
  # top.location.href = '".$_SERVER['HTTP_REFERER']."';
  javascript("alert('".MDEDIT_EDITED_MSG."');self.close();");

} elseif ($_REQUEST['do'] == "edit") {

  // Retrieve the information from the database
  if ($_REQUEST['type'] == 'ge')
    $sub = ", parent_id";
  else
    $sub = '';
  $sql = "select id, name, img_src, comments, license, exclude".$sub." from ".$table." where id = '".$_REQUEST['id']."'";
  #echo $sql;
  $dbrs = $dbconn->Execute ($sql);

  if ($dbrs->fields[5] == 't')
    $checked = "CHECKED";
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
			"http://www.w3.org/TR/REC-html40/loose.dtd">

<HTML>
<HEAD>
	<meta HTTP-EQUIV="Pragma" CONTENT="no-cache">
	<meta http-equiv="Content-Type" content="text/html; charset=<?php echo  LANG_CHARSET ?>">
	<TITLE><?php echo  $header ?></TITLE>
    <style type="text/css">
      <?php require_once(FS_PATH."/lib/inc-css.php"); ?>
    </style>
</HEAD>
<BODY BGCOLOR='#<?php echo $NETJUKE_SESSION_VARS["bgcolor"]?>' TEXT='#<?php echo $NETJUKE_SESSION_VARS["text"]?>' LINK='#<?php echo $NETJUKE_SESSION_VARS["link"]?>' ALINK='#<?php echo $NETJUKE_SESSION_VARS["alink"]?>' VLINK='#<?php echo $NETJUKE_SESSION_VARS["vlink"]?>' ONLOAD='self.focus();'>
	<a name="PageTop"></a>

	<div align=center>
		<table width='100%' border=0 cellspacing=1 cellpadding=3 class='border'>
		<tr>
                  <td align=left class="header" colspan=2><b><?php echo  $header ?></b></td>
		</tr>
		<form action='<?php echo $_SERVER['PHP_SELF']?>' method=post name='trackForm'>
                  <input type=hidden name='do' value='save'>
                  <input type=hidden name='type' value='<?php echo $_REQUEST['type'] ?>'>
                  <input type=hidden name='id' value='<?php echo $_REQUEST['id'] ?>'>
                  <tr>
                    <td width="30%" align=right valign=top class="content" nowrap>
                      <?php echo  $name ?>
                      <input type="checkbox" name="gr_do" value="1">
                    </td>
                    <td width="70%" align=left valign=top class="content">
                      <?php echo pairSelect($table,'gr_id',$_REQUEST['id'],"document.trackForm.gr_do.checked = true;")?>
                      <br>
                      <input type="text" name="gr_name" value="" size="35" maxlength="100" class=input_content onChange="document.trackForm.gr_do.checked = true;">
		    </td>
		  </tr>
		  <?php if ($_REQUEST['type'] == 'ge') { ?>
		  <tr>
                    <td width="30%" align=right valign=top class="content" nowrap>
                      <?php echo  MDEDIT_FORM_SUB_GENRE ?>
                      <input type="checkbox" name="sub_do" value="1">
                    </td>
                    <td width="70%" align=left valign=top class="content">
                      <?php echo pairSelect('netjuke_genres','sub_id',$dbrs->fields[6],"document.trackForm.sub_do.checked = true;", constant ('MDEDIT_FORM_NO_GENRE'),"and parent_id = 0")?>
                      <br>
                      <input type="text" name="sub_name" value="" size="35" maxlength="100" class=input_content onChange="document.trackForm.gr_do.checked = true;">
                    </td>
		  </tr>
		  <?php } ?>
		  <tr>
                    <td width="30%" align=right valign=top class="content" nowrap>
                      <?php echo  $img_header ?>
                      <input type="checkbox" name="gr_img_do" value="1">
                    </td>
                    <td width="70%" align=left valign=top class="content">
                      <input type="text" name="gr_img" value="<?php echo $dbrs->fields[2] ?>" size="35" maxlength="256" class=input_content onChange="document.trackForm.gr_img_do.checked = true;">
                    </td>
                  </tr>
		  <tr>
                    <td width="30%" align=right valign=top class="content" nowrap><?php echo  MDEDIT_FORM_LC ?></td>
                    <td width="70%" align=left valign=top class="content">
                      <input type="checkbox" name="dl_cnt_reset" value="1"><?php echo  MDEDIT_FORM_RESET ?></td>
                    </td>
                  </tr>
                  <tr>
                    <td width="30%" align=right valign=top class="content" nowrap>
                      <?php echo  MDEDIT_FORM_COMMENTS ?>
                      <input type="checkbox" name="gr_com_do" value="1">
                    </td>
                    <td width="70%" align=left valign=top class="content">
                      <textarea name="gr_com" rows="10" cols="35" class=input_content onChange="document.trackForm.gr_com_do.checked = true;"><?php echo $dbrs->fields[3] ?></textarea>
                    </td>
                  </tr>
                  <tr>
                    <td width="30%" align=right valign=top class="content" nowrap>
                      <?php echo  MDEDIT_FORM_LICENSE ?>
                      <input type="checkbox" name="gr_lic_do" value="1">
                    </td>
                    <td width="70%" align=left valign=top class="content">
                      <?php echo GetLicenseSelect (0, "document.trackForm.gr_lic_do.checked = true;"); ?>
                      <br />
                      <textarea name="gr_lic" rows="10" cols="35" class=input_content onChange="document.trackForm.gr_lic_do.checked = true;"><?php echo $dbrs->fields[4] ?></textarea>
                    </td>
                  </tr>
                  <tr>
                    <td width="30%" align=right valign=top class="content" nowrap><?php echo  MDEDIT_FORM_EX ?></td>
                    <td width="70%" align=left valign=top class="content">
                      <input type="checkbox" name="gr_exclude" value="1" <?php echo $checked; ?>></td>
                    </td>
                  </tr>
                  <tr>
                    <td colspan=2 align=center valign=middle class="content">
                      <input type=submit name="btn_update" value='<?php echo  MDEDIT_FORM_BTN_SAVE ?>' class='btn_content'>
                      <input type=button name="btn_del" value='<?php echo  MDEDIT_FORM_BTN_DEL ?>' class='btn_content' onclick="if (confirm('<?php echo  MDEDIT_FORM_BTN_DEL_CONF ?>'))  top.location.href = '<?php echo $_SERVER['PHP_SELF']?>?do=delete&type=<?php echo $_REQUEST['type']?>&id=<?php echo abs($_REQUEST['id'])?>'; ">
                      <input type=button name="btn_ref" value='<?php echo  MDEDIT_FORM_BTN_REF ?>' class='btn_content' onclick="top.location.href = '<?php echo $_SERVER['PHP_SELF']."?do=refresh&type=".$_REQUEST['type']."&id=".$_REQUEST['id']?>'; ">
                      <input type=button name="btn_org" value='<?php echo  MDEDIT_FORM_BTN_ORG ?>' class='btn_content' onclick="top.location.href = '<?php echo WEB_PATH."/admin/organize.php?do=organize_group&type=".$_REQUEST['type']."&id=".$_REQUEST['id']?>'; ">
                      <input type=reset value='<?php echo  MDEDIT_FORM_BTN_RESET ?>' class='btn_content'>
                    </td>
                  </tr>
                </form>
                </table>
                <?php
                  if (ENABLE_XML == 't') {
                    $xml_button = buildButton (WEB_PATH."/xml.php?do=".$xml."&id=".$_REQUEST['id'], COMMON_XML_HELP, 'xml');
                    echo '<br><center>'.$xml_button.'</center>';
                  }
                ?>

		<br>
		<table width='100%' border=0 cellspacing=1 cellpadding=3 class="border">
			<tr>
				<td width="" align="center" class="content"><a href="<?php echo WEB_PATH.'/play.php?do=play&val='.$_REQUEST['val']?>" title="<?php echo  MDEDIT_PLAY_HELP ?>"><b><?php echo  MDEDIT_PLAY ?></b></a></td>
				<td width="" align="center" class="content"><a href="javascript:window.close();" title="<?php echo  MDEDIT_CLOSEWIN_HELP ?>"><b><?php echo  MDEDIT_CLOSEWIN ?></b></a></td>
			</tr>
		</table>
	<div>

</BODY>
</HTML>

<?php

  exit;

} elseif ($_REQUEST['do'] == 'view') {

  # Display Table Showing Values
  header ( 'Location : '.WEB_PATH.'/md-view.php?type='.$_REQUEST['type'].'&id='.$_REQUEST['id'] );

} else {

  javascript ("self.close();");

   exit;

}

?>
