<?php

   include "pdo_connection.php";

   if($_REQUEST["todo"] == 1) {
      $sql = "UPDATE _9a_song SET Artist_ID = ?, Title = ? WHERE ID = ?";
      $values = array($_REQUEST["artist"], $_REQUEST["title"], $_REQUEST["ID"]);
      $stmt = $pdo->prepare($sql);
      $stmt->execute($values);
      if($stmt->rowCount() == 0) echo "ERROR#Error saving or nothing changed!";
      else echo ReturnSong($_REQUEST['ID']);
   }

   if($_REQUEST["todo"] == 2) {
      $sql = "INSERT INTO _9a_song SET Artist_ID = ?, Title = ?";
      $values = array($_REQUEST["artist"], $_REQUEST["title"]);
      $stmt = $pdo->prepare($sql);
      $stmt->execute($values);
      $newid = $pdo->lastInsertId();
      if($newid) echo ReturnSong($newid);
      else  echo "ERROR#Error! Song not saved.";
   }

   if($_REQUEST["todo"] == 3) {
      $sql = "UPDATE _9a_song SET Song = ? WHERE ID = ?";
      $values = array($_REQUEST["song"], $_REQUEST["ID"]);
      // $values = array(mysql_real_escape_string($_REQUEST["song"]), $_REQUEST["ID"]);
      $stmt = $pdo->prepare($sql);
      $stmt->execute($values);
      if($stmt->rowCount() == 0) echo "ERROR#Error saving or nothing changed!";
      else echo "OK";
   }

   if($_REQUEST["todo"] == -1) {
      $sql = "DELETE FROM _9a_song WHERE ID = ?";
      $values = array($_REQUEST["ID"]);
      $stmt = $pdo->prepare($sql);
      $stmt->execute($values);
      if($stmt->rowCount() == 0) echo "ERROR# - Nothing deleted!";
      else echo "OK";
   }

   function ReturnSong($SongID) {
      global $pdo;
      $output = "";
      $sql = "SELECT _9a_song.ID, _9a_song.Artist_ID, _9a_song.Title, _9a_arist.Name"
                        ."  FROM _9a_song JOIN _9a_arist ON _9a_song.Artist_ID = _9a_arist.ID"
                        ." WHERE _9a_song.ID = ?";
      $values = array($SongID);
      $stmt = $pdo->prepare($sql);
      $stmt->execute($values);
      if($stmt->rowCount() == 0) return "ERROR# - No songs selected.";
      $row = $row = $stmt->fetch();
      $output = "OK#".$row["ID"]."#".$row["Artist_ID"]."#".$row["Title"]."#".$row["Name"];
      return $output;
   }

?>