<?php

namespace Ignite\Core\Http\Requests;

use Ignite\Core\Contracts\Repositories\PageRepository;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class UpdatePageRequest extends FormRequest
{
    const SEGMENT_ID = 5;

    /**
     * Get the validation rules that apply to the request.
     *
     * @param PageRepository $pageRepository
     * @return array
     */
    public function rules(PageRepository $pageRepository)
    {
        $page = $pageRepository->find($this->segment(static::SEGMENT_ID));

        $rules = [
            'label' => 'required|max:255',
            'locale' => 'size:5|regex:/([a-z]){2}_([A-Z]){2}/',
            'code' => 'required|regex:/([a-z0-9\-\/])/',
            'content' => 'required',
            'display_in_menu' => 'required|in:1,0',
            'is_protected' => 'in:1,0',
            'allowed_groups' => 'exists:core_group,id',
            'status' => 'required|in:active,inactive',
            'template' => 'required',
            'published_at' => 'required|date_format:Y-m-d H:i:s',
            'meta_title' => 'max:255',
            'meta_description' => 'max:255',
            'meta_keywords' => 'max:255',
        ];

        if ($page->isAlias()) {
            unset(
                $rules['display_in_menu'],
                $rules['status'],
                $rules['template'],
                $rules['published_at']
            );
        }

        if (! $page->isHome()) {
            $rules['code'] = [
                'regex:/([a-z0-9\-\/])/',
                Rule::unique('core_page')->ignore($page->getCode(), 'code')
            ];
        } else {
            unset($rules['code']);
        }

        return $rules;
    }

    /**
     * Get the error messages for the defined validation rules.
     *
     * @return array
     */
    public function messages()
    {
        return [
            'code.unique' => sprintf('The URL code `%s` has already been used.', $this->code),
        ];
    }

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return $this->user()->can('core.cms.pages.update');
    }
}
