<?php

use Intervention\Image\ImageManagerStatic as Image;
use Intervention\Image\Exception\NotReadableException;

if (detect_device())
  define('USER_DEVICE', 'm');
else {
  define('USER_DEVICE', 'p');
}
function getURL()
{
  $host = $_SERVER['HTTP_HOST'];
  $request_uri = $_SERVER['REQUEST_URI'];
  $request_uri = parse_url($request_uri, PHP_URL_PATH);
  return trim($host . $request_uri, '/');
}

function is_favourite($post_id, $user_id, $type = 'song')
{
  global $db;
  return $db->where('user_id', $user_id)->where('file_id', $post_id)->has('favourite');
}

 function randLightColor(){
    $colors = [
        '#fc5c65', '#fd9644', '#fed330', '#26de81', '#2bcbba',
        '#eb3b5a', '#fa8231', '#cc06d99e', '#20bf6b', '#45aaf2',
        '#4b7bec', '#a55eea', '#a55eea', '#e9b414', '#2d98da',
        '#3867d6', '#8854d0', '#40407a', '#2c2c54',
        '#474787', '#ff5252', '#ff793f', '#ef5777', '#575fcf',
        '#4bcffa', '#0be881', '#f53b57', '#3c40c6', '#05c46b',
        '#485460', '#ff3f34', '#FFC312', '#C4E538', '#FDA7DF',
        '#F79F1F', '#A3CB38', '#08a53d', '#EE5A24',
        '#009432', '#0652DD', '#0652DD', '#EA2027', '#5758BB',
        '#9c88ff', '#74b9ff', '#a29bfe', '#6c5ce7', '#fab1a0',
        '#ff7675', '#fd79a8','#f45444','#000000'
    ];
    $random_keys=array_rand($colors,3);
    return $colors[$random_keys[0]];
}

function randGradient()
{
    $color1 = randLightColor();
    $color2 = randLightColor();
    $angle = rand(1, 360);
    $gradient = "background: linear-gradient({$angle}deg, {$color1}, {$color2})";
    return $gradient;
}

function slug($str)
{
  if (extension_loaded('intl')) {
    $generator = new Ausi\SlugGenerator\SlugGenerator();
    return $generator->generate($str);
  }
    $str = str_replace(' ', '-', trim($str));
    $str = str_replace('_', '-', $str);
    $str = preg_replace("/[^A-Za-z0-9-]/", "", $str);
    $str = str_replace('---', '-', $str);
    $str = str_replace('--', '-', $str);
    return strtolower($str);
}

function title($str)
{
  $str = trim($str);
  return ucwords($str);
}


function RegisterUser($data)
{
  global $db;
  if ($data) {
    if (!$data['identifier']) {
      return false;
    }
    if (!$data['first_name']) {
      return false;
    }
    if ($db->where('auth_id', $data['identifier'])->has('users')) {
      return true;
    }
    $UserData = [
      'name' => $data['first_name'] . ' ' . $data['last_name'],
      'user_name' => genUserName($data['first_name']),
      'email' => $data['email'],
      'user_type' => $data['provider'],
      'avator' => $data['photoURL'],
      'auth_id' => $data['identifier'],
      'created_at' => $db->now(),
      'status' => 1
    ];
    if ($db->insert('users', $UserData)) {
      if ($data['photoURL']) {
        @CopyAvator($data['photoURL'], $UserData['user_name']);
      }
      return true;
    }
  }
  return false;
}

function CopyAvator($PhotoURL, $username)
{
  global $RootPath;
  $tmp_photo = $RootPath . '/upload_file/' . uniqid('photo_') . '.jpg';
  if (@copy($PhotoURL, $tmp_photo)) {
    $ImgDir1 = $RootPath . '/upload_file/userthumb/40x40';
    $ImgDir2 = $RootPath . '/upload_file/userthumb/150x150';
    if (!is_dir($ImgDir1)) {
      mkdir($ImgDir1, 0777, true);
    }
    if (!is_dir($ImgDir2)) {
      mkdir($ImgDir2, 0777, true);
    }
    try {
      Image::make($tmp_photo)->resize(40, 40)->save($ImgDir1 . '/' . $username . '.jpg', THUMB_QUALITY);
      Image::make($tmp_photo)->resize(150, 150)->save($ImgDir2 . '/' . $username . '.jpg', THUMB_QUALITY);
    } catch (NotReadableException $e) {
      error_log($e->getMessage());
    }
    @unlink($tmp_photo);
  }
}

function genUserName($str, $id = '')
{
  global $db;
  $slug = slug($str);
  if ($id) {
    $db->where('id', $id, '!=');
  }
  $checkExists =  $db->where('user_name', $slug)->has('users');
  if ($checkExists) {
    return genUserName($slug . '-' . rand(1, 9), $id);
  }
  return $slug;
}


function formatSize($size, $type = false, $round = 2)
{
  $sizes = array('byts', 'kb', 'mb', 'gb', 'tb');
  $total = count($sizes) - 1;
  for ($i = 0; $size > 1024 && $i < $total; $i++)
    $size /= 1024;
  if ($type == true)
    return array(round($size, $round), $sizes[$i]);
  return round($size, $round) . ' ' . $sizes[$i];
}
function fileDownload($Path, $fileName, $ext)
{
  switch ($ext) {
    case 'MP3':
      $mime = "audio/mpeg";
      break;
    case 'JPG':
      $mime = "image/jpg";
      break;
    default:
      $mime = "application/octet-stream";
  }

  header('Content-type: ' . $mime);
  header('Content-Disposition: attachment; filename="' . $fileName . '"');
  header('Content-Length: ' . filesize($Path));
  readfile($Path);
  exit;
}

function checkMimeType($file)
{
  $mtype = false;
  if (function_exists('finfo_open')) {
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mtype = finfo_file($finfo, $file);
    finfo_close($finfo);
  } elseif (function_exists('mime_content_type')) {
    $mtype = mime_content_type($file);
  }
  return $mtype;
}
function getPageUrl($page, $link)
{
  return str_replace('{{PAGE}}', $page, $link);
}

function skyPageNavigate($totalpage, $start, $limit, $link)
{
  if ($totalpage != 1 && $totalpage != 0) {
    $pagination = '<nav aria-label="Page navigation"><ul class="pagination justify-content-center">';
    $totalLink = 5;
    $no_of_page = $totalpage;

    if ($start * $limit > $limit)
      $pagination .= '<li class="page-item"><a class="page-link" href="' . getPageUrl($start - 1, $link) . '"><i class="fa fa-caret-left" aria-hidden="true"></i> Prev</a></li>';
    // $pagination .= link_to('< Prev', $link.($start-1));

    $count_record = 0;
    $i = 1;
    if ($start >= $totalLink - floor($totalLink / 2))
      $i = $start - floor($totalLink / 2);

    if ($no_of_page > $totalLink)
      if (($no_of_page - $i) < $totalLink)
        $i = $i - ($totalLink - ($no_of_page - $i) - 1);

    for (; $i <= $no_of_page; $i++) {
      if ($start == $i)
        $pagination .= '<li class="page-item active" aria-current="page"><a href="#" class="page-link" tabindex="-1">' . $i . '</a></li>';
      else
        $pagination .=  '<li class="page-item"><a class="page-link" href="' . getPageUrl($i, $link) . '">' . $i . '</a></li>';
      //  $pagination .= link_to($i,$link.$i).'';
      $count_record = $count_record + 1;
      if ($count_record == $totalLink)
        break;
    }

    if ($start < $no_of_page) {
      $pagination .= '<li class="page-item"><a class="page-link" href="' . getPageUrl($start + 1, $link) . '">Next <i class="fa fa-caret-right" aria-hidden="true"></i></a></li>';
    }
    if ($start > 0)
      $pagination .= '</ul></nav>';
    return $pagination;
  }
}

function getAds($str)
{
  return  file_get_contents($str . '_' . USER_DEVICE . '.html');
}

function getFileContent($path)
{
  global $RootPath;
  return file_get_contents($RootPath . '/templates/' . $path . '.html');
}

function detect_device()
{
  if (preg_match('/uc browser|ucweb|android|up.browser|up.link|windows ce|iemobile|mini|mmp|symbian|midp|wap|phone|pocket|mobile|pda|psp/i', $_SERVER['HTTP_USER_AGENT'])) {
    return true;
  }
  if (stristr($_SERVER['HTTP_USER_AGENT'], 'windows') && !stristr($_SERVER['HTTP_USER_AGENT'], 'windows ce')) {
    return false;
  }
  if (stristr($_SERVER['HTTP_ACCEPT'], 'text/vnd.wap.wml') || stristr($_SERVER['HTTP_ACCEPT'], 'application/vnd.wap.xhtml+xml')) {
    return true;
  }
  if (isset($_SERVER['HTTP_X_WAP_PROFILE']) || isset($_SERVER['HTTP_PROFILE']) || isset($_SERVER['X-OperaMini-Features']) || isset($_SERVER['UA-pixels'])) {
    return true;
  }
  $dmdarray = array(
    'acs-' => 'acs-', 'alav' => 'alav', 'alca' => 'alca', 'amoi' => 'amoi', 'audi' => 'audi', 'aste' => 'aste',
    'avan' => 'avan', 'benq' => 'benq', 'bird' => 'bird', 'blac' => 'blac', 'blaz' => 'blaz', 'brew' => 'brew', 'cell' => 'cell',
    'cldc' => 'cldc', 'cmd-' => 'cmd-', 'dang' => 'dang', 'doco' => 'doco', 'eric' => 'eric', 'hipt' => 'hipt', 'inno' => 'inno',
    'ipaq' => 'ipaq', 'java' => 'java', 'jigs' => 'jigs', 'kddi' => 'kddi', 'keji' => 'keji', 'leno' => 'leno', 'lg-c' => 'lg-c',
    'lg-d' => 'lg-d', 'lg-g' => 'lg-g', 'lge-' => 'lge-', 'maui' => 'maui', 'maxo' => 'maxo', 'midp' => 'midp', 'mits' => 'mits',
    'mmef' => 'mmef', 'mobi' => 'mobi', 'mot-' => 'mot-', 'moto' => 'moto', 'mwbp' => 'mwbp', 'nec-' => 'nec-', 'newt' => 'newt',
    'noki' => 'noki', 'opwv' => 'opwv', 'palm' => 'palm', 'pana' => 'pana', 'pant' => 'pant', 'pdxg' => 'pdxg', 'phil' => 'phil',
    'play' => 'play', 'pluc' => 'pluc', 'port' => 'port', 'prox' => 'prox', 'qtek' => 'qtek', 'qwap' => 'qwap', 'sage' => 'sage',
    'sams' => 'sams', 'sany' => 'sany', 'sch-' => 'sch-', 'sec-' => 'sec-', 'send' => 'send', 'seri' => 'seri', 'sgh-' => 'sgh-',
    'shar' => 'shar', 'sie-' => 'sie-', 'siem' => 'siem', 'smal' => 'smal', 'smar' => 'smar', 'sony' => 'sony', 'sph-' => 'sph-',
    'symb' => 'symb', 't-mo' => 't-mo', 'teli' => 'teli', 'tim-' => 'tim-', 'tosh' => 'tosh', 'treo' => 'treo', 'tsm-' => 'tsm-',
    'upg1' => 'upg1', 'upsi' => 'upsi', 'vk-v' => 'vk-v', 'voda' => 'voda', 'wap-' => 'wap-', 'wapa' => 'wapa', 'wapi' => 'wapi',
    'wapp' => 'wapp', 'wapr' => 'wapr', 'webc' => 'webc', 'winw' => 'winw', 'winw' => 'winw', 'xda-' => 'xda-'
  );
  // check if the first four characters of the current user agent are set as a key in the array
  if (isset($dmdarray[substr($_SERVER['HTTP_USER_AGENT'], 0, 4)])) {
    return true;
  }
}

function Redirect($url)
{
  header("Location: $url");
  exit;
}
