<?php

namespace App\Controller\Member;

use App\Controller\Member\AppMemberController;
use Cake\Event\Event;

class ToolsController extends AppMemberController
{

    public function beforeFilter(Event $event)
    {
        parent::beforeFilter($event);
    }

    public function quick()
    {
        $this->loadModel('Users');

        $user = $this->Users->findById($this->Auth->user('id'))->first();
        $this->set('user', $user);
    }

    public function massShrinker()
    {
        $this->loadModel('Users');

        $user = $this->Users->findById($this->Auth->user('id'))->first();
        $this->set('user', $user);

        $link = $this->Users->Links->newEntity();
        if ($this->request->is('post')) {
            $urls = explode("\n", str_replace("\r", "\n", $this->request->data['urls']));
            $urls = array_unique(array_filter($urls));
            $urls = array_slice($urls, 0, 20);

            $results = [];
            foreach ($urls as $url) {
                $results[] = $this->addMassShrinker($url);
            }

            $this->set('results', $results);
        }
        $this->set('link', $link);
    }

    public function api()
    {
        $this->loadModel('Users');

        $user = $this->Users->findById($this->Auth->user('id'))->first();
        $this->set('user', $user);
    }

    protected function addMassShrinker($url)
    {
        $this->loadModel('Links');

        $result = ['url' => '', 'short' => ''];

        $url = parse_url($url, PHP_URL_SCHEME) === null ? 'http://' . $url : $url;

        $link = $this->Links->find()->where(['url' => $url, 'user_id' => $this->Auth->user('id')])->first();

        if ($link) {
            return ['url' => $url, 'short' => $link->alias];
        }

        $link = $this->Links->newEntity();
        $data = [];

        $data['user_id'] = $this->Auth->user('id');
        $data['url'] = $url;
        $data['alias'] = $this->Links->geturl();
        $link->status = 'active';
        $link->hits = 0;

        $link = $this->Links->patchEntity($link, $data);
        if ($this->Links->save($link)) {
            return ['url' => $url, 'short' => $link->alias];
        }
        return ['url' => $url, 'short' => 'error'];
    }
}
