<?php

function dzsap_ajax_downloadTrack() {
  global $dzsap;
  // -- download here
  $filename = '';

  if (isset($_GET['id']) && $_GET['id']) {
    $po = get_post($_GET['id']);
    $pid = $_GET['id'];

    if ($po && $po->post_title) {
      $filename = $po->post_title;
    }

    if ($dzsap->mainoptions['allow_download_only_for_registered_users'] == 'on') {
      global $current_user;

      if ($current_user->ID) {


        if ($dzsap->mainoptions['allow_download_only_for_registered_users_capability'] && $dzsap->mainoptions['allow_download_only_for_registered_users_capability'] != 'read') {
          if (current_user_can(DZSAP_PERMISSION_ULTIMATE) || current_user_can($dzsap->mainoptions['allow_download_only_for_registered_users_capability'])) {

          } else {

            die(__("You do not have permission", DZSAP_ID));
          }
        }
      } else {

        die(__("You need to register", DZSAP_ID));
      }
    }


    $audioFilePath = '';

    $mockPostId = 0;
    $mockMargs = array();
//          error_log('$po - 5'.print_r($po,true));
    if ($po->post_type == 'product') {
      $filename = $dzsap->get_track_source($po->ID, $mockPostId, $mockMargs);
//            error_log('product get track source'.print_r($filename,true));

      if (strpos($filename, site_url()) !== false) {
        $audioFilePath = str_replace(site_url(), ABSPATH, $filename);
      }
    }
    if ($po->post_type == 'attachment') {
      $filename = wp_get_attachment_url($po->ID);
      $audioFilePath = get_attached_file($po->ID);
    }
    if ($po->post_type == DZSAP_REGISTER_POST_TYPE_NAME) {
      $filename = $dzsap->get_track_source($po->ID, $mockPostId, $mockMargs);
      $audioFilePath = '';
      if (strpos($filename, site_url()) !== false) {
        $audioFilePath = str_replace(site_url(), ABSPATH, $filename);
      }
    }

    if ($filename == '') {

      if (isset($_GET['source'])) {
        $filename = $_GET['source'];
      }


      if ($filename == '') {
        if (function_exists('get_field')) {
          $arr = get_field('scratch_preview', $po->ID);


          if ($arr) {

            $media = wp_get_attachment_url($arr);

            $filename = $media;
          }
        }
      }
    }

    // -- force it
    if (isset($_GET['songname']) && $_GET['songname']) {
      $filename = $_GET['songname'];
    }

//                    echo $filename;

    // -- still in download


    $extension = 'mp3';
    $content_type = 'application/octet-stream';

    // -- dzs ap download
    if (strpos($filename, '.m4a') !== false) {
      $extension = 'm4a';
      $content_type = 'audio/mp4';
//						$content_type = 'audio/x-m4a';
    }
    if (strpos($filename, '.wav') !== false) {
      $extension = 'wav';
      $content_type = 'audio/wav';
    }


    $filename_for_download = $filename;
//          error_log('add extension here .. no id', strpos($filename_in_header,'.'));

    $filename_exploder = explode('/', $filename_for_download);
    $filename_for_download = $filename_exploder[count($filename_exploder) - 1];

    if (strpos($filename_for_download, '.') === false) {
      $filename_for_download .= '.' . strtolower($extension);
    }


    header("Pragma: public");
    header("Expires: 0");

    header("Content-Type: '.$content_type.'");
    header("Content-Disposition: attachment; filename=\"" . ($filename_for_download) . "\"");
    header("Content-Transfer-Encoding: binary");

    if (!($audioFilePath && file_exists($audioFilePath))) {

      if (strpos($audioFilePath, DIRECTORY_SEPARATOR) === 0) {
        $audioFilePath = getenv("HOME");
      }
    }

    if ($audioFilePath && file_exists($audioFilePath)) {

      header('Content-Length: ' . filesize($audioFilePath));
      readfile($audioFilePath);
    } else {
      echo file_get_contents($filename);
    }


    dzsap_mysql_insert_activity(array(
      'id_video' => $po->ID,
      'type' => 'download',
    ));


    // --end id


  } else {
    // -- where does link come from ?
    if (isset($_GET['link']) && $_GET['link']) {

//                        $aux  =$_GET['link'];
      $aux = explode('/', $_GET['link']);
      $filename = $aux[count($aux) - 1];

      $filename = html_entity_decode($filename);
      $extension = 'mp3';

      // -- dzsap download from link

      if (strpos($_GET['link'], '.m4a') !== false) {
        $extension = 'm4a';
      }


      $filename_in_header = strtolower($filename);

      if (strpos($filename_in_header, '.') === false) {
        $filename_in_header .= '.' . $extension;
      }

      header("Pragma: public");
      header("Expires: 0");
      header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
      header("Cache-Control: public");
      header("Content-Description: File Transfer");
      header("Content-type: application/octet-stream");
      header("Content-Disposition: attachment; filename=\"" . $filename_in_header . "\"");
      header("Content-Transfer-Encoding: binary");


      echo file_get_contents($_GET['link']);


    } else {

      echo esc_html__("You need to set media id", DZSAP_ID);
    }

  }


}