<?php

namespace App\Http\Controllers;

use App\Models\AppSetting;
use App\Models\News;
use App\Models\UserSetting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class SettingsController extends Controller
{
    // ──────────────────────────────────────────────────────────
    // GET /settings  →  name: 'settings'
    // ──────────────────────────────────────────────────────────
    public function index()
    {
        // Buat record settings jika user belum punya
        Auth::user()->userSetting()->firstOrCreate([
            'user_id' => Auth::id(),
        ]);

        // Berita milik user (maks 5 terbaru untuk ditampilkan di settings)
        $userNews = News::where('user_id', Auth::id())
            ->latest()
            ->take(5)
            ->get();

        // AppSetting publik (tetap dipertahankan sesuai controller lama)
        $settings = AppSetting::where('is_public', true)
            ->orderBy('group')
            ->orderBy('key')
            ->get()
            ->groupBy('group');

        return view('settings.index', compact('settings', 'userNews'));
    }

    // ──────────────────────────────────────────────────────────
    // PUT /settings  →  name: 'settings.update'
    // Router: bedakan form notifikasi vs form upload berita
    // via hidden field _form_type
    // ──────────────────────────────────────────────────────────
    public function update(Request $request)
    {
        $formType = $request->input('_form_type', 'notification');

        if ($formType === 'news') {
            return $this->handleNewsUpload($request);
        }

        return $this->handleNotification($request);
    }

    // ──────────────────────────────────────────────────────────
    // PRIVATE: simpan toggle notifikasi
    // ──────────────────────────────────────────────────────────
    private function handleNotification(Request $request)
    {
        $keys = [
            'news_notif',
            'promo_notif',
            'report_notif',
            'email_notif',
            'browser_notif',
        ];

        // Checkbox tidak dikirim saat tidak dicentang → paksa false
        $data = [];
        foreach ($keys as $key) {
            $data[$key] = $request->boolean($key);
        }

        UserSetting::updateOrCreate(
            ['user_id' => Auth::id()],
            $data
        );

        return redirect()->back()->with('success', 'Pengaturan notifikasi berhasil disimpan.');
    }

    // ──────────────────────────────────────────────────────────
    // PRIVATE: upload berita baru
    // ──────────────────────────────────────────────────────────
    private function handleNewsUpload(Request $request)
    {
        $request->validate([
            'news_title'       => 'required|string|max:255',
            'news_description' => 'nullable|string|max:5000',
            'news_image'       => 'nullable|image|mimes:jpeg,png,jpg,gif|max:5120',
        ], [
            'news_title.required' => 'Judul berita wajib diisi.',
            'news_image.image'    => 'File harus berupa gambar.',
            'news_image.max'      => 'Ukuran gambar maksimal 5 MB.',
        ]);

        $imagePath = null;
        if ($request->hasFile('news_image')) {
            $imagePath = $request->file('news_image')->store('news', 'public');
        }

        News::create([
            'user_id'     => Auth::id(),
            'title'       => $request->news_title,
            'description' => $request->news_description,
            'image_path'  => $imagePath,
        ]);

        return redirect()->back()->with('success', 'Berita berhasil diupload.');
    }
}