<?php

namespace App\Controller\Admin;

use App\Controller\Admin\AppAdminController;
use Cake\Network\Exception\NotFoundException;

class LinksController extends AppAdminController
{

    public function index()
    {
        $query = $this->Links->find()
            ->contain([ 'Users']);
        $links = $this->paginate($query);

        $this->set('links', $links);
    }

    public function edit($alias = null)
    {
        if (!$alias) {
            throw new NotFoundException(__('Invalid link'));
        }

        $link = $this->Links->findByAlias($alias)->first();
        if (!$link) {
            throw new NotFoundException(__('Invalid link'));
        }

        if ($this->request->is(['post', 'put'])) {
            $this->request->data['user_id'] = $link->user_id;
            $link = $this->Links->patchEntity($link, $this->request->data);
            if ($this->Links->save($link)) {
                $this->Flash->success(__('The Link has been updated.'));
                return $this->redirect(['action' => 'edit', $alias]);
            } else {
                //debug( $link->errors() );
                $this->Flash->error(__('Oops! There are mistakes in the form. Please make the correction.'));
            }
        }
        $this->set('link', $link);
    }

    public function hide($alias)
    {
        $this->request->allowMethod(['post', 'delete']);
        
        $link = $this->Links->findByAlias($alias)->first();

        $link->status = 'hidden';

        if ($this->Links->save($link)) {
            $this->Flash->success(__('The Link with id: {0} has been hided.', $alias));
            return $this->redirect(['action' => 'index']);
        }
    }
}
