<?php

namespace App\Http\Requests;

use App\Models\AppBannerSetting;
use App\Traits\ConvertsBase64ToFiles;
use Illuminate\Foundation\Http\FormRequest;

class AppBannerSettingRequest extends FormRequest
{
    use ConvertsBase64ToFiles;

    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        return [
            'title' => 'required|string|min:2|max:180',
            'description' => 'required|string|min:2|max:1000',
            'show_app_store_button' => 'required|boolean',
            'show_play_store_button' => 'required|boolean',
            'app_store_link' => 'nullable|required_if:show_app_store_button,1|url|max:500',
            'play_store_link' => 'nullable|required_if:show_play_store_button,1|url|max:500',
            'image' => $this->imageRule(),
            'app_store_image' => $this->storeImageRule(),
            'play_store_image' => $this->storeImageRule(),
        ];
    }

    protected function prepareForValidation()
    {
        $input = $this->input();

        if (isset($input['data']['attributes']) && is_array($input['data']['attributes'])) {
            $input = $input['data']['attributes'];
        }

        $input['show_app_store_button'] = filter_var(
            $input['show_app_store_button'] ?? false,
            FILTER_VALIDATE_BOOLEAN,
            FILTER_NULL_ON_FAILURE
        ) ?? false;

        $input['show_play_store_button'] = filter_var(
            $input['show_play_store_button'] ?? false,
            FILTER_VALIDATE_BOOLEAN,
            FILTER_NULL_ON_FAILURE
        ) ?? false;

        if (!($input['show_app_store_button'] ?? false)) {
            $input['app_store_link'] = null;
        }

        if (!($input['show_play_store_button'] ?? false)) {
            $input['play_store_link'] = null;
        }

        foreach (['image', 'app_store_image', 'play_store_image'] as $imageKey) {
            if (isset($input[$imageKey]) && !isImageBase64($input[$imageKey])) {
                unset($input[$imageKey]);
            }
        }

        $this->replace($input ?? []);
        $this->convertBase64ToFiles();
    }

    protected function base64FileKeys(): array
    {
        return ['image', 'app_store_image', 'play_store_image'];
    }

    protected function imageRule(): array
    {
        $hasCurrentImage = (bool) optional(AppBannerSetting::query()->first())->image;

        return [
            $hasCurrentImage ? 'nullable' : 'required',
            'image',
            'mimes:webp,jpg,jpeg,png',
            'dimensions:min_width=900,min_height=1800',
        ];
    }

    protected function storeImageRule(): array
    {
        return [
            'nullable',
            'image',
            'mimes:webp,jpg,jpeg,png',
            'dimensions:min_width=855,min_height=290',
        ];
    }
}
