<?php

namespace App\Http\Controllers;

use App\Models\SiteSetting;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Inertia\Inertia;
use Inertia\Response;

class SiteSettingController extends Controller
{
    /** Admin customization page */
    public function index(): Response
    {
        return Inertia::render('Admin/Customization/HomePage', [
            'settings' => SiteSetting::allDecoded(),
        ]);
    }

    /** Display the About Us Customization page */
    public function about(): Response
    {
        return Inertia::render('Admin/Customization/AboutPage', [
            'settings' => SiteSetting::allDecoded(),
        ]);
    }

    /** Display the Payment Gateway Settings page */
    public function paymentSettings(): Response
    {
        return Inertia::render('Admin/Customization/PaymentSettingsPage', [
            'settings' => SiteSetting::allDecoded(),
        ]);
    }

    /** Save SSLCommerz / Payment Gateway Settings */
    public function savePaymentSettings(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'sslcommerz_store_id'       => 'nullable|string|max:255',
            'sslcommerz_store_password' => 'nullable|string|max:255',
            'sslcommerz_is_sandbox'     => 'nullable|boolean',
        ]);

        if ($validator->fails()) {
            return response()->json(['status' => 'error', 'errors' => $validator->errors()], 422);
        }

        $keys = ['sslcommerz_store_id', 'sslcommerz_store_password', 'sslcommerz_is_sandbox'];

        foreach ($keys as $key) {
            if ($request->has($key)) {
                SiteSetting::set($key, $request->input($key));
            }
        }

        return response()->json(['status' => 'success', 'message' => 'Payment gateway settings saved successfully.']);
    }

    /** Display the Footer Customization page */
    public function footer(): Response
    {
        return Inertia::render('Admin/Customization/FooterPage', [
            'settings' => SiteSetting::allDecoded(),
        ]);
    }

    /** Save Footer Customization Settings */
    public function saveFooter(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'footer_about_text'     => 'nullable|string',
            'footer_reg_no'         => 'nullable|string|max:255',
            'footer_tax_status'     => 'nullable|string|max:255',
            'footer_address'        => 'nullable|string|max:255',
            'footer_phone'          => 'nullable|string|max:255',
            'footer_email'          => 'nullable|string|max:255',
            'footer_payment_banner' => 'nullable|string|max:500',
            'footer_copyright_text' => 'nullable|string|max:255',
            'footer_legal_subtext'  => 'nullable|string|max:255',
        ]);

        if ($validator->fails()) {
            return response()->json(['status' => 'error', 'errors' => $validator->errors()], 422);
        }

        $keys = [
            'footer_about_text', 'footer_reg_no', 'footer_tax_status',
            'footer_address', 'footer_phone', 'footer_email',
            'footer_payment_banner', 'footer_copyright_text', 'footer_legal_subtext',
        ];

        foreach ($keys as $key) {
            if ($request->has($key)) {
                SiteSetting::set($key, $request->input($key));
            }
        }

        return response()->json(['status' => 'success', 'message' => 'Footer settings saved successfully.']);
    }

    /** Public API: serves all site settings to the React SPA */
    public function publicSettings(): JsonResponse
    {
        return response()->json(SiteSetting::allDecoded());
    }

    /** Save hero section settings (slides + content) */
    public function saveHero(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'hero_badge'                 => 'nullable|string|max:100',
            'hero_quick_donate_title'    => 'nullable|string|max:80',
            'hero_quick_donate_subtitle' => 'nullable|string|max:160',
            'hero_amount_presets'        => 'nullable|array',
            'hero_amount_presets.*'      => 'numeric|min:10',
            'hero_trust_stats'           => 'nullable|array',
            'hero_trust_stats.*.value'   => 'nullable|string|max:50',
            'hero_trust_stats.*.label'   => 'nullable|string|max:100',
            'hero_slides'                => 'nullable|array|max:6',
            'hero_slides.*.url'          => 'nullable|string',
            'hero_slides.*.title'        => 'nullable|string|max:120',
            'hero_slides.*.subtitle'     => 'nullable|string|max:250',
        ]);

        if ($validator->fails()) {
            return response()->json(['status' => 'error', 'errors' => $validator->errors()], 422);
        }

        $keys = [
            'hero_badge', 'hero_quick_donate_title', 'hero_quick_donate_subtitle',
            'hero_amount_presets', 'hero_trust_stats', 'hero_slides',
        ];

        foreach ($keys as $key) {
            if ($request->has($key)) {
                SiteSetting::set($key, $request->input($key));
            }
        }

        return response()->json(['status' => 'success', 'message' => 'Hero settings saved successfully.']);
    }

    /** Save navigation settings */
    public function saveNav(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'nav_logo_image'  => 'nullable|string',
            'nav_logo_letter' => 'nullable|string|max:5',
            'nav_logo_text'   => 'nullable|string|max:60',
            'nav_cta_text'    => 'nullable|string|max:40',
            'nav_links'       => 'nullable|array',
            'nav_links.*.label'   => 'required|string|max:40',
            'nav_links.*.view'    => 'required|string|max:40',
            'nav_links.*.visible' => 'required|boolean',
        ]);

        if ($validator->fails()) {
            return response()->json(['status' => 'error', 'errors' => $validator->errors()], 422);
        }

        foreach (['nav_logo_image', 'nav_logo_letter', 'nav_logo_text', 'nav_cta_text', 'nav_links'] as $key) {
            if ($request->has($key)) {
                SiteSetting::set($key, $request->input($key));
            }
        }

        return response()->json(['status' => 'success', 'message' => 'Navigation settings saved successfully.']);
    }

    /** Save Impact Pillars settings */
    public function savePillars(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'impact_pillars' => 'nullable|array|max:4',
            'impact_pillars.*.id' => 'required|string',
            'impact_pillars.*.title' => 'required|string|max:100',
            'impact_pillars.*.description' => 'required|string|max:250',
            'impact_pillars.*.icon' => 'required|string',
        ]);

        if ($validator->fails()) {
            return response()->json(['status' => 'error', 'errors' => $validator->errors()], 422);
        }

        if ($request->has('impact_pillars')) {
            SiteSetting::set('impact_pillars', $request->input('impact_pillars'));
        }

        return response()->json(['status' => 'success', 'message' => 'Impact Pillars saved successfully.']);
    }

    /** Save Sections Visibility settings */
    public function saveSections(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'home_sections_visibility' => 'nullable|array',
            'home_sections_visibility.*' => 'boolean',
        ]);

        if ($validator->fails()) {
            return response()->json(['status' => 'error', 'errors' => $validator->errors()], 422);
        }

        if ($request->has('home_sections_visibility')) {
            SiteSetting::set('home_sections_visibility', $request->input('home_sections_visibility'));
        }

        return response()->json(['status' => 'success', 'message' => 'Sections visibility saved successfully.']);
    }

    /** Save Home Gallery settings */
    public function saveGallery(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'home_gallery' => 'nullable|array|max:6',
            'home_gallery.*.url' => 'required|string',
        ]);

        if ($validator->fails()) {
            return response()->json(['status' => 'error', 'errors' => $validator->errors()], 422);
        }

        if ($request->has('home_gallery')) {
            SiteSetting::set('home_gallery', $request->input('home_gallery'));
        }

        return response()->json(['status' => 'success', 'message' => 'Home Gallery saved successfully.']);
    }

    /** Upload a hero slider image */
    public function uploadImage(Request $request): JsonResponse
    {
        $request->validate([
            'image' => 'required|image|mimes:jpeg,png,jpg,webp,gif|max:5120',
        ]);

        $file     = $request->file('image');
        $filename = 'hero-' . time() . '-' . rand(1000, 9999) . '.' . $file->getClientOriginalExtension();

        // Save to the React SPA's public/images folder so it's served by Vite dev server
        $spaPublicPath = base_path('../public/images');
        if (!is_dir($spaPublicPath)) {
            mkdir($spaPublicPath, 0775, true);
        }
        
        $resolvedPath = realpath($spaPublicPath) ?: $spaPublicPath;
        
        $file->move($resolvedPath, $filename);
        return response()->json(['url' => '/images/' . $filename]);
    }

    /** Save About Us settings */
    public function saveAboutUs(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'about_who_we_are' => 'nullable|string',
            'about_what_we_do' => 'nullable|string',
            'about_vision' => 'nullable|string',
            'about_mission' => 'nullable|string',
            'about_goals' => 'nullable|string',
            'about_income_policy' => 'nullable|string',
            'about_hero_media' => 'nullable|string',
            'about_ngo_profile' => 'nullable|string',
            'about_board_members' => 'nullable|array',
        ]);

        if ($validator->fails()) {
            return response()->json(['status' => 'error', 'errors' => $validator->errors()], 422);
        }

        foreach ($request->only([
            'about_who_we_are', 'about_what_we_do', 'about_vision', 'about_mission', 
            'about_goals', 'about_income_policy', 'about_hero_media', 'about_ngo_profile', 'about_board_members'
        ]) as $key => $value) {
            SiteSetting::set($key, $value);
        }

        return response()->json(['status' => 'success', 'message' => 'About Us settings saved successfully.']);
    }

    /** Upload advanced media for About Us */
    public function uploadAboutMedia(Request $request): JsonResponse
    {
        $request->validate([
            'file' => 'required|file|mimes:jpeg,png,jpg,webp,gif,mp4,webm,pdf|max:20480',
        ]);

        $file = $request->file('file');
        $extension = strtolower($file->getClientOriginalExtension());
        $filename = 'about-' . time() . '-' . rand(1000, 9999) . '.' . $extension;

        $type = 'images';
        if (in_array($extension, ['mp4', 'webm'])) {
            $type = 'videos';
        } elseif ($extension === 'pdf') {
            $type = 'documents';
        }

        $spaPublicPath = base_path('../public/about/' . $type);
        if (!is_dir($spaPublicPath)) {
            mkdir($spaPublicPath, 0775, true);
        }
        
        $resolvedPath = realpath($spaPublicPath) ?: $spaPublicPath;
        $file->move($resolvedPath, $filename);
        
        return response()->json(['url' => '/about/' . $type . '/' . $filename]);
    }
}
