<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\GeneralSetting;
use App\Services\SmsService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class GeneralSettingController extends Controller
{
    public function edit()
    {
        $settings = GeneralSetting::getContent();
        $smsBalance = app(SmsService::class)->getBalance();

        return view('admin.settings.general', compact('settings', 'smsBalance'));
    }

    public function update(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'site_name' => 'required|string|max:120',
            'site_tagline' => 'nullable|string|max:200',
            'site_about_message' => 'nullable|string|max:1000',
            'site_phone' => 'nullable|string|max:50',
            'site_whatsapp' => 'nullable|string|max:50',
            'site_email' => 'nullable|email|max:190',
            'site_address' => 'nullable|string|max:255',
            'site_social_label' => 'nullable|array',
            'site_social_label.*' => 'nullable|string|max:60',
            'site_social_url' => 'nullable|array',
            'site_social_url.*' => 'nullable|url|max:255',
            'site_logo' => 'nullable|file|mimes:png,jpg,jpeg,webp|max:4096',
            'site_favicon' => 'nullable|file|mimes:png,ico,jpg,jpeg,webp|max:2048',
            'theme_primary' => ['required', 'regex:/^#(?:[0-9a-fA-F]{3}){1,2}$/'],
            'theme_secondary' => ['required', 'regex:/^#(?:[0-9a-fA-F]{3}){1,2}$/'],
            'theme_accent' => ['required', 'regex:/^#(?:[0-9a-fA-F]{3}){1,2}$/'],
            'theme_admin_sidebar' => ['required', 'regex:/^#(?:[0-9a-fA-F]{3}){1,2}$/'],
            'theme_head_gradient_from' => ['required', 'regex:/^#(?:[0-9a-fA-F]{3}){1,2}$/'],
            'theme_head_gradient_to' => ['required', 'regex:/^#(?:[0-9a-fA-F]{3}){1,2}$/'],

            'sms_provider' => 'required|string|in:bulksmsbd',
            'bulksmsbd_api_key' => 'nullable|string|max:255',
            'bulksmsbd_sender_id' => 'nullable|string|max:30',

            'email_provider' => 'required|string|in:smtp,resend',
            'smtp_host' => 'nullable|string|max:190',
            'smtp_port' => 'nullable|integer|min:1|max:65535',
            'smtp_encryption' => 'nullable|string|max:10',
            'smtp_username' => 'nullable|string|max:190',
            'smtp_password' => 'nullable|string|max:190',
            'from_email' => 'nullable|email|max:190',
            'from_name' => 'nullable|string|max:120',
            'resend_api_key' => 'nullable|string|max:255',
            'email_template_logo' => 'nullable|file|mimes:png,jpg,jpeg,webp|max:4096',
            'contact_admin_subject' => 'nullable|string|max:190',
            'contact_admin_body' => 'nullable|string|max:20000',
            'contact_user_subject' => 'nullable|string|max:190',
            'contact_user_body' => 'nullable|string|max:20000',
            'lead_assigned_subject' => 'nullable|string|max:190',
            'lead_assigned_body' => 'nullable|string|max:20000',
            'lead_status_admin_subject' => 'nullable|string|max:190',
            'lead_status_admin_body' => 'nullable|string|max:20000',
            'otp_subject' => 'nullable|string|max:190',
            'otp_body' => 'nullable|string|max:20000',

            'ai_provider' => 'required|string|in:openai,gemini',
            'openai_api_key' => 'nullable|string|max:255',
            'openai_model' => 'nullable|string|max:120',
            'gemini_api_key' => 'nullable|string|max:255',
            'gemini_model' => 'nullable|string|max:120',

            'admin_login_otp_enabled' => 'nullable|boolean',
            'employee_login_otp_enabled' => 'nullable|boolean',
            'public_registration_enabled' => 'nullable|boolean',
            'login_otp_channel' => 'required|string|in:email,sms',
            'login_otp_expiry_minutes' => 'required|integer|min:2|max:30',
            'login_otp_max_attempts' => 'required|integer|min:3|max:10',
            'login_otp_resend_cooldown_seconds' => 'required|integer|min:15|max:180',
        ]);

        $existing = GeneralSetting::getContent();

        $logo = $this->storeImageIfUploaded($request, 'site_logo', $existing['site']['logo'] ?? null);
        $favicon = $this->storeImageIfUploaded($request, 'site_favicon', $existing['site']['favicon'] ?? null);
        $emailTemplateLogo = $this->storeImageIfUploaded($request, 'email_template_logo', $existing['email_templates']['logo'] ?? null);
        $socialLabels = $validated['site_social_label'] ?? [];
        $socialUrls = $validated['site_social_url'] ?? [];
        $socialLinks = [];
        $rowCount = max(count($socialLabels), count($socialUrls));
        for ($i = 0; $i < $rowCount; $i++) {
            $label = trim((string) ($socialLabels[$i] ?? ''));
            $url = trim((string) ($socialUrls[$i] ?? ''));
            if ($label === '' || $url === '') {
                continue;
            }
            $socialLinks[] = [
                'label' => $label,
                'url' => $url,
            ];
        }

        $content = [
            'site' => [
                'name' => $validated['site_name'],
                'tagline' => $validated['site_tagline'] ?? '',
                'about_message' => $validated['site_about_message'] ?? '',
                'phone' => $validated['site_phone'] ?? '',
                'whatsapp_number' => $validated['site_whatsapp'] ?? '',
                'email' => $validated['site_email'] ?? '',
                'address' => $validated['site_address'] ?? '',
                'social_links' => $socialLinks,
                'logo' => $logo,
                'favicon' => $favicon,
            ],
            'theme' => [
                'primary' => $validated['theme_primary'],
                'secondary' => $validated['theme_secondary'],
                'accent' => $validated['theme_accent'],
                'admin_sidebar' => $validated['theme_admin_sidebar'],
                'head_gradient_from' => $validated['theme_head_gradient_from'],
                'head_gradient_to' => $validated['theme_head_gradient_to'],
            ],
            'sms' => [
                'provider' => $validated['sms_provider'],
                'bulksmsbd_api_key' => $validated['bulksmsbd_api_key'] ?? '',
                'bulksmsbd_sender_id' => $validated['bulksmsbd_sender_id'] ?? 'GPS',
            ],
            'email' => [
                'provider' => $validated['email_provider'],
                'smtp_host' => $validated['smtp_host'] ?? '',
                'smtp_port' => (int) ($validated['smtp_port'] ?? 587),
                'smtp_encryption' => $validated['smtp_encryption'] ?? 'tls',
                'smtp_username' => $validated['smtp_username'] ?? '',
                'smtp_password' => $validated['smtp_password'] ?? '',
                'from_email' => $validated['from_email'] ?? '',
                'from_name' => $validated['from_name'] ?? '',
                'resend_api_key' => $validated['resend_api_key'] ?? '',
            ],
            'email_templates' => [
                'logo' => $emailTemplateLogo,
                'contact_admin_subject' => $validated['contact_admin_subject'] ?? 'New Contact Request Received',
                'contact_admin_body' => $validated['contact_admin_body'] ?? '',
                'contact_user_subject' => $validated['contact_user_subject'] ?? 'We Received Your Contact Request',
                'contact_user_body' => $validated['contact_user_body'] ?? '',
                'lead_assigned_subject' => $validated['lead_assigned_subject'] ?? 'A Lead Has Been Assigned To You',
                'lead_assigned_body' => $validated['lead_assigned_body'] ?? '',
                'lead_status_admin_subject' => $validated['lead_status_admin_subject'] ?? 'Lead Status Updated By Employee',
                'lead_status_admin_body' => $validated['lead_status_admin_body'] ?? '',
                'otp_subject' => $validated['otp_subject'] ?? 'Your Login OTP',
                'otp_body' => $validated['otp_body'] ?? '',
            ],
            'ai' => [
                'provider' => $validated['ai_provider'],
                'openai_api_key' => $validated['openai_api_key'] ?? '',
                'openai_model' => $validated['openai_model'] ?? 'gpt-4o-mini',
                'gemini_api_key' => $validated['gemini_api_key'] ?? '',
                'gemini_model' => $validated['gemini_model'] ?? 'gemini-1.5-flash',
            ],
            'security' => [
                'public_registration_enabled' => $request->boolean('public_registration_enabled'),
                'admin_login_otp_enabled' => $request->boolean('admin_login_otp_enabled'),
                'employee_login_otp_enabled' => $request->boolean('employee_login_otp_enabled'),
                'login_otp_channel' => $validated['login_otp_channel'],
                'login_otp_expiry_minutes' => (int) $validated['login_otp_expiry_minutes'],
                'login_otp_max_attempts' => (int) $validated['login_otp_max_attempts'],
                'login_otp_resend_cooldown_seconds' => (int) $validated['login_otp_resend_cooldown_seconds'],
            ],
        ];

        GeneralSetting::saveContent($content);

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

    public function siteInfo(): JsonResponse
    {
        $settings = GeneralSetting::getContent();

        return response()->json([
            'site_name' => $settings['site']['name'] ?? config('app.name'),
            'tagline' => $settings['site']['tagline'] ?? '',
            'about_message' => $settings['site']['about_message'] ?? '',
            'phone' => $settings['site']['phone'] ?? '',
            'email' => $settings['site']['email'] ?? '',
            'address' => $settings['site']['address'] ?? '',
            'social_links' => $settings['site']['social_links'] ?? [],
            'logo_url' => !empty($settings['site']['logo']) ? asset('storage/' . ltrim($settings['site']['logo'], '/')) : null,
            'favicon_url' => !empty($settings['site']['favicon']) ? asset('storage/' . ltrim($settings['site']['favicon'], '/')) : null,
            'theme' => $settings['theme'] ?? [],
        ]);
    }

    public function aiGenerate(Request $request): JsonResponse
    {
        $data = $request->validate([
            'prompt' => 'required|string|min:3|max:4000',
            'context' => 'nullable|string|max:2000',
        ]);

        $settings = GeneralSetting::getContent();
        $provider = $settings['ai']['provider'] ?? 'openai';

        try {
            if ($provider === 'gemini') {
                $apiKey = $settings['ai']['gemini_api_key'] ?? '';
                $model = $settings['ai']['gemini_model'] ?? 'gemini-1.5-flash';

                if (empty($apiKey)) {
                    return response()->json(['message' => 'Gemini API key is missing in General Settings.'], 422);
                }

                $text = $this->generateWithGemini($apiKey, $model, $data['prompt'], $data['context'] ?? '');
                return response()->json(['text' => $text]);
            }

            $apiKey = $settings['ai']['openai_api_key'] ?? '';
            $model = $settings['ai']['openai_model'] ?? 'gpt-4o-mini';

            if (empty($apiKey)) {
                return response()->json(['message' => 'OpenAI API key is missing in General Settings.'], 422);
            }

            $text = $this->generateWithOpenAI($apiKey, $model, $data['prompt'], $data['context'] ?? '');
            return response()->json(['text' => $text]);

        } catch (\Throwable $e) {
            return response()->json([
                'message' => 'AI generation failed.',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    private function generateWithOpenAI(string $apiKey, string $model, string $prompt, string $context = ''): string
    {
        $fullPrompt = trim($context . "\n\n" . $prompt);

        $res = Http::withToken($apiKey)
            ->timeout(40)
            ->post('https://api.openai.com/v1/chat/completions', [
                'model' => $model,
                'messages' => [
                    ['role' => 'system', 'content' => 'You are a helpful website copywriter. Write concise, persuasive copy in plain text.'],
                    ['role' => 'user', 'content' => $fullPrompt],
                ],
                'temperature' => 0.7,
            ]);

        if (! $res->ok()) {
            throw new \RuntimeException('OpenAI API error: ' . $res->body());
        }

        return trim((string) data_get($res->json(), 'choices.0.message.content', ''));
    }

    private function generateWithGemini(string $apiKey, string $model, string $prompt, string $context = ''): string
    {
        $fullPrompt = trim($context . "\n\n" . $prompt);

        $res = Http::timeout(40)
            ->post("https://generativelanguage.googleapis.com/v1beta/models/{$model}:generateContent?key={$apiKey}", [
                'contents' => [
                    [
                        'parts' => [
                            ['text' => "You are a helpful website copywriter. Write concise, persuasive copy in plain text.\n\n{$fullPrompt}"],
                        ],
                    ],
                ],
            ]);

        if (! $res->ok()) {
            throw new \RuntimeException('Gemini API error: ' . $res->body());
        }

        return trim((string) data_get($res->json(), 'candidates.0.content.parts.0.text', ''));
    }

    private function storeImageIfUploaded(Request $request, string $field, ?string $fallback = null): ?string
    {
        if ($request->hasFile($field)) {
            return $request->file($field)->store('settings', 'public');
        }

        return $fallback;
    }
}
