<?php
namespace App\Http\Requests;
use App\Enums\{KeywordDevice,SearchEngine};use App\Models\{Keyword,Project};use App\Support\KeywordTargetOptions;use Illuminate\Foundation\Http\FormRequest;use Illuminate\Validation\{Rule,Validator};
class StoreKeywordRequest extends FormRequest{protected function prepareForValidation():void{if(!$this->has('phrases')&&$this->has('phrase'))$this->merge(['phrases'=>$this->input('phrase')]);}public function project():?Project{return $this->route('customerProject')?:$this->user()?->projects()->active()->where('ulid',$this->input('project'))->first();}public function authorize():bool{$p=$this->project();return $p&&($this->user()?->can('create',[Keyword::class,$p])??false);}public function rules():array{$legacy=$this->has('phrase');return ['project'=>['nullable','string'],'phrases'=>$legacy?['nullable','string']:['required','string','max:20000'],'phrase'=>$legacy?['required','string','max:190']:['nullable'],'search_engine'=>['required',Rule::enum(SearchEngine::class)],'country_code'=>['required',Rule::in(array_keys(KeywordTargetOptions::countries()))],'language_code'=>['required',Rule::in(array_keys(KeywordTargetOptions::languages()))],'device'=>['required',Rule::enum(KeywordDevice::class)]];}public function withValidator(Validator $v):void{$v->after(function(Validator $v){if(!$this->project())$v->errors()->add('project',__('keywords.validation.project'));if($this->filled(['country_code','language_code'])&&!KeywordTargetOptions::supports($this->input('country_code'),$this->input('language_code')))$v->errors()->add('language_code',__('keywords.validation.target_pair'));$lines=preg_split('/\R/u',(string)$this->input('phrases'))?:[];if(count(array_filter($lines,fn($x)=>trim($x)!==''))>100)$v->errors()->add($this->has('phrase')?'phrase':'phrases',__('keywords.validation.limit',['count'=>100]));});}}
