<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Setting;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Hash;
use PragmaRX\Google2FAQRCode\Google2FA;

class AdminSettingController extends Controller
{
    public function index() 
    { 
        return view('admin.settings.index'); 
    }

    // ==========================================
    // ১. বোট কনফিগারেশন (এটি আগে ডিলিট হয়ে গিয়েছিল)
    // ==========================================
    public function botConfig() 
    { 
        return view('admin.settings.bot'); 
    }

    public function updateBot(Request $request)
    {
        $keys = ['telegram_bot_token', 'telegram_admin_id'];
        foreach ($keys as $key) {
            if ($request->has($key)) {
                Setting::updateOrCreate(
                    ['setting_key' => $key],
                    ['setting_value' => $request->$key]
                );
            }
        }
        return back()->with('success', 'Bot Configuration Updated Successfully!');
    }

    // ==========================================
    // ২. সিস্টেম সেটিংস আপডেট (সব কি-সহ)
    // ==========================================
    public function update(Request $request)
    {
        // পাসওয়ার্ড পরিবর্তন
        if ($request->has('current_password') && $request->current_password != '') {
            $admin = auth()->guard('admin')->user();
            if (Hash::check($request->current_password, $admin->password)) {
                if($request->new_password === $request->confirm_password) {
                    $admin->password = Hash::make($request->new_password);
                    $admin->save();
                }
            }
        }

        // লোগো ও ফেভিকন আপলোড
        if ($request->hasFile('site_logo')) {
            $file = $request->file('site_logo');
            $filename = 'logo_' . time() . '.' . $file->getClientOriginalExtension();
            $file->move(public_path('uploads/logo'), $filename);
            $oldLogo = Setting::val('site_logo');
            if ($oldLogo && File::exists(public_path($oldLogo))) { File::delete(public_path($oldLogo)); }
            Setting::updateOrCreate(['setting_key' => 'site_logo'], ['setting_value' => 'uploads/logo/' . $filename]);
        }

        if ($request->hasFile('site_favicon')) {
            $file = $request->file('site_favicon');
            $filename = 'fav_' . time() . '.' . $file->getClientOriginalExtension();
            $file->move(public_path('uploads/logo'), $filename);
            $oldFav = Setting::val('site_favicon');
            if ($oldFav && File::exists(public_path($oldFav))) { File::delete(public_path($oldFav)); }
            Setting::updateOrCreate(['setting_key' => 'site_favicon'], ['setting_value' => 'uploads/logo/' . $filename]);
        }

        // টগল সুইচ হ্যান্ডেল (Checkbox)
        $toggles = ['enable_google_login', 'enable_captcha', 'enable_email_verify'];
        foreach ($toggles as $toggle) {
            $val = $request->has($toggle) ? 'yes' : 'no';
            Setting::updateOrCreate(['setting_key' => $toggle], ['setting_value' => $val]);
        }

        // সব টেক্সট ডাটা, SEO, API ও SMTP কী আপডেট
        $keys = [
            'site_name', 'site_email', 'site_phone', 'seo_title', 'seo_description', 'seo_keywords',
            'payfastbd_api_key', 'telegram_bot_token', 'telegram_admin_id', 'notice_text',
            'google_client_id', 'google_client_secret', 'recaptcha_site_key', 'recaptcha_secret_key',
            'smtp_host', 'smtp_port', 'smtp_username', 'smtp_password', 'smtp_encryption', 'mail_from_address'
        ];

        foreach ($keys as $key) {
            if ($request->has($key)) {
                Setting::updateOrCreate(
                    ['setting_key' => $key],
                    ['setting_value' => $request->$key]
                );
            }
        }

        return back()->with('success', 'System Configuration Updated Successfully!');
    }

    // ==========================================
    // ৩. এডমিন ২এফএ লজিক
    // ==========================================
    public function show2faSetup()
    {
        $admin = auth()->guard('admin')->user();
        $google2fa = new Google2FA();

        $secret = $admin->two_factor_secret;
        if (!$secret) {
            $secret = $google2fa->generateSecretKey();
            $admin->two_factor_secret = $secret;
            $admin->save();
        }

        $QR_Image = $google2fa->getQRCodeInline(
            config('app.name'),
            $admin->username,
            $secret
        );

        return view('admin.2fa-setup', compact('QR_Image', 'secret'));
    }

    public function enable2fa(Request $request)
    {
        $request->validate(['verify_code' => 'required']);
        $admin = auth()->guard('admin')->user();
        $google2fa = new Google2FA();

        if ($google2fa->verifyKey($admin->two_factor_secret, $request->verify_code)) {
            $admin->two_factor_enabled = 1;
            $admin->save();
            session(['admin_2fa_verified' => true]);
            return back()->with('success', '2FA Enabled Successfully!');
        }
        return back()->with('error', 'Invalid verification code!');
    }

    public function disable2fa()
    {
        $admin = auth()->guard('admin')->user();
        $admin->two_factor_enabled = 0;
        $admin->two_factor_secret = null;
        $admin->save();
        session()->forget('admin_2fa_verified');
        return back()->with('success', '2FA Disabled.');
    }
}
