<?php
header('Content-Type: application/json; charset=utf-8');
require_once '../config/init.php';
$upload = false;
$cover = '';
$tagwriter = '';
$id = Input('id');
$thumbname = '';
$filefrom = Input('filefrom');
$thumbfrom = Input('thumbfrom');
$filefromUrl = trim(Input('url'));
$filename  = trim(Input('filename'));
if ($id != '') {
  $file = $db->where('id', $id)->getOne(TABLE_FILES);

  $cid = $file['cid'];
  $category = $db->where('id', $cid)->getOne(TABLE_CAT);
  if (!$category || !$file) {
    $response = ['status' => 2, 'message' => 'Category / File Does not find database'];
    echo json_encode($response);
    exit;
  }
} else {
  $response = ['status' => 2, 'message' => 'File Id Missing'];
  echo json_encode($response);
  exit;
}

$artist = Input('artist');
$des = Input('description', true);
$des = str_replace(array('<p><br></p>', '<p></p>'), '', $des);

$savePath = $RootPath . '/' . $category['folder'];
$mkdir = rtrim($savePath, '/');
$path = $savePath . $file['dname'];
$extension = $file['ext'];

if (!is_dir($mkdir)) {
  mkdir($mkdir, 0777, true);
}
if ($filefrom == "EXTERNAL_LINK") {
  $filefromUrl = urlexpander($filefromUrl);
  if ($filefromUrl) {
    if ($filename) {
      $fileInfo = pathinfo($filename);
      $filename = $fileInfo['filename'];
      $extension = isset($fileInfo['extension']) ? $fileInfo['extension'] : '';
    } else {
      $fileInfo = pathinfo($filefromUrl);
      $filename = $fileInfo['filename'];
      $extension = isset($fileInfo['extension']) ? $fileInfo['extension'] : '';
    }
    if ($extension == '') {
      $extension =  pathinfo($filefromUrl, PATHINFO_EXTENSION);
    }

    if ($extension == '') {
      $extension =  'dat';
    }
    if ($extension != "") {
      $extension = strtolower($extension);
      if (in_array($extension, $allowExt)) {
        $path = $savePath . name_underscore($filename) . '.' . $extension;
        if (urlCopy($filefromUrl, $path)) {
          $upload = true;
          if ($file['dname'] != basename($path)) {
            $delext = pathinfo($file['dname'], PATHINFO_EXTENSION);
            if (!in_array($delext, $allowExt)) {
              $delext  = '';
            }
            $delfilename = $delext ? $file['dname'] : $file['dname'] . '.' . $file['ext'];
            if (file_exists($RootPath . '/' . $category['folder'] . $delfilename)) {
              unlink($RootPath . '/' . $category['folder'] . $delfilename);
            }
          }
        }
      }
    }
  }
} else {
  if ($_FILES['file']['name']) {
    if ($filename) {
      $fileInfo = pathinfo($filename);
      $filename = $fileInfo['filename'];
      $extension = isset($fileInfo['extension']) ? $fileInfo['extension'] : '';
    } else {
      $fileInfo = pathinfo($_FILES['file']['name']);
      $filename = $fileInfo['filename'];
      $extension = isset($fileInfo['extension']) ? $fileInfo['extension'] : '';
    }
    if ($extension == '') {
      $extension =  pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
    }

    $extension = strtolower($extension);
    if (in_array($extension, $allowExt)) {
      $path = $savePath . name_underscore($filename) . '.' . $extension;
      if (UploadFile('file', $path)) {
        if ($file['dname'] != basename($path)) {
          $delext = pathinfo($file['dname'], PATHINFO_EXTENSION);
          if (!in_array($delext, $allowExt)) {
            $delext  = '';
          }
          $delfilename = $delext ? $file['dname'] : $file['dname'] . '.' . $file['ext'];

          if (file_exists($RootPath . '/' . $category['folder'] . $delfilename)) {
            unlink($RootPath . '/' . $category['folder'] . $delfilename);
          }
        }
        $upload = true;
      }
    }
  }
}

$w_pos = Input('w_pos') ? Input('w_pos') : 'top-left';
$SaveThumbnail = $RootPath . '/' . $category['folder'];

if ($thumbfrom == 'EXTERNAL_LINK') {
  $thumbURL = trim(Input('thumb_url'));
  $thumb_ext = pathinfo($thumbURL, PATHINFO_EXTENSION);
  if ($thumbURL && $thumb_ext) {
    $tmp_thumbname = 'tmp_thumb.' . $thumb_ext;
    $saveThumb = $RootPath . '/' . $category['folder'] . $tmp_thumbname;
    if (urlCopy($thumbURL, $saveThumb)) {
      $thumbname = $file['thumb'] ? pathinfo($file['thumb'], PATHINFO_FILENAME) : uniqid('thumb_');
      genThumb($saveThumb, $SaveThumbnail, $thumbname, $w_pos, true, FILE_THUMB_SIZES);
      unlink($saveThumb);
    }
  }
} else {
  if ($_FILES['thumb']['name']) {
    $thumbname = $file['thumb'] ? pathinfo($file['thumb'], PATHINFO_FILENAME) : uniqid('thumb_');
    genThumb($_FILES['thumb']['tmp_name'], $SaveThumbnail, $thumbname, $w_pos, true, FILE_THUMB_SIZES);
  }
}

$file_name = pathinfo($filename, PATHINFO_FILENAME);

if ($extension == 'mp3') {
  $Tagdata = array(
    'Title' => $file_name . ' - ' . APP_NAME,
    'Artist' => $artist ? $artist . ' - ' . APP_NAME : APP_NAME,
    'Album' => $category['name'] . '-' . APP_NAME,
    'Year' => date('Y'),
    'Genre' => APP_NAME,
    'Comment' => 'Downloaded from ' . APP_NAME
  );
  $newcovername = $thumbname ? $thumbname : pathinfo($file['thumb'], PATHINFO_FILENAME);
  $filecover = $RootPath . '/' . $category['folder'] . MP3TAG_COVER . '/cover_' . $newcovername . '.jpg';
  $catCover = $RootPath . '/upload_file/folderthumb/' . MP3TAG_COVER . '/cover_' . pathinfo($category['thumb'], PATHINFO_FILENAME) . '.jpg';
  if (file_exists($filecover)) {
    $cover = $filecover;
  } else if (file_exists($catCover)) {
    $cover = $catCover;
  }

  if (empty($cover)) {
    $cover =   $RootPath . '/assets/images/cover.jpg';
  }

  if (WriteTag($path, $cover, $Tagdata)) {
    $tagwriter = true;
  }
}

$release_date = Input('release_date');

if ($release_date)
  $release_date = date('Y-m-d H:i:s', strtotime($release_date));

$fileslug = Input('slug') ? Input('slug') : genSlug($file_name);
$oldslug = ($fileslug != $file['slug']) ? $file['slug'] : '';
$fileExt =  $extension ? $extension : $file['ext'];
$data = [
  'name' => $file_name,
  'dname' => ($upload == true) ? basename($path) : $file['dname'],
  'cid' => $file['cid'],
  'old_slug' => $oldslug,
  'slug' => Input('slug') ? Input('slug') : genSlug($file_name),
  'ext' => $fileExt,
  'size' => ($upload == true) ? filesize($path) : $file['size'],
  'duration' => ($upload == true) ? getDuration($path) : $file['duration'],
  'artist' => $artist,
  'thumb' => $thumbname ? $thumbname . '.' . THUMB_FORMAT : $file['thumb'],
  'des' => $des,
  'pos' => Input('pos') ? Input('pos') : 0,
  'meta_title' => Input('meta_title'),
  'meta_keyw' => Input('meta_keyw'),
  'meta_des' => Input('meta_des'),
  'newtag' => Input('new_tag') ? 1 : 0,
  'status' => Input('status') ? 1 : 0,
  'trend' => Input('trend') ? 1 : 0,
  'created_at' => $release_date ? $release_date : $db->now()
];

if ($db->where('id', $id)->update(TABLE_FILES, $data)) {
  if ($file['artist'] != $artist)
    genArtist($artist);
  $response = ['status' => 1, 'message' => $file_name . '.' . $fileExt];
  echo json_encode($response);
  exit;
} else {
  $response = ['status' => 2, 'message' => $db->getLastError()];
  echo json_encode($response);
  exit;
}
