<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Mail\TestMail;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;

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

    public function update(Request $request)
    {
        $data = $request->except(['_token', '_method', 'intro_video_file']);

        // Checkbox keys: explicitly set to '0' when not present in request
        $booleanKeys = [
            'comments_enabled', 'comments_require_approval',
            'intro_enabled', 'nav_show_messages',
            'ai_auto_description', 'ai_auto_seo',
            'premium_free_mode',
            'ads_enabled',
        ];
        foreach ($booleanKeys as $k) {
            if (!array_key_exists($k, $data)) {
                $data[$k] = '0';
            }
        }

        foreach ($data as $key => $value) {
            Setting::set($key, $value);
        }

        cache()->forget('premium_free_mode');

        return back()->with('success', 'Ayarlar kaydedildi.');
    }

    /**
     * Favicon yükle — public/favicon.{ext} olarak kaydet, setting'e yaz.
     */
    public function uploadFavicon(Request $request)
    {
        $request->validate(['favicon_file' => 'required|file|mimes:png,ico,svg,jpg,jpeg|max:2048']);

        $file = $request->file('favicon_file');
        $ext  = strtolower($file->getClientOriginalExtension()) ?: 'png';
        $dest = public_path('favicon.' . $ext);

        // Eski favicon dosyalarını temizle
        foreach (['png', 'ico', 'svg', 'jpg', 'jpeg'] as $e) {
            $old = public_path('favicon.' . $e);
            if (file_exists($old) && $old !== $dest) @unlink($old);
        }

        $file->move(public_path(), 'favicon.' . $ext);

        $url = '/favicon.' . $ext;
        Setting::set('site_favicon', $url);

        return back()->with('favicon_success', 'Favicon güncellendi.');
    }

    /**
     * Intro videoyu BunnyCDN Storage'a yükle, URL'yi ayarlara kaydet.
     */
    public function uploadIntro(Request $request)
    {
        $request->validate(['intro_video_file' => 'required|file|mimes:mp4,webm|max:204800']); // max 200MB

        $zone    = Setting::get('bunnycdn_zone');
        $apiKey  = Setting::get('bunnycdn_api_key');
        $pullUrl = rtrim(Setting::get('bunnycdn_pull_url', ''), '/');

        if (!$zone || !$apiKey || !$pullUrl) {
            return back()->with('intro_error', 'Önce BunnyCDN ayarlarını kaydedin (Zone, API Key, Pull URL).');
        }

        $file     = $request->file('intro_video_file');
        $ext      = $file->getClientOriginalExtension() ?: 'mp4';
        $fileName = 'intro/site-intro.' . $ext;
        $apiUrl   = "https://storage.bunnycdn.com/{$zone}/{$fileName}";

        $response = Http::withHeaders([
            'AccessKey'    => $apiKey,
            'Content-Type' => $file->getMimeType(),
        ])->withBody(file_get_contents($file->getRealPath()), $file->getMimeType())
          ->put($apiUrl);

        if (!$response->successful()) {
            return back()->with('intro_error', 'BunnyCDN yükleme başarısız: ' . $response->status() . ' — ' . $response->body());
        }

        $cdnUrl = $pullUrl . '/' . $fileName;
        Setting::set('intro_video_url', $cdnUrl, 'intro');

        return back()->with('intro_success', 'Intro video yüklendi ve URL kaydedildi.');
    }

    public function testMail(Request $request)
    {
        $request->validate(['test_mail_to' => 'required|email'], [
            'test_mail_to.required' => 'Alıcı e-posta adresi zorunludur.',
            'test_mail_to.email'    => 'Geçerli bir e-posta adresi girin.',
        ]);

        // DB'deki ayarları runtime'da uygula
        $keys = ['mail_host','mail_port','mail_username','mail_password',
                 'mail_from_address','mail_from_name','mail_encryption'];
        $rows = Setting::whereIn('key', $keys)->pluck('value', 'key');

        if (!$rows->get('mail_host')) {
            return back()->with('mail_error', 'Önce SMTP ayarlarını kaydedin.');
        }

        $encryption = strtolower($rows->get('mail_encryption', 'tls'));
        $port       = (int) $rows->get('mail_port', 587);

        Config::set('mail.mailers.smtp.host',       $rows->get('mail_host'));
        Config::set('mail.mailers.smtp.port',       $port);
        Config::set('mail.mailers.smtp.username',   $rows->get('mail_username'));
        Config::set('mail.mailers.smtp.password',   $rows->get('mail_password'));
        Config::set('mail.mailers.smtp.encryption', $encryption);
        Config::set('mail.mailers.smtp.timeout',    15);
        Config::set('mail.mailers.smtp.stream', [
            'ssl' => [
                'verify_peer'      => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true,
            ],
        ]);
        Config::set('mail.from.address', $rows->get('mail_from_address'));
        Config::set('mail.from.name',    $rows->get('mail_from_name', config('app.name')));
        Config::set('mail.default', 'smtp');
        Mail::purge('smtp');

        // Socket timeout — PHP default 60s, düşür
        $prevTimeout = ini_get('default_socket_timeout');
        ini_set('default_socket_timeout', '15');
        set_time_limit(30);

        try {
            Mail::to($request->test_mail_to)->send(new TestMail());
            ini_set('default_socket_timeout', $prevTimeout);
            return back()->with('mail_success', 'Test e-postası başarıyla gönderildi → ' . $request->test_mail_to);
        } catch (\Throwable $e) {
            ini_set('default_socket_timeout', $prevTimeout);
            return back()->with('mail_error', 'Gönderi başarısız: ' . $e->getMessage());
        }
    }
}
