<?php
require_once __DIR__ . '/getid3/getid3.php';
use Intervention\Image\ImageManagerStatic as Image;
use Intervention\Image\Exception\NotReadableException;
use WebPConvert\WebPConvert;
function genThumb($Source, $saveTo, $thumbname, $postion, $cover = false, $thumbsizes = CATICON_SIZES, $x = 0, $y = 0)
{
    global $RootPath;
    $thumbformat = (THUMB_FORMAT == 'webp') ? 'png' : THUMB_FORMAT;
    $appsizes = explode(',', $thumbsizes);
    foreach ($appsizes as $wh) {
        $Imgwh = explode('x', $wh);
        $ImgDir =  $saveTo . $wh;
        if (!is_dir($ImgDir))
            mkdir($ImgDir);
        if ($postion != false) {
            if ($wh == PREVIEW_THUMB || $wh == MP3TAG_COVER) {
                try {
                    if ($wh == MP3TAG_COVER && $cover == true) {
                        Image::make($Source)->resize($Imgwh[0], $Imgwh[1])->insert($RootPath . '/assets/images/mp3watermark.png', $postion, $x, $y)->save($ImgDir . '/' . 'cover_' . $thumbname . '.jpg', THUMB_QUALITY);
                    }
                    Image::make($Source)->resize($Imgwh[0], $Imgwh[1])->insert($RootPath . '/assets/images/watermark.png', $postion, $x, $y)->save($ImgDir . '/' . $thumbname . '.' . $thumbformat, THUMB_QUALITY);
                } catch (NotReadableException $e) {
                    return false;
                }
            } else {
                try {
                    Image::make($Source)->resize($Imgwh[0], $Imgwh[1])->save($ImgDir . '/' . $thumbname . '.' . $thumbformat, THUMB_QUALITY);
                } catch (NotReadableException $e) {
                    return false;
                }
            }
        } else {
            if ($wh == MP3TAG_COVER || $wh == PREVIEW_THUMB) {
                try {
                    if ($wh == MP3TAG_COVER && $cover == true) {
                        Image::make($Source)->resize($Imgwh[0], $Imgwh[1])->save($ImgDir . '/cover_' . $thumbname . '.jpg', THUMB_QUALITY);
                    }
                    Image::make($Source)->resize($Imgwh[0], $Imgwh[1])->save($ImgDir . '/' . $thumbname . '.' . $thumbformat, THUMB_QUALITY);
                } catch (NotReadableException $e) {
                    return false;
                }
            } else {
                try {
                    Image::make($Source)->resize($Imgwh[0], $Imgwh[1])->save($ImgDir . '/' . $thumbname . '.' . $thumbformat, THUMB_QUALITY);
                } catch (NotReadableException $e) {
                    return false;
                }
            }
        }
        if (THUMB_FORMAT == 'webp') {
            WebPConvert::convert($ImgDir . '/' . $thumbname . '.' . $thumbformat, $ImgDir . '/' . $thumbname . '.webp', []);
            unlink($ImgDir . '/' . $thumbname . '.' . $thumbformat);
        }
    }

    return true;
}
function WriteTag($Filename, $cover, $data = array(), $remove_other_tags = true)
{
    if (file_exists($Filename)) {
        $TaggingFormat = 'UTF-8';
        $TagFormatsToWrite = array('id3v1', 'id3v2.4', 'ape'); //array('id3v2.4','id3v2.3','id3v2.2','ape');
        $getID3 = new getID3;
        $getID3->setOption(array('encoding' => $TaggingFormat));
        getid3_lib::IncludeDependency(GETID3_INCLUDEPATH . 'write.php', __FILE__, true);
        $tagwriter = new getid3_writetags;
        $tagwriter->filename       = $Filename;
        $tagwriter->tagformats     = $TagFormatsToWrite;
        $tagwriter->overwrite_tags = true;
        $tagwriter->tag_encoding   = $TaggingFormat;
        $tagwriter->remove_other_tags = $remove_other_tags;

        $commonkeysarray = array('Title', 'Artist', 'Album', 'Year', 'Comment');
        foreach ($commonkeysarray as $key) {
            if (!empty($data[$key])) {
                $TagData[strtolower($key)][] = $data[$key];
            }
        }

        if (file_exists($cover)) {
            if (in_array('id3v2.4', $tagwriter->tagformats) || in_array('id3v2.3', $tagwriter->tagformats) || in_array('id3v2.2', $tagwriter->tagformats)) {
                if ($fd = @fopen($cover, 'rb')) {
                    $APICdata = fread($fd, filesize($cover));
                    fclose($fd);
                    list($APIC_width, $APIC_height, $APIC_imageTypeID) = GetImageSize($cover);
                    $imagetypes = array(1 => 'gif', 2 => 'jpeg', 3 => 'png');
                    if (isset($imagetypes[$APIC_imageTypeID])) {
                        $TagData['attached_picture'][0]['data']          = $APICdata;
                        $TagData['attached_picture'][0]['picturetypeid'] = $APIC_imageTypeID;
                        $TagData['attached_picture'][0]['description']   = basename($cover);
                        $TagData['attached_picture'][0]['mime']          = 'image/' . $imagetypes[$APIC_imageTypeID];
                    }
                }
            }
        }
        $tagwriter->tag_data = $TagData;
        if ($tagwriter->WriteTags()) {
            return true;
        }
        // if ($tagwriter->WriteTags()) {
        // 	$warning =  'Successfully wrote tags<BR>';
        // 	if (!empty($tagwriter->warnings)) {
        // 		$warning.= 'There were some warnings:<blockquote style="background-color: #FFCC33; padding: 10px;">'.implode('<br><br>', $tagwriter->warnings).'</div>';
        // 	}
        //     return $warning;
        // } else {
        // 	return 'Failed to write tags!<div style="background-color: #FF9999; padding: 10px;">'.implode('<br><br>', $tagwriter->errors).'</div>';
        // }


    }
    return false;
}


function getDuration($filename)
{
    $getID3 = new getID3;
    $ThisFileInfo = $getID3->analyze($filename);
    return gmdate("i:s", @$ThisFileInfo['playtime_seconds']);
}

function genSlug($slug, $id = '', $type = true)
{
    global $db;
    $slug = pathinfo($slug, PATHINFO_FILENAME);
    $slug = slug($slug);

    if ($id) {
        $db->where('id', $id, '!=');
    }
    $db->where('slug', $slug);
    if ($type == true) {
        $checkExists =  $db->has(TABLE_FILES);
    } else {
        $checkExists =   $db->has(TABLE_CAT);
    }

    if ($checkExists) {
        return genSlug($slug . '-' . rand(1, 9), $id, $type);
    }

    return $slug;
}

function genArtist($str)
{

    global $db;
    $artist = explode(',', $str);
    array_filter($artist);
    $ids = array();
    foreach ($artist as $ar) {
        $name = trim($ar);
        if ($name) {
            $slug = slug($name);
            $check = $db->where('slug', $slug)->has('artist');
            if ($check != true) {
                $id = $db->insert('artist', ['name' => $name, 'slug' => $slug, 'thumb' => '', 'status' => 1, 'created_at' => $db->now()]);
                array_push($ids, $id);
            }
        }
    }
    return $ids;
}

?>