<?php
  $pdo;
  try {
	  $pdo = new PDO($dsn, $user, $passwd);
	  // if ($pdo) echo "Connected to the $dbname database successfully!";

  } catch (PDOException $e) {
	  echo $e->getMessage();
  }

function get_images($pdo, $search='%', $sort='img_date', $sdir='DESC') {
  if ($sort != 'img_date' && $sdir != 'ASC') {
    if ($sort != 'img_title' && $sdir != 'DESC') {
      echo('Ey boss, database request is kinda f*cked up. Maybe you want to try that again, hey...<br>'.$sort.' '.$sdir);
      die();
    }
  }
  $params = array('search' => $search);
  $stmt = $pdo->prepare("SELECT * FROM images WHERE img_title LIKE CONCAT('%', :search ,'%') ORDER BY $sort $sdir;");
  $stmt->execute($params);
  // $stmt->debugDumpParams();
  $data = $stmt->fetchAll();

  $img_list = '<ul class="img_list">';
  foreach ($data as $block) {
    $img_list .= '<li>';
    $img_list .= '<img src=\''.$block['img_path'].'\'><br>';
    $img_list .= '<h4>'.$block['img_title']."<br></h4>";
    $img_list .= '<p class="list_text">'.$block['img_desc']."</p>";
    $img_list .= '</li>';
  }
  $img_list .= '</ul>';
  echo $img_list;
}

function get_audio($pdo, $search='%', $sort='aud_date', $sdir='DESC') {
  if ($sort != 'aud_date' && $sdir != 'ASC') {
    if ($sort != 'aud_title' && $sdir != 'DESC') {
      echo('Ey boss, database request is kinda f*cked up. Maybe you want to try that again, hey...<br>'.$sort.' '.$sdir);
      die();
    }
  }
  $params = array('search' => $search);
  $stmt = $pdo->prepare("SELECT * FROM audio WHERE aud_title LIKE CONCAT('%', :search ,'%') ORDER BY $sort $sdir;");
  $stmt->execute($params);
  // $stmt->debugDumpParams();
  $data = $stmt->fetchAll();

  $aud_list = '<ul class="aud_list">';
  foreach ($data as $block) {
    $aud_list .= '<li>';
    $aud_list .= '<div class="music_player">';
    $aud_list .= '<img src="'.get_album_cover($block["aud_title"]).'">';
    $aud_list .= '<audio controls>';
    $aud_list .= '<source src=\''.$block['aud_path'].'\' type="audio/mpeg">';
    $aud_list .= 'There would be an awesome music player here if you weren\'t such a weirdo...';
    $aud_list .= '</audio>';
    $aud_list .= '</div>';
    $aud_list .= '<h4>'.$block['aud_title']."<br></h4>";
    $aud_list .= '<p class="list_text">'.$block['aud_desc']."</p>";
    $aud_list .= '<p><a href="'.$block['aud_path'].'">download</a></p>'; // TODO: mask dl link with helper class
    $aud_list .= '</li>';
  }
  $aud_list .= '</ul>';
  echo $aud_list;
}

function get_album_cover($title) {
  // TODO: put actual code here, maybe steal from this lib https://github.com/wapmorgan/Mp3Info/blob/master/src/Mp3Info.php
  return "nopathyet";
}
