<?php

namespace App\Repositories;
use App\Interfaces\PhotoRepositoryInterface;
use App\Models\Game;
use Illuminate\Mail\Mailer;

/**
*
*@author: Tiamiyu waliu kola
*@website : www.crea8social.com
*/
class GameRepository
{
    public function __construct(
        Game $game,
        PhotoRepositoryInterface $photoRepositoryInterface,
        Mailer $mailer,
        NotificationRepository $notificationRepository
    )
    {
        $this->model = $game;
        $this->photoRepository = $photoRepositoryInterface;
        $this->mailer = $mailer;
        $this->notification = $notificationRepository;
    }

    /**
     * Method to add games
     *
     * @param array $val
     * @param boolean $isAdmin
     * @return bool
     */
    public function add($val, $isAdmin = false)
    {
        $expected = [
            'title',
            'description',
            'category',
            'content',
            'approved' => (\Config::get('game-need-confirm')) ? 0 : 1,
            'verified' => 0
        ];

        /**
         * @var $title
         * @var $description
         * @var $category
         * @var $approved
         * @var $verified
         * @var $content
         */
        extract(array_merge($expected, $val));

        if ($isAdmin) {
            $approved = 1;
        }

        $slug = toAscii($title);

        if (!empty($title) and !empty($content)) {
            $game = $this->model->newInstance();
            $game->title = sanitizeText($title, 130);
            $game->description = sanitizeText($description);
            $game->category = $category;
            $game->user_id = \Auth::user()->id;
            $game->verified = $verified;
            $game->slug = '';
            $game->approved = $approved;
            $game->iframe_content = $content;
            $game->save();

            $game->slug = $game->id;
            $game->save();
            return $game;
        }

        return false;
    }

    public function save($val, $game, $isAdmin = false)
    {
        $expected = [
            'title',
            'description',
            'category',
            'content',
            'approved' => (\Config::get('game-need-confirm')) ? 0 : 1,
            'verified' => 0,
            'info' => []
        ];

        /**
         * @var $title
         * @var $description
         * @var $category
         * @var $approved
         * @var $verified
         * @var $content
         * @var $info
         */
        extract(array_merge($expected, $val));

        if ($isAdmin or \Auth::user()->isAdmin()) {
            $approved = 1;
        }


        if (!empty($title) and !empty($content)) {

            $game->title = sanitizeText($title, 130);

            $game->description = sanitizeText($description);
            $game->category = $category;
            $game->user_id = \Auth::user()->id;
            $game->verified = $verified;
            $game->approved = $approved;
            $game->iframe_content = $content;
            $game->info = serialize($info);
            $game->save();

            return $game;
        }

        return false;
    }

    public function exists($title)
    {
        return $this->model->where('title', '=', $title)
            ->orWhere('id', '=', $title)
            ->first();
    }

    public function seperateExists($title, $id)
    {
        return $this->model->where('slug', '=', $title)->Where('id', '!=', $id)->first();
    }

    public function get($id)
    {
        return $this->exists($id);
    }

    public function approve($id)
    {
        $game = $this->get($id);

        if($game) {
            $game->approved = 1;
            $game->save();

            //send notification to owner
            $user = $game->user;
            $this->notification->send($user->id, [
               'path' => 'notification.game.approved',
                'game' => $game
            ]);

            try{
                $this->mailer->queue('emails.game.approved', [
                    'fullname' => $user->fullname,
                    'username' => $user->username,
                    'gameLink' => $game->present()->url()
                ], function($mail) use($user) {
                    $mail->to($user->email_address, $user->fullname)
                        ->subject(trans('mail.game-approved', ['fullname' => $user->fullname]));
                });
            } catch(\Exception $e) {

            }
        }
    }

    public function listAll($limit = 10, $cat = null)
    {
         $games = $this->model->with('cat', 'user', 'likes');

         if ($cat) {
             $games = $games->where('category', '=', $cat);
         }

         return $games = $games->where('approved', '=', 1)->orderBy('id', 'desc')->paginate($limit);
    }

    public function suggest($limit)
    {
        return $this->listAll($limit);
    }

    public function adminList($limit = 10, $cat = null)
    {
        $games = $this->model->with('cat', 'user', 'likes');

        if ($cat) {
            $games = $games->where('category', '=', $cat);
        }

        return $games = $games->orderBy('id', 'desc')->paginate($limit);
    }

    public function myList($limit = 10)
    {
        return $this->model->with('cat', 'user', 'likes')->where('user_id', '=', \Auth::user()->id)->orderBy('id', 'desc')->paginate($limit);
    }

    public function search($term, $limit = 10)
    {
        $games = $this->model->with('cat', 'user', 'likes');

        $games = $games->where(function($games) use($term) {
             $games->where('title', 'LIKE', '%'.$term.'%')
                 ->orWhere('description', 'LIKE', '%'.$term.'%');
        });

        return $games = $games->where('approved', '=', 1)->orderBy('id', 'desc')->paginate($limit);

    }

    public function delete($id)
    {
        $game = $this->get($id);

        if ($game) {
            $game->delete();
            foreach([
                        'App\\Repositories\\LikeRepository',
                    ] as $object) {
                app($object)->deleteAllByGame($id);
            }
        }
    }

    public function changePhoto($image, $game)
    {
        $user = (empty($user)) ? \Auth::user() : $user;
        $image = $this->photoRepository->upload($image, [
            'path' => 'users/'.$user->id,
            'slug' => 'games-'.$game->id,
            'userid' => $user->id
        ]);

        /**
         * Now save user avatar
         */
        $game->logo = $image;
        $game->save();

        return $image;
    }

    public function deleteAllByUser($userid)
    {
        return $this->model->where('user_id', '=', $userid)->delete();
    }

    public function total()
    {
        return $this->model->count();
    }
}