<?php

namespace App\Http\Requests\Dashboard;

use App\Models\Document;
use App\Models\FileType;
use Illuminate\Foundation\Http\FormRequest;

class DocumentRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        if ($this->isMethod("patch")) {
            $document = Document::find($this->route("id"));
            return auth()->user()->hasPermission("edit_all_documents") || ($document->user->id == auth()->user()->id);
        }

        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {

        $rules = [
            "arch_id" => [
                "required",
                function($attribute, $value, $fail) {
                    $arch_id = $this->request->get('arch_id');
                    $deptId = explode('/', $arch_id)[0];
                    if ($deptId !== $this->request->get('department')) {
                        $fail("Dept id error");
                    }
                }
            ],
            "name" => "required|min:10|max:255",
            "department" => "required|integer|exists:departments,id",
            "description" => "required|min:30",
        ];

        if ($this->isMethod("patch")) {
            $fileRules = [
                "file_item.*" => "mimes:jpg,jpeg,png|max:4096"
            ];
        } else {
            $fileRules = [
                "file_item.*" => "mimes:jpg,jpeg,png|max:4096"
            ];
        }

        $rules = array_merge(
            $rules,
            $fileRules,
        );

        return $rules;
    }
}
