<?php

   include "pdo_connection.php";

   function ReturnPlaylists($ActiveID) {

      global $pdo;

      $output = "";

      $sql = "SELECT ID, Playlist, Date FROM _9a_playlist WHERE User_ID = ?";

      $values[] = $_REQUEST["user"];
      $stmt = $pdo->prepare($sql);
      $stmt->execute($values);

      if($stmt->rowCount() == 0) return "No playlists";
      else {
         while($row = $stmt->fetch()) {
            $output = $output."|".$row["ID"]."#".$row["Playlist"]."#".$row["Date"];
         }
         return $ActiveID.$output;
      }
   }

   if($_REQUEST["todo"] == 0) echo ReturnPlaylists(0);

   if($_REQUEST["todo"] == -1) {
      global $pdo;
      $sql = "DELETE FROM _9a_playlist WHERE User_ID = ? AND ID = ?";
      $values[] = $_REQUEST["user"];
      $values[] = $_REQUEST["id"];
      $stmt = $pdo->prepare($sql);
      $stmt->execute($values);

      if($stmt->rowCount() == 0) {
         echo "ERROR# - Nothing deleted!";
         return;
      } else echo ReturnPlaylists(0);
   }

   if($_REQUEST["todo"] ==  1) {
      global $pdo;
      $sql = "INSERT INTO _9a_playlist SET User_ID = ?, Playlist = ?";
      $values[] = $_REQUEST["user"];
      $values[] = $_REQUEST["name"];
      $stmt = $pdo->prepare($sql);
      $stmt->execute($values);
      $newid = $pdo->lastInsertId();
      if($newid) echo ReturnPlaylists($newid);
      else echo "ERROR# - Playlist name is not saved";
   }

   if($_REQUEST["todo"] ==  2) {
      global $pdo;
      $sql = "UPDATE _9a_playlist SET Playlist = ?, Date = NOW() WHERE User_ID = ? AND ID = ?";
      $values[] = $_REQUEST["name"];
      $values[] = $_REQUEST["user"];
      $values[] = $_REQUEST["id"];
      $stmt = $pdo->prepare($sql);
      $stmt->execute($values);
      if($stmt->rowCount() == 0) {
         echo "ERROR# - Playlist name is not changed!";
         return;
      } else echo ReturnPlaylists($_REQUEST['id']);
   }

?>