<?php

namespace App\Http\Requests\Api\WebsiteSetting;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;

class UpdateRequest extends FormRequest
{
    /**
     * Handle a failed validation attempt.
     */
    protected function failedValidation(Validator $validator)
    {
        $response = response()->json([
            'error' => [
                'code' => 422,
                'message' => 'The given data was invalid.',
                'details' => $validator->errors()
            ],
        ], 422);

        throw new HttpResponseException($response);
    }

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        $user = auth('api')->user();

        return $user && $user->ability('admin', 'website_settings');
    }

    /**
     * Prepare the data for validation.
     */
    protected function prepareForValidation()
    {
        $data = [];

        // Convert boolean fields from 1/0 or "true"/"false" to actual booleans
        $booleanFields = [
            'header_show_phone',
            'header_sticky',
            'header_show_theme_toggle',
            'show_social_icon',
        ];

        foreach ($booleanFields as $field) {
            if ($this->has($field)) {
                $value = $this->input($field);
                $data[$field] = filter_var($value, FILTER_VALIDATE_BOOLEAN);
            }
        }

        // Convert JSON strings to arrays
        $arrayFields = ['social_links', 'footer_legal_links'];

        foreach ($arrayFields as $field) {
            if ($this->has($field)) {
                $value = $this->input($field);
                if (is_string($value) && !empty($value)) {
                    $decoded = json_decode($value, true);
                    if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
                        $data[$field] = $decoded;
                    }
                } elseif (is_string($value) && empty($value)) {
                    // Empty string should become empty array
                    $data[$field] = [];
                }
                // If already an array, keep it as is
            }
        }

        if (!empty($data)) {
            $this->merge($data);
        }
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $imageRule = \App\Classes\Files::fileValidationRule('image');

        return [
            // SEO settings (title required for page meta)
            'seo_title' => 'required|string|max:255',
            'seo_description' => 'nullable|string|max:1000',
            'seo_keywords' => 'nullable|string|max:500',
            'seo_author' => 'nullable|string|max:255',
            'seo_robots' => 'nullable|string|max:100',
            'seo_og_type' => 'nullable|string|max:50',
            'seo_og_locale' => 'nullable|string|max:20',
            'seo_og_site_name' => 'nullable|string|max:255',
            'seo_og_image' => ($this->hasFile('seo_og_image') && $this->file('seo_og_image')->isValid())
                ? $imageRule
                : 'nullable',
            'seo_twitter_card' => 'nullable|string|max:50',
            'seo_twitter_site' => 'nullable|string|max:100',
            'seo_twitter_creator' => 'nullable|string|max:100',

            // Website settings (required for header, footer, contact sections)
            'website_name' => 'required|string|max:255',
            'website_tagline' => 'nullable|string|max:255',
            'website_phone' => 'required|string|max:50',
            'website_email' => 'required|email|max:255',
            'website_address' => 'required|string|max:500',
            'website_hours' => 'nullable|string|max:255',
            'website_logo' => ($this->hasFile('website_logo') && $this->file('website_logo')->isValid())
                ? $imageRule
                : 'nullable',
            'website_favicon' => ($this->hasFile('website_favicon') && $this->file('website_favicon')->isValid())
                ? $imageRule
                : 'nullable',

            // Header settings
            'header_show_phone' => 'nullable|boolean',
            'header_sticky' => 'nullable|boolean',
            'header_show_theme_toggle' => 'nullable|boolean',

            // Navigation labels
            'nav_services' => 'nullable|string|max:100',
            'nav_how_it_works' => 'nullable|string|max:100',
            'nav_pricing' => 'nullable|string|max:100',
            'nav_reviews' => 'nullable|string|max:100',
            'nav_faq' => 'nullable|string|max:100',
            'nav_contact' => 'nullable|string|max:100',
            'nav_schedule_pickup' => 'nullable|string|max:100',

            // Social links (JSON array)
            'social_links' => 'nullable|array',
            'social_links.*.name' => 'nullable|string|max:100',
            'social_links.*.url' => 'nullable|string|max:500',
            'social_links.*.icon' => 'nullable|string|max:50',

            // Show social icons globally
            'show_social_icon' => 'nullable|boolean',

            // Footer settings
            'footer_description' => 'nullable|string|max:500',
            'footer_quick_links_title' => 'nullable|string|max:100',
            'footer_services_title' => 'nullable|string|max:100',
            'footer_contact_title' => 'nullable|string|max:100',
            'footer_copyright' => 'nullable|string|max:255',
            'footer_legal_links' => 'nullable|array',
            'footer_legal_links.*.title' => 'nullable|string|max:100',
            'footer_legal_links.*.url' => 'nullable|string|max:500',
        ];
    }
}
