<?php

/*
|--------------------------------------------------------------------------
| OwnStore - Build your own online store
| Author: TakfeDev (MKJUEL)
| All Rights Reserved
|--------------------------------------------------------------------------
*/

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Artisan;
use App\Models\Setting;
use Illuminate\Support\Facades\Cache;

class SettingController extends Controller
{
    public function editSeo()
    {
        $settings = Setting::pluck('value', 'key')->toArray();

        return Inertia::render('cp/Settings/Seo', [
            'appName' => config('app.name'),
            'seoMetaDescription' => $settings['seo_meta_description'] ?? '',
            'seoMetaKeywords' => $settings['seo_meta_keywords'] ?? '',
            
            'lightLogo' => Storage::disk('public')->exists('settings/light_logo.png') 
                ? asset('storage/settings/light_logo.png') . '?v=' . time() : null,
            'darkLogo' => Storage::disk('public')->exists('settings/dark_logo.png') 
                ? asset('storage/settings/dark_logo.png') . '?v=' . time() : null,
            'favicon' => Storage::disk('public')->exists('settings/favicon.png') 
                ? asset('storage/settings/favicon.png') . '?v=' . time() : null,
            'ogImage' => Storage::disk('public')->exists('settings/og_image.png') 
                ? asset('storage/settings/og_image.png') . '?v=' . time() : null,
        ]);
    }

    public function updateSeo(Request $request)
    {
        $request->validate([
            'app_name' => 'required|string|max:255',
            'seo_meta_description' => 'nullable|string|max:500',
            'seo_meta_keywords' => 'nullable|string|max:255',
            'light_logo' => 'nullable|image|mimes:jpeg,png,jpg,svg|max:2048',
            'dark_logo' => 'nullable|image|mimes:jpeg,png,jpg,svg|max:2048',
            'favicon' => 'nullable|image|mimes:jpeg,png,jpg,ico,svg|max:1024',
            'og_image' => 'nullable|image|mimes:jpeg,png,jpg,webp|max:5120',
        ]);

        $this->updateEnv('APP_NAME', '"' . $request->app_name . '"');

        Setting::updateOrCreate(['key' => 'seo_meta_description'], ['value' => $request->seo_meta_description]);
        Setting::updateOrCreate(['key' => 'seo_meta_keywords'], ['value' => $request->seo_meta_keywords]);

        if ($request->hasFile('light_logo')) {
            $request->file('light_logo')->storeAs('settings', 'light_logo.png', 'public');
        }
        if ($request->hasFile('dark_logo')) {
            $request->file('dark_logo')->storeAs('settings', 'dark_logo.png', 'public');
        }
        if ($request->hasFile('favicon')) {
            $request->file('favicon')->storeAs('settings', 'favicon.png', 'public');
        }
        if ($request->hasFile('og_image')) {
            $request->file('og_image')->storeAs('settings', 'og_image.png', 'public');
        }

        Artisan::call('config:clear');
        Cache::forget('app_settings');

        return back()->with('success', 'SEO & Branding Settings updated successfully.');
    }

    public function editAppearance()
    {
        $settings = Setting::pluck('value', 'key')->toArray();
        return Inertia::render('cp/Settings/Appearance', [
            'settings' => $settings
        ]);
    }

    public function updateAppearance(Request $request)
    {
        $data = $request->except(['_token']);
        foreach ($data as $key => $value) {
            Setting::updateOrCreate(['key' => $key], ['value' => $value]);
        }
        Cache::forget('app_settings');
        return back()->with('success', 'Appearance updated globally.');
    }

    public function editTrust()
    {
        $settings = Setting::pluck('value', 'key')->toArray();

        return Inertia::render('cp/Settings/Trust', [
            'protectionBadgeName' => $settings['protection_badge_name'] ?? 'Buyer Protection',
            'protectionSlogan' => $settings['protection_slogan'] ?? 'Protects your orders from payment to delivery.',
            'enableRefundSystem' => filter_var($settings['enable_refund_system'] ?? true, FILTER_VALIDATE_BOOLEAN),
            
            // --- Footer Info & Payment Banner ---
            'aboutUsText' => $settings['about_us_text'] ?? 'OwnStore is a powerful B2B/B2C marketplace built by TakfeDev. We make it easy for every store owner to manage their business globally with seamless tools and secure transactions.',
            'contactUsText' => $settings['contact_us_text'] ?? "Email: support@example.com\nPhone: +1 234 567 890",
            'enableFooterPaymentImage' => filter_var($settings['enable_footer_payment_image'] ?? true, FILTER_VALIDATE_BOOLEAN),
            'footerPaymentImage' => Storage::disk('public')->exists('settings/footer_payment.png') 
                ? asset('storage/settings/footer_payment.png') . '?v=' . time() : null,
        ]);
    }

    public function updateTrust(Request $request)
    {
        $request->validate([
            'protection_badge_name' => 'required|string|max:50',
            'protection_slogan' => 'required|string|max:150',
            'about_us_text' => 'nullable|string|max:1000',
            'contact_us_text' => 'nullable|string|max:500',
            'enable_footer_payment_image' => 'boolean',
            'footer_payment_image' => 'nullable|image|mimes:jpeg,png,jpg,webp,svg|max:2048',
        ]);

        Setting::updateOrCreate(['key' => 'protection_badge_name'], ['value' => $request->protection_badge_name]);
        Setting::updateOrCreate(['key' => 'protection_slogan'], ['value' => $request->protection_slogan]);
        Setting::updateOrCreate(['key' => 'enable_refund_system'], ['value' => $request->enable_refund_system ? '1' : '0']);
        
        // --- Update Footer Info ---
        Setting::updateOrCreate(['key' => 'about_us_text'], ['value' => $request->about_us_text]);
        Setting::updateOrCreate(['key' => 'contact_us_text'], ['value' => $request->contact_us_text]);
        Setting::updateOrCreate(['key' => 'enable_footer_payment_image'], ['value' => $request->enable_footer_payment_image ? '1' : '0']);

        if ($request->hasFile('footer_payment_image')) {
            $request->file('footer_payment_image')->storeAs('settings', 'footer_payment.png', 'public');
        }
        
        Cache::forget('app_settings');

        return back()->with('success', 'Trust & Footer Information updated successfully.');
    }

    public function editImageOptimization()
    {
        $settings = Setting::whereIn('key', [
            'image_compression_enabled',
            'image_output_format',
            'image_quality',
            'image_max_width',
        ])->pluck('value', 'key')->toArray();

        return Inertia::render('cp/Settings/ImageOptimization', [
            'settings' => $settings
        ]);
    }

    public function updateImageOptimization(Request $request)
    {
        $data = $request->validate([
            'image_compression_enabled' => 'boolean',
            'image_output_format' => 'required|in:webp,jpeg,png',
            'image_quality' => 'required|integer|min:10|max:100',
            'image_max_width' => 'required|integer|min:0|max:4000',
        ]);

        foreach ($data as $key => $value) {
            Setting::updateOrCreate(['key' => $key], ['value' => is_bool($value) ? ($value ? '1' : '0') : $value]);
        }

        Cache::forget('app_settings');

        return back()->with('success', 'Image compression settings updated successfully.');
    }

    public function editCustomScripts()
    {
        $settings = Setting::whereIn('key', [
            'custom_header_script', 
            'custom_footer_script'
        ])->pluck('value', 'key')->toArray();

        return Inertia::render('cp/Settings/CustomScripts', [
            'settings' => $settings
        ]);
    }

    public function updateCustomScripts(Request $request)
    {
        // We use string without limits because scripts can be large and contain HTML tags
        $data = $request->validate([
            'custom_header_script' => 'nullable|string',
            'custom_footer_script' => 'nullable|string',
        ]);

        foreach ($data as $key => $value) {
            Setting::updateOrCreate(['key' => $key], ['value' => $value]);
        }

        Cache::forget('app_settings');

        return back()->with('success', 'Custom scripts saved successfully.');
    }

    private function updateEnv($key, $value)
    {
        $path = base_path('.env');
        if (file_exists($path)) {
            $oldContent = file_get_contents($path);
            if (preg_match('/^' . $key . '=/m', $oldContent)) {
                $newContent = preg_replace('/^' . $key . '=.*/m', $key . '=' . $value, $oldContent);
            } else {
                $newContent = $oldContent . PHP_EOL . $key . '=' . $value;
            }
            file_put_contents($path, $newContent);
        }
    }
}