<?php
require_once $RootPath . '/config/upoad_func.php';

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

header("Content-Type: application/json");
$Action = filter_input(INPUT_GET, 'action', FILTER_SANITIZE_STRING);
if ($Action == "reportsong") {
    $errors = array();
    if ($isLogged) :
        $subject = filter_input(INPUT_POST, 'subject', FILTER_SANITIZE_STRING);
        $body = filter_input(INPUT_POST, 'body', FILTER_SANITIZE_STRING);
        $file_id = filter_input(INPUT_POST, 'file_id', FILTER_SANITIZE_STRING);

        if (empty($subject)) {
            array_push($errors, 'Please enter Subject');
        }
        if (empty($body)) {
            array_push($errors, 'Missing Body');
        }
        if (empty($file_id)) {
            array_push($errors, 'Missing File ID');
        }

        if (count($errors) == 0) {

            $id =  $db->insert('reports', [
                'subject' => 'Song Reported ID: ' . $file_id,
                'user_id' => $AuthUser['id'],
                'body' => 'Subject: ' . $subject . ' Message: ' . $body,
                'created_at' => $db->now(),
            ]);

            if ($id) {
                $status = 1;
                $message = 'Success';
            } else {
                $status = 0;
                $message = 'Failed';
            }
        } else {
            $status = 0;
            $message = $errors[0];
        }
    else :

        $status = 0;
        $message = "Login first";

    endif;
} else if ($Action == "deletesong") {
    $errors = array();
    if ($isLogged) {

        $id = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_STRING);

        if (empty($id)) {
            array_push($errors, 'Missing File ID');
        }

        if (count($errors) == 0) {

            $file = $db->where('id', $id)->getOne(TABLE_FILES);
            if (!$file) {
                echo json_encode([
                    'status' => 0,
                    'message' => 'Unable Delete File'

                ]);
                exit;
            }
            if ($file['user_id'] == $AuthUser['id']) {
                $db->where('id', $id)->update(TABLE_FILES, ['deleted_at' => $db->now()]);
                $status = 1;
                $message = "Song Deleted Successfuly";
            } else {
                $status = 0;
                $message = "Not Authorise";
            }
        } else {
            $status = 0;
            $message = $errors[0];
        }
    } else {

        $status = 0;
        $message = "Login first";
    }
} elseif ($Action == "addfavourite") {
    $errors = array();
    if ($isLogged) {

        $file_id = str_replace('file_', '', filter_input(INPUT_POST, 'id', FILTER_SANITIZE_STRING));

        if (empty($file_id)) {
            array_push($errors, 'Missing File ID');
        }

        if (count($errors) == 0) {
            $isFav = $db->where('file_id', $file_id)->where('user_id', $AuthUser['id'])->getOne('favourite', 'user_id');
            if (!$isFav) {
                $db->insert('favourite', ['file_id' => $file_id, 'user_id' => $AuthUser['id'], 'created_at' => $db->now()]);
                $status = 1;
                $message = "Successfuly Added to Favourite";
            } else {
                if ($isFav['user_id'] == $AuthUser['id']) {
                    $db->where('file_id', $file_id)->where('user_id', $AuthUser['id'])->delete('favourite');
                }
                $status = 1;
                $message = "Favourite Removed";
            }
        } else {
            $status = 0;
            $message = $errors[0];
        }
    } else {

        $status = 0;
        $message = "Login first";
    }
} else if ($Action == "editprofile") {

    if ($isLogged) {

        $errors = array();
        if (@$_FILES['avator']['name']) {

            $Source = $_FILES['avator']['tmp_name'];

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

            if (function_exists('finfo_open')) {
                $finfo = finfo_open(FILEINFO_MIME_TYPE);
                $mtype = finfo_file($finfo, $Source);
                finfo_close($finfo);
            } elseif (function_exists('mime_content_type')) {
                $mtype = mime_content_type($Source);
            }

            if (!in_array($mtype, ['image/jpg', 'image/jpeg', 'image/png'])) {
                array_push($errors, 'Please Select Validate Image');
            } else {
                try {
                    Image::make($Source)->resize(40, 40)->save($ImgDir1 . '/' . $AuthUser['user_name'] . '.jpg', THUMB_QUALITY);
                    Image::make($Source)->resize(150, 150)->save($ImgDir2 . '/' . $AuthUser['user_name'] . '.jpg', THUMB_QUALITY);
                } catch (NotReadableException $e) {
                    array_push($errors, 'Please Select Validate Image');
                }
            }
        }

        $fullname = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
        $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
        $phone = filter_input(INPUT_POST, 'phone', FILTER_SANITIZE_STRING);

        if (strlen($fullname) < 3  || strlen($fullname) >  20) {
            array_push($errors, 'Please enter validate name Min 4 - 20 character!');
        }

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            array_push($errors, 'Please enter validate Email!');
        }
        if ($phone) {
            if (strlen($phone) >= 13 || strlen($phone) < 10) {
                array_push($errors, 'Please enter validate Phone!');
            }
        }

        if (count($errors) == 0) {
            $db->where('id', $AuthUser['id'])->update('users', [
                'name' => $fullname,
                'email' => $email,
                'mobile' => $phone
            ]);

            $status = 1;
            $message = "Successfuly Updated";
        } else {
            $status = 0;
            $message = $errors[0];
        }
    } else {
        $status = 0;
        $message = 'Please Login first';
    }
} else if ($Action == "editsong") {
    if ($isLogged) {
        $file_id = filter_input(INPUT_POST, 'file_id', FILTER_SANITIZE_STRING);
        if (!$fileinfo = $db->where('id', $file_id)->where('user_id', $AuthUser['id'])->getOne(TABLE_FILES)) {
            echo json_encode(['status' => 0, 'message' => 'File not exists']);
            exit;
        }

        $category = $db->where('id', $fileinfo['cid'])->getOne(TABLE_CAT);
        if (!$category) {
            echo json_encode(['status' => 0, 'message' => 'Category Does not exists']);
            exit;
        }

        $filename = filter_input(INPUT_POST, 'file_name', FILTER_SANITIZE_STRING);

        if (!$filename) {
            echo json_encode(['status' => 0, 'message' => 'Title can not be empty']);
            exit;
        }

        $artist = $fileinfo['artist'];
        // $artists = $_POST['artist'];
        // if ($artist) {
        //     $artist = filter_var_array($artists, FILTER_SANITIZE_STRING);
        //     $artist = @implode(',', $artist);
        // }

        $thumb =    @$_FILES['thumb']['tmp_name'];
        $tagwriter = false;

        $w_pos = 'top-left';
        $saveThumbTo = $RootPath . '/' . $category['folder'];
        $thumbname = $fileinfo['thumb'] ? pathinfo($fileinfo['thumb'], PATHINFO_FILENAME) : uniqid('thumb_');

        if ($thumb) {
            $thumbExt = @pathinfo($_FILES['thumb']['name'], PATHINFO_EXTENSION);
            $thumbType = @checkMimeType($thumb);
            if ($thumbType == "image/jpeg" || in_array($thumbExt, ['jpg', 'jpeg', 'png'])) {
                genThumb($thumb, $saveThumbTo, $thumbname, $w_pos, true, FILE_THUMB_SIZES);
            }
        }

        $extension = pathinfo($fileinfo['dname'], PATHINFO_EXTENSION);
        if (!in_array($extension, $allowExt)) {
            $extension  = '';
        }

        $ogfilename = $extension ? $fileinfo['dname'] : $fileinfo['dname'] . '.' . $fileinfo['ext'];
        $path = $RootPath . '/' . $category['folder'] . $ogfilename;

        if (pathinfo($ogfilename, PATHINFO_EXTENSION) == 'mp3' && file_exists($path)) {

            $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;
            }
        }

        $db->where('id', $file_id)->where('user_id', $AuthUser['id'])->update(
            TABLE_FILES,
            [
                'name' => $filename,
                'artist' => $artist,
                'thumb' => $thumbname ? $thumbname . '.' . THUMB_FORMAT : '',
            ]
        );

        $status = 1;
        $message = "Successfuly Updated!";
    } else {
        $status = 0;
        $message = "Please Login first";
    }
} else if ($Action == "uploadsong") {
    if ($isLogged) {
        $errors = array();
        $filename = filter_input(INPUT_POST, 'file_name', FILTER_SANITIZE_STRING);
        $cid = filter_input(INPUT_POST, 'category_id', FILTER_SANITIZE_STRING);
        $category = $db->where('id', $cid)->where('subcate', 0)->getOne(TABLE_CAT);
        $upload = false;


        $artist = '';
        if (isset($_POST['artist'])) {
            $artists = $_POST['artist'];
            foreach ($artists as $ar) {
                $fartist = filter_var($ar, FILTER_SANITIZE_STRING);
                if ($fartist) {
                    $artist .= trim($fartist) . ',';
                }
            }
            $artist = trim($artist, ',');
        }

        $file = $_FILES['file']['tmp_name'];
         
        $fileExt = '';
        $fileType = '';
        
        if ($file) {
            $fileExt =  @pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
            $fileType = @checkMimeType($file);
        }

        

        $uploadFileLimit = (1024 * 1024) * USER_MAX_UPLOAD; //20MB
         
        if (!$filename) {
            array_push($errors, 'Please Enter Valid Title');
        }

        if (!$file) {
            array_push($errors, 'Please Select Audio File');
        }


        if (!$category) {
            array_push($errors, 'Category Not Found');
        }

       

        if (!$fileType == "audio/mp3" && strtoupper($fileExt) != "mp3") {
            array_push($errors, 'Please Upload mp3 Audio');
        }

        
        if (@$_FILES['file']['size'] > $uploadFileLimit) {
            array_push($errors, 'Please Reupload Smaller File Size');
        }

       
        if (count($errors) == 0) {

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

            if (!is_dir($mkdir)) {
                mkdir($mkdir, 0777, true);
            }

            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 . uniqid('file_') . '.' . $extension;
                if (move_uploaded_file($_FILES['file']['tmp_name'], $path))
                    $upload = true;
            }

            if (!$upload) {
                echo json_encode(['status' => $status, 'message' => 'File Does not upload']);
                exit;
            }

            $w_pos = 'top-left';
            $saveThumbTo = $RootPath . '/' . $category['folder'];

             
            $data = [
                'name' => $filename,
                'dname' => basename($path),
                'cid' => $cid,
                'user_id' => $AuthUser['id'],
                'slug' => genSlug($filename),
                'ext' => $extension,
                'size' => filesize($path),
                'duration' => getDuration($path),
                 'des' => '',
                'download' => 0,
                'pos' =>  0,
                'meta_title' => '',
                'meta_keyw' => '',
                'meta_des' => '',
                'newtag' => 1,
                'status' =>  1,
                'trend' => 0,
                'approved_at' => (USER_UPLOAD_APPROVE == "ON") ? $db->now() : NULL,
                'created_at' => $db->now()
            ];

            if ($id  = $db->insert(TABLE_FILES, $data)) {

                $parentids = array_filter(explode('/', $category['folder']));
                array_shift($parentids);
                if ($parentids) {
                    $db->where('id', $parentids, 'IN')->update(TABLE_CAT, ['totalitem' => $db->inc(1)]);
                }

                $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
                );

               
             

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

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

                $status = 1;
                $message = "Successfuly Uploaded!";
            } else {
                $status = 0;
                $message = "File Not Uploaded!";
            }
        } else {
            $status = 0;
            $message = $errors[0];
        }
    } else {

        $status = 0;
        $message = "Please login first!";
    }
} elseif ($Action == 'categorylist') {
    if ($q = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_STRING))
        $db->where('name', '%' . $q . '%', 'LIKE');

    $db->where('subcate', 0);
    $data = $db->orderBy('name')->get(TABLE_CAT, null, 'id,name as text');
    echo json_encode(['results' => $data]);
    exit;
} else {


    $status = 0;
    $message = "No Method Found";
}

echo json_encode(['status' => $status, 'message' => $message]);
