<?php
header('Content-Type: application/json; charset=utf-8');
require_once '../config/init.php';
$upload = false;
$extension = '';
$thumbname = '';
$cover = '';
$tagwriter = '';
$filefrom = Input('filefrom');
$thumbfrom = Input('thumbfrom');
$filefromUrl = trim(Input('url'));
$cid = Input('cid');
$filename  = trim(Input('filename'));
if ($cid != "") {
  $category = $db->where('id', $cid)->getOne(TABLE_CAT);
  if (!$category) {
    $response = ['status' => 2, 'message' => 'Category / File Does not find database'];
    echo json_encode($response);
    exit;
  }
} else {
  $response = ['status' => 2, 'message' => 'Category ID Missing'];
  echo json_encode($response);
  exit;
}

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

if (@$_FILES['file']['name'] == '' && $filefromUrl == '') {
  $response = ['status' => 2, 'message' => 'Select File or File URL Required'];
  echo json_encode($response);
  exit;
}


$savePath = $RootPath . '/' . $category['folder'];
$mkdir = rtrim($savePath, '/');

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;
      }
    }
  }
} else if($filefrom == "MULTI"){
  $filename = pathinfo($filename,PATHINFO_FILENAME);
  $filepath = base64_decode($filefromUrl);
  $filepath = str_replace("%20",' ',$filepath);
  $extension =  pathinfo($filepath, PATHINFO_EXTENSION);
  $path = $savePath . name_underscore($filename) . '.' . $extension;
  if(@rename($RootPath.'/'.$filepath,$path)){
    $upload = true;
  }
}

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))
        $upload = true;
    }
  }
}



if ($upload == true) {

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

  if ($thumbfrom == 'EXTERNAL_LINK') {
    if($filefrom=="MULTI" && Input('thumb_url')){
      $thumbURL = @base64_decode(Input('thumb_url'));
    } else {
      $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 = uniqid('thumb_');
        genThumb($saveThumb, $SaveThumbnail, $thumbname, $w_pos, true, FILE_THUMB_SIZES);
        unlink($saveThumb);
      }
    }
  } else {
    if ($_FILES['thumb']['name']) {
      $thumbname = uniqid('thumb_');
      genThumb($_FILES['thumb']['tmp_name'], $SaveThumbnail, $thumbname, $w_pos, true, FILE_THUMB_SIZES);
    }
  }

  if ($extension == 'mp3') {
    $Tagdata = array(
      'Title' => $filename . ' - ' . 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
    );

    $filecover = $RootPath . '/' . $category['folder'] . MP3TAG_COVER . '/cover_' . $thumbname . '.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));

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

  if ($id = $db->insert(TABLE_FILES, $data)) {
    genArtist($artist);
    $parentids = array_filter(explode('/', $category['folder']));
    array_shift($parentids);
    if ($parentids) {
      $db->where('id', $parentids, 'IN')->update(TABLE_CAT, ['totalitem' => $db->inc(1)]);
    }
    if($filefrom=="MULTI"){
    $response = ['status' => 1, 'message' => $filefromUrl];
    } else  {
      $response = ['status' => 1, 'message' => $filename . '.' . $extension];
    }

    echo json_encode($response);
    exit;
  } else {
    if (file_exists($path)) {
      unlink($path);
    }
    if ($thumbname) {
      $appsizes = explode(',', FILE_THUMB_SIZES);
      foreach ($appsizes as $wh) {
        $Imgwh = explode('x', $wh);
        $ImgDir =  $RootPath . '/' . $category['folder'] . $wh . '/' . $thumbname;
        if (file_exists($ImgDir)) {
          unlink($ImgDir);
        }
      }
      if (file_exists($path)) {
        unlink($path);
      }
    }
    $response = ['status' => 2, 'message' => $db->getLastError()];
    echo json_encode($response);
    exit;
  }
} else {
  $response = ['status' => 2, 'message' => 'File Does not Upload'];
  echo json_encode($response);
  exit;
}
