<?php

/**
 * @author Pratik Dev <webmaster.pratik@gmail.com>
 */
header('Content-Type: application/json; charset=utf-8');
require_once '../config/init.php';
$currentAction = Input('submit');
if ($currentAction == 'list') {
    $searchValue = dtsValue();
    if ($searchValue) {
        $db->where('name', '%' . $searchValue . '%', 'LIKE');
    }
    if (InputArray('order')) {
        $column = dtOrderby();
        if ($column == 2)
            $db->orderBy('name', dtOrderby(false));
        else
            $db->orderBy('id', dtOrderby(false));
    } else {
        $db->orderBy('id');
    }
    if (Input('length') != -1) {
        $arists = $db->withTotalCount()->get('artist', array(dtlimit(), dtlimit(false)));
    } else {
        $arists = $db->withTotalCount()->get('artist');
    }

    $numRows = $db->totalCount;
    $data = array();
    $size = explode(',', CATICON_SIZES);
    foreach ($arists as $ar) {
        if ($ar['thumb'] != "") {
            $thumb = '<img class="border border-dark" src="../../upload_file/artistthumb/' . $size[0] . '/' . $ar['thumb'] . '" alt="Icon" width="60" height="60">';
        } else {
            $thumb = '';
        }
        $row = array();
        $row[] = $ar['id'];
        $row[] = $thumb;
        $row[] = $ar['name'];
        $row[] = ($ar['status'] == true) ? '<span id="' . $ar['id'] . '" class="status btn btn-success btn btn-sm">Active</span>' : '<span id="' . $ar['id'] . '" class="status btn btn-warning btn-sm">Block</span>';
        $row[] = '<button type="button" name="edit" id="' . $ar["id"] . '" class="edit btn btn-success btn-sm mr-2"><i class="fas fa-edit"></i></button><button type="button" name="delete" id="' . $ar["id"] . '" class="delete btn btn-danger btn-sm"><i class="fas fa-trash-alt"></i></button>';
        $data[] = $row;
    }
    $output = array(
        "draw"                =>    intval(Input('draw')),
        "recordsTotal"      =>  $numRows,
        "recordsFiltered"     =>     $numRows,
        "data"                =>   $data
    );
    echo json_encode($output);
} else if ($currentAction == 'delete') {

    $id = Input('id');

    $art = $db->where('id', $id)->getOne('artist');
    if (!$art) {
        $data = [
            'status' => 0,
            'message' => 'Delete Unsucessfuly'
        ];
        exit;
    }
    $thumbnailname = $art['thumb'];
    if ($thumbnailname) {
        $saveTo = $RootPath . '/upload_file/artistthumb';
        $appsizes = explode(',', CATICON_SIZES);
        foreach ($appsizes as $wh) {
            $Imgwh = explode('x', $wh);
            $ImgDir = $saveTo . '/' . $wh;
            if (file_exists($ImgDir . '/' . $thumbnailname))
                unlink($ImgDir . '/' . $thumbnailname);
        }
        $newthumbname = pathinfo($thumbnailname, PATHINFO_FILENAME);
        $catCover = $RootPath . '/upload_file/artistthumb/' . MP3TAG_COVER . '/' . $newthumbname . '.jpg';
        if (file_exists($catCover)) {
            unlink($catCover);
        }
    }

    if ($db->where('id', Input('id'))->delete('artist')) {
        $data = [
            'status' => 1,
            'message' => 'Deleted Sucessfuly'
        ];
    } else {
        $data = [
            'status' => 0,
            'message' => 'Delete Unsucessfuly'
        ];
    }

    echo json_encode($data);
} else if ($currentAction == 'getOne') {
    $db->where('id', Input('id'));
    $catInfo = $db->getOne('artist');
    $size = explode(',', CATICON_SIZES);
    if ($catInfo['thumb'] != '') {
        $thumbnail = '../../upload_file/artistthumb/' . $size[0] . '/' . $catInfo['thumb'];
    } else {
        $thumbnail = '';
    }
    $data = [
        'id' => $catInfo['id'],
        'name' => $catInfo['name'],
        'thumb' => $thumbnail,
        'status' => $catInfo['status'],
        'slug' => $catInfo['slug'],
        'meta_title' => $catInfo['meta_title'],
        'meta_keyw' => $catInfo['meta_keyw'],
        'meta_des' =>  $catInfo['meta_des'],
        'added_home' => $catInfo['added_home']

    ];
    echo json_encode($data);
} else if ($currentAction == 'create' || $currentAction == 'edit') {
    $name = Input('name');
    $status = Input('status') ? 1 : 0;
    $slug =  slug($name);
    $action = $currentAction;
    $thumbnailname = '';
    if (!$name) {
        $data = [
            'status' => 0,
            'message' => 'Artist Name can not be empty'
        ];
        echo json_encode($data);
        exit;
    }
    if (Input('id'))
        $db->where('id', Input('id'), '!=');
    if ($db->where('slug', $slug)->has('artist')) {
        $data = [
            'status' => 0,
            'message' => 'Artist Already exists'
        ];
        echo json_encode($data);
        exit;
    }

    if ($action == 'create') {
        $data = [
            'name' => $name,
            'slug' => $slug,
            'status' => $status,
            'meta_title' => Input('meta_title'),
            'meta_keyw' => Input('meta_keyw'),
            'meta_des' => Input('meta_des'),
            'added_home' => Input('added_home') ? 1 : 0,
            'created_at' => $db->now()
        ];
        $id = $db->insert('artist', $data);
    } else {
        if (!Input('id')) {
            $data = [
                'status' => 0,
                'message' => 'Artist Id Missing'
            ];
        }

        $data = [
            'name' => $name,
            'slug' => $slug,
            'status' => $status,
            'meta_title' => Input('meta_title'),
            'meta_keyw' => Input('meta_keyw'),
            'meta_des' => Input('meta_des'),
            'added_home' => Input('added_home') ? 1 : 0,
            'created_at' => $db->now()
        ];
        if ($db->where('id', Input('id'))->update('artist', $data)) {
            $id = Input('id');
        }
    }

    if ($id) {
        $artist = $db->where('id', $id)->getOne('artist');
        $w_pos = Input('w_pos') ? Input('w_pos') : 'top-left';
        $saveToThumb = $RootPath . '/upload_file/artistthumb/';
        $thumbfrom = Input('thumbfrom');
        if ($thumbfrom == 'EXTERNAL_LINK') {
            $thumbURL = trim(Input('thumb_url'));
            $thumb_ext = pathinfo($thumbURL, PATHINFO_EXTENSION);

            if ($thumbURL && $thumb_ext) {
                $tmp_thumbname = 'tmp_thumb.' . $thumb_ext;
                $thumbnailname = $artist['thumb'] ? pathinfo($artist['thumb'], PATHINFO_FILENAME) : uniqid('thumb_');

                $saveThumb = $RootPath . '/upload_file/artistthumb/' . $tmp_thumbname;
                if (urlCopy($thumbURL, $saveThumb)) {
                    genThumb($saveThumb, $saveToThumb, $thumbnailname, $w_pos);
                    unlink($saveThumb);
                }
            }
        } else {
            if ($_FILES['thumb']['name']) {
                $thumbnailname = $artist['thumb'] ? pathinfo($artist['thumb'], PATHINFO_FILENAME) : uniqid('thumb_');
                genThumb($_FILES['thumb']['tmp_name'], $saveToThumb, $thumbnailname, $w_pos);
            }
        }

        if ($thumbnailname) {
            $db->where('id', $id)->update('artist', ['thumb' => $thumbnailname ? $thumbnailname . '.' . THUMB_FORMAT : $artist['thumb']]);
        }



        echo json_encode([
            'status' => 1,
            'message' => 'Created/Update sucessfuly'
        ]);
    } else {
        echo json_encode([
            'status' => 0,
            'message' => 'Created Unsucessfuly'
        ]);
    }
} else if ($currentAction == "removethumb") {
    if ($id = InputArray('id')) {
        $art = $db->where('id', $id)->getOne('artist');
        $thumbnailname = $art['thumb'];
        if ($thumbnailname) {
            $saveTo = $RootPath . '/upload_file/artistthumb';
            $appsizes = explode(',', CATICON_SIZES);
            foreach ($appsizes as $wh) {
                $Imgwh = explode('x', $wh);
                $ImgDir = $saveTo . '/' . $wh;
                if (file_exists($ImgDir . '/' . $thumbnailname))
                    unlink($ImgDir . '/' . $thumbnailname);
            }
            $newthumbname = pathinfo($thumbnailname, PATHINFO_FILENAME);
            $catCover = $RootPath . '/upload_file/artistthumb/' . MP3TAG_COVER . '/' . pathinfo($art['thumb'], PATHINFO_FILENAME) . '.jpg';
            if (file_exists($catCover)) {
                unlink($catCover);
            }
        }
        $db->where('id', $id)->update('artist', ['thumb' => '']);
    }
    echo json_encode([
        'status' => 1,
        'message' => 'Thumbnail Removed'

    ]);
} elseif ($currentAction == "statusUpdater") {

    $id = Input('id');
    $status = $db->where('id', $id)->getValue('artist', 'status');

    if ($status == 1) {
        $data = ['status' => 0];
    } else {
        $data = ['status' => 1];
    }
    $db->where('id', $id)->update('artist', $data);
    echo json_encode([
        'status' => 1,
        'message' => 'Status Updated'

    ]);
} else if ($currentAction == "multipledelete") {
    $ids = InputArray('ids');
    if(!$ids){
        echo json_encode(['status'=>0,'message'=>'Sorry No item Selected']);
        exit;
    }
    $cnt = 0;
    foreach ($ids as $id) {
        if ($id) {
            $art = $db->where('id', $id)->getOne('artist');
            if (!$art) {
               continue;
            }
            $thumbnailname = $art['thumb'];
            if ($thumbnailname) {
                $saveTo = $RootPath . '/upload_file/artistthumb';
                $appsizes = explode(',', CATICON_SIZES);
                foreach ($appsizes as $wh) {
                    $Imgwh = explode('x', $wh);
                    $ImgDir = $saveTo . '/' . $wh;
                    if (file_exists($ImgDir . '/' . $thumbnailname))
                        unlink($ImgDir . '/' . $thumbnailname);
                }
                $newthumbname = pathinfo($thumbnailname, PATHINFO_FILENAME);
                $catCover = $RootPath . '/upload_file/artistthumb/' . MP3TAG_COVER . '/' . $newthumbname . '.jpg';
                if (file_exists($catCover)) {
                    unlink($catCover);
                }
            }

            if ($db->where('id', $id)->delete('artist')) {
                $cnt++;
            }
        }
    }

    echo json_encode(['status'=>1,'message'=>'Deleted Total: '.$cnt.' Items']);
}
