<?php
declare(strict_types=1);

namespace App\Controller;

use App\Controller\AppController;
use Cake\ORM\TableRegistry;

class ContentBlocksController extends AppController
{
    public function initialize(): void
    {
        parent::initialize();
        $this->viewBuilder()
            ->setLayout('admin')
            ->setLayoutPath('Admin');
        if (!$this->isAdmin()) {
            throw new \Cake\Http\Exception\ForbiddenException('Admins only.');
        }
    }
    private function isAdmin(): bool
    {
        $id = $this->request->getAttribute('identity');
        return (bool)($id && $id->get('role') === 'admin');
    }
    public function index()
    {
        $contentBlocksTable = TableRegistry::getTableLocator()->get('ContentBlocks.ContentBlocks');
        $blocks = $contentBlocksTable->find()->all();
        $this->set(compact('blocks'));
    }
    public function edit($id)
    {
        $contentBlocksTable = \Cake\ORM\TableRegistry::getTableLocator()->get('ContentBlocks.ContentBlocks');
        $contentBlock = $contentBlocksTable->get($id);
        if ($this->request->is(['patch', 'post', 'put'])) {
            $data = $this->request->getData();
            $file = $this->request->getData('upload_file');
            if ($file && $file->getError() === UPLOAD_ERR_OK) {
                $ext = pathinfo($file->getClientFilename(), PATHINFO_EXTENSION);
                $filename = uniqid('block_') . '.' . $ext;
                $directory = ($contentBlock->type === 'image') ? 'img' : 'videos';
                $targetPath = WWW_ROOT . $directory . DS . $filename;
                $file->moveTo($targetPath);
                $data['value'] = '/' . $directory . '/' . $filename;
            }
            $contentBlock = $contentBlocksTable->patchEntity($contentBlock, $data);
            if ($contentBlocksTable->save($contentBlock)) {
                $this->Flash->success(__('The content block has been saved.'));
                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The content block could not be saved. Please, try again.'));
        }
        $block = $contentBlock;
        $this->set(compact('block'));
    }
}
