<?php
/**
 * Game Controller
 */
class Game extends Controller
{
    /**
     * Process
     */
    public function process()
    {    

		$AuthUser		= $this->getVariable("AuthUser");
		$Route			= $this->getVariable("Route");
 
        // Config
        $Config['btn']  = 'game';
        $Config['nav']  = 'games';

        if (isset($Route->params->id)) {
            $Listing    = $this->db->from('posts')->where('id',$Route->params->id,'=')->first();
            if(empty($Listing['id'])) {
                header('location:'.APP.'/404');
            }
            $Selected   = array();
            $SelectCategories = $this->db->from('posts_category')->where('post_id', $Listing['id'])->all();
            foreach ($SelectCategories as $SelectCategory) {
                $Selected[] = $SelectCategory['category_id'];
            }
        }
        $Categories         = $this->db->from('categories')->orderby('name','ASC')->all();

        $TabNav = array(
            'upload'    =>  $this->translate('Upload game'),
            'remote'    =>  $this->translate('Remote add'),
            'fetch'     =>  $this->translate('Fetch game')
        ); 
        $this->setVariable('Listing',isset($Listing) ? $Listing : null); 
        $this->setVariable('Selected',isset($Selected) ? $Selected : null); 
        $this->setVariable('Config', $Config);  
        $this->setVariable('TabNav', $TabNav);  
        $this->setVariable('Categories', $Categories);  

        if(Input::cleaner((isset($_POST['_ACTION']) ? $_POST['_ACTION'] : null)) == 'save' AND empty($Listing['id'])) {
            $this->save();
        } elseif(Input::cleaner((isset($_POST['_ACTION']) ? $_POST['_ACTION'] : null)) == 'save' AND isset($Listing['id'])) {
            $this->update();
        }

        $this->view("game", "admin");
    }

    public function save() { 
        if (empty($Notify)) {  
            $ImageName      = randomcode();
            $SourceName     = randomcode();

            if(!empty($_POST['image_url'])) {
                $path_image = UPLOADPATH . '/temp/' . randomcode() . '.png';
                downloader($_POST['image_url'], $path_image);
                $_FILES['image'] = $path_image;
            }
            if(isset($_FILES['image']) AND $_FILES['image']['name']) {
                $image      = uploader($_FILES['image'],$ImageName,UPLOADPATH.'/'.GAME_FOLDER.'/',GAME_X.','.GAME_Y,'png');
                uploader($_FILES['image'],$ImageName,UPLOADPATH.'/'.GAME_FOLDER.'/',GAME_X.','.GAME_Y,'webp');
                uploader($_FILES['image'],'thumb-'.$ImageName,UPLOADPATH.'/'.GAME_FOLDER.'/',GAME_THUMB_X.','.GAME_THUMB_Y,'png');
                uploader($_FILES['image'],'thumb-'.$ImageName,UPLOADPATH.'/'.GAME_FOLDER.'/',GAME_THUMB_X.','.GAME_THUMB_Y,'webp');
                unlink($path_image);
            }

            if(isset($_FILES['file']) AND $_POST['type'] == 'upload'){
                if (preg_match('/[.](zip)$/', $_FILES['file']['name'])) {

                    if (!file_exists(UPLOADPATH . '/source/')) {
                        mkdir(UPLOADPATH . '/source/', 0777, true);
                    }
                    move_uploaded_file($_FILES['file']['tmp_name'],UPLOADPATH . '/source/'.$SourceName.'.zip');

                    $zip = new ZipArchive;
                    $res = $zip->open(UPLOADPATH . '/source/'.$SourceName.'.zip');
                    if ($res === TRUE) {
                        $zip->extractTo(UPLOADPATH . '/source/'.$SourceName);
                        $zip->close();
                        unlink(UPLOADPATH . '/source/'.$SourceName.'.zip');
                        $SourceLink = $SourceName;
                    }

                }
            }

            if(isset($_POST['self'])) {
                $self = Input::seo($_POST['self']);
            } else {
                $self = Input::seo($_POST['title']);
            }

            $dataarray          = array(
                "type"              => Input::cleaner($_POST['type']),
                "title"             => Input::cleaner($_POST['title']),
                "self"              => $self,
                "image"             => isset($image) ? $image : null,
                "description"       => Input::cleaner($_POST['description']),
                "control"           => Input::cleaner($_POST['control']),
                "source"            => isset($SourceLink) ? $SourceLink : null,
                "keywords"          => Input::cleaner($_POST['keywords']),
                "meta_title"        => Input::cleaner($_POST['meta_title']),
                "meta_description"  => Input::cleaner($_POST['meta_description']),
                "resolution"        => (isset($_POST['width']) ? $_POST['width'].'x'.$_POST['height'] : null),
                "view"              => Input::cleaner($_POST['view'],'0'),
                "featured"          => (int)Input::cleaner($_POST['featured'],'2'),
                "comment"           => (int)Input::cleaner($_POST['comment'],'2'),
                "member"            => (int)Input::cleaner($_POST['member'],'2'),
                "status"            => (int)Input::cleaner($_POST['status'],'2'),
                "created"           => date('Y-m-d H:i:s')
            );   
            $this->db->insert('posts')->set($dataarray); 

            $post_id     = $this->db->lastId(); 

            // Genres
            if (count($_POST['categories']) >= '1') {
                for ($i = 0; $i < count($_POST['categories']); $i++) {
                    if (Input::cleaner($_POST['categories'][$i])) {
                        $dataarray = array(
                            "category_id"   => Input::cleaner($_POST['categories'][$i]),
                            "post_id"       => $post_id
                        );
                        $this->db->insert('posts_category')->set($dataarray);
                    }
                }
            }
            removefolder(PATH.'/cache');
            $Notify['type']     = 'success';
            $Notify['text']     = $this->translate('Action completed successfully'); 
            $this->notify($Notify);
            header("location: ".APP.'/admin/games');
        }else{ 
            $this->notify($Notify);
        }
        return $this;
    }

    public function update() {
        $Listing        = $this->getVariable("Listing");       
        $Selected       = $this->getVariable("Selected");       
        if (empty($Notify)) { 

            $ImageName      = randomcode();
            $SourceName     = randomcode();
            if(!empty($_POST['image_url'])) {
                if (!file_exists(UPLOADPATH . '/temp/')) {
                    mkdir(UPLOADPATH . '/temp/', 0777, true);
                }
                $path_image = UPLOADPATH . '/temp/' . randomcode() . '.png';
                downloader($_POST['image_url'], $path_image);
                $_FILES['image'] = $path_image;
            }
            if(isset($_FILES['image']) AND $_FILES['image']['name']) {
                unlink(UPLOADPATH . '/'.GAME_FOLDER.'/'.$Listing['image']);
                unlink(UPLOADPATH . '/'.GAME_FOLDER.'/thumb-'.$Listing['image']);
                unlink(UPLOADPATH . '/'.GAME_FOLDER.'/'.webper($Listing['image']));
                unlink(UPLOADPATH . '/'.GAME_FOLDER.'/thumb-'.webper($Listing['image']));

                $image      = uploader($_FILES['image'],$ImageName,UPLOADPATH.'/'.GAME_FOLDER.'/',GAME_X.','.GAME_Y,'png');
                uploader($_FILES['image'],$ImageName,UPLOADPATH.'/'.GAME_FOLDER.'/',GAME_X.','.GAME_Y,'webp');
                uploader($_FILES['image'],'thumb-'.$ImageName,UPLOADPATH.'/'.GAME_FOLDER.'/',GAME_THUMB_X.','.GAME_THUMB_Y,'png');
                uploader($_FILES['image'],'thumb-'.$ImageName,UPLOADPATH.'/'.GAME_FOLDER.'/',GAME_THUMB_X.','.GAME_THUMB_Y,'webp');
                unlink($path_image);
            }

            if(isset($_FILES['file']) AND $_POST['type'] == 'upload'){
                if (preg_match('/[.](zip)$/', $_FILES['file']['name'])) {

                    if (!file_exists(UPLOADPATH . '/source/')) {
                        mkdir(UPLOADPATH . '/source/', 0777, true);
                    }
                    move_uploaded_file($_FILES['file']['tmp_name'],UPLOADPATH . '/source/'.$SourceName.'.zip');
                    removefolder(UPLOADPATH . '/source/'.$Listing['source']);

                    $zip = new ZipArchive;
                    $res = $zip->open(UPLOADPATH . '/source/'.$SourceName.'.zip');
                    if ($res === TRUE) {
                        $zip->extractTo(UPLOADPATH . '/source/'.$SourceName);
                        $zip->close();
                        unlink(UPLOADPATH . '/source/'.$SourceName.'.zip');
                        $SourceLink = $SourceName;
                    }

                }
            } elseif($_POST['type'] == 'remote') {
                $SourceLink = Input::cleaner($_POST['source']);
            }

            if(isset($_POST['self'])) {
                $self = Input::seo($_POST['self']);
            } else {
                $self = Input::seo($_POST['title']);
            }
            $dataarray          = array(
                "type"              => Input::cleaner($_POST['type']),
                "title"             => Input::cleaner($_POST['title']),
                "self"              => $self,
                "image"             => isset($image) ? $image : $Listing['image'],
                "description"       => Input::cleaner($_POST['description']),
                "control"           => Input::cleaner($_POST['control']),
                "source"            => isset($SourceLink) ? $SourceLink : $Listing['source'],
                "keywords"          => Input::cleaner($_POST['keywords']),
                "meta_title"        => Input::cleaner($_POST['meta_title']),
                "meta_description"  => Input::cleaner($_POST['meta_description']),
                "resolution"        => (isset($_POST['width']) ? $_POST['width'].'x'.$_POST['height'] : null),
                "view"              => Input::cleaner($_POST['view'],'0'),
                "featured"          => (int)Input::cleaner($_POST['featured'],'2'),
                "comment"           => (int)Input::cleaner($_POST['comment'],'2'),
                "member"            => (int)Input::cleaner($_POST['member'],'2'),
                "status"            => (int)Input::cleaner($_POST['status'],'2')
            );   
            $this->db->update('posts')->where('id',$Listing['id'])->set($dataarray);

            // Genres
            if (count($_POST['categories']) >= '1') { 
                foreach ($Selected as $Key => $Value) {  
                    if (!in_array($Value, $_POST['categories'])) {  
                        $this->db->delete('posts_category')->where('category_id', $Value, '=')->where('post_id',$Listing['id'],'=')->done();
                    }
                }
                for ($i = 0; $i < count($_POST['categories']); $i++) {
                    if (!in_array($_POST['categories'][$i], $Selected)) {
                        $dataarray = array(
                            "category_id"   => Input::cleaner($_POST['categories'][$i]),
                            "post_id"       => $Listing['id']
                        );
                        $this->db->insert('posts_category')->set($dataarray);
                    }
                }
            } 

            $Notify['type']     = 'success';
            $Notify['text']     = $this->translate('Action completed successfully'); 
            $this->notify($Notify);
            removefolder(PATH.'/cache');
            header("location: ".APP.'/admin/game/'.$Listing['id']);
        }else{ 
            $this->notify($Notify);
        } 
        return $this;
    }
}