<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Setting;
use Illuminate\Http\Request;

class SettingController extends Controller
{
    public function index()
    {
        $settings = Setting::all()->pluck('value', 'key')->toArray();
        return view('admin.settings.index', compact('settings'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'store_name' => 'nullable|string|max:255',
            'store_description' => 'nullable|string',
            'whatsapp_number' => 'nullable|string|max:20',
        ]);

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

        return redirect()->route('admin.settings.index')->with('success', 'Pengaturan berhasil disimpan.');
    }

    public function branding()
    {
        $settings = Setting::all()->pluck('value', 'key')->toArray();
        return view('admin.settings.branding', compact('settings'));
    }

    public function storeBranding(Request $request)
    {
        $validated = $request->validate([
            'app_name' => 'nullable|string|max:255',
            'app_description' => 'nullable|string',
            'app_logo' => 'nullable|image|max:2048',
        ]);

        if ($request->hasFile('app_logo')) {
            $path = $request->file('app_logo')->store('assets', 'public');
            
            $oldLogo = Setting::where('key', 'app_logo')->value('value');
            if ($oldLogo && \Illuminate\Support\Facades\Storage::disk('public')->exists($oldLogo)) {
                 \Illuminate\Support\Facades\Storage::disk('public')->delete($oldLogo);
            }
            
            $validated['app_logo'] = $path;
        }

        foreach ($validated as $key => $value) {
            if ($key === 'app_logo' && !$request->hasFile('app_logo')) {
                continue; // don't overwrite if no new file is uploaded
            }
            Setting::updateOrCreate(
                ['key' => $key],
                ['value' => $value]
            );
        }

        return redirect()->route('admin.settings.branding')->with('success', 'Branding App berhasil diperbarui.');
    }

    public function footer()
    {
        $settings = Setting::all()->pluck('value', 'key')->toArray();
        return view('admin.settings.footer', compact('settings'));
    }

    public function storeFooter(Request $request)
    {
        $keys = [
            'store_name', 'store_description', 'store_about',
            'store_address', 'store_phone', 'whatsapp_number',
            'social_instagram', 'social_facebook', 'social_tiktok', 'social_youtube',
            'footer_link1_label', 'footer_link1_url',
            'footer_link2_label', 'footer_link2_url',
            'footer_link3_label', 'footer_link3_url',
            'footer_link4_label', 'footer_link4_url',
            'footer_link5_label', 'footer_link5_url',
            'footer_link6_label', 'footer_link6_url',
            'footer_ext_label1', 'footer_ext_url1',
            'footer_ext_label2', 'footer_ext_url2',
            'footer_ext_label3', 'footer_ext_url3',
            'footer_ext_label4', 'footer_ext_url4',
            'footer_ext_label5', 'footer_ext_url5',
            'footer_ext_label6', 'footer_ext_url6',
        ];

        foreach ($keys as $key) {
            Setting::updateOrCreate(
                ['key' => $key],
                ['value' => $request->input($key, '')]
            );
        }

        return redirect()->route('admin.settings.footer')->with('success', 'Pengaturan Footer berhasil disimpan.');
    }

    public function hero()
    {
        $settings = Setting::all()->pluck('value', 'key')->toArray();
        return view('admin.settings.hero', compact('settings'));
    }

    public function storeHero(Request $request)
    {
        $keys = [
            'hero_bg_color1', 'hero_bg_color2', 'hero_bg_angle',
            'hero_eyebrow',
            'hero_headline_1', 'hero_headline_2',
            'hero_tagline',
            'hero_cta1_label', 'hero_cta1_url',
            'hero_cta2_label', 'hero_cta2_url',
            'hero_badge1', 'hero_badge2', 'hero_badge3',
        ];

        foreach ($keys as $key) {
            Setting::updateOrCreate(
                ['key' => $key],
                ['value' => $request->input($key, '')]
            );
        }

        return redirect()->route('admin.settings.hero')->with('success', 'Pengaturan Hero berhasil disimpan.');
    }

    public function video()
    {
        $settings = Setting::all()->pluck('value', 'key')->toArray();
        return view('admin.settings.video', compact('settings'));
    }

    public function storeVideo(Request $request)
    {
        $validated = $request->validate([
            'video_section_active' => 'nullable|boolean',
            'video_title'          => 'nullable|string|max:255',
            'video_description'    => 'nullable|string',
            'video_source_type'    => 'required|in:youtube,upload',
            'video_youtube_id'     => 'nullable|string|max:255',
            'video_file'           => 'nullable|file|mimes:mp4,webm|max:20480', // 20MB limit
        ]);

        if ($request->hasFile('video_file')) {
            $path = $request->file('video_file')->store('assets/videos', 'public');
            
            $oldVideo = Setting::where('key', 'video_file')->value('value');
            if ($oldVideo && \Illuminate\Support\Facades\Storage::disk('public')->exists($oldVideo)) {
                 \Illuminate\Support\Facades\Storage::disk('public')->delete($oldVideo);
            }
            
            $validated['video_file'] = $path;
        }

        // Default handler for unchecked boolean
        $validated['video_section_active'] = $request->has('video_section_active') ? '1' : '0';

        foreach ($validated as $key => $value) {
            if ($key === 'video_file' && !$request->hasFile('video_file')) {
                continue; // don't overwrite local storage pointer if no new file is pushed
            }
            Setting::updateOrCreate(
                ['key' => $key],
                ['value' => $value ?? '']
            );
        }

        return redirect()->route('admin.settings.video')->with('success', 'Pengaturan Video Konten berhasil disimpan.');
    }
}
