<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Setting;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\ValidationException;

class SettingController extends Controller
{
    public function branding(Request $request): JsonResponse
    {
        $companyName = Setting::where('key', 'company_name')->value('value') ?: 'مدیریت پروژه';
        $logoPath = Setting::where('key', 'company_logo')->value('value');

        return response()->json([
            'success' => true,
            'data' => $this->brandingData($request, $companyName, $logoPath),
            'message' => 'هویت سازمان',
        ]);
    }

    public function index(Request $request): JsonResponse
    {
        try {
            $query = Setting::query();

            if ($request->filled('group')) {
                $query->where('group', $request->group);
            }

            $settings = $query->orderBy('group')->orderBy('key')->get();

            return response()->json([
                'success' => true,
                'data' => $settings,
                'message' => 'لیست تنظیمات',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در دریافت تنظیمات',
            ], 500);
        }
    }

    public function store(Request $request): JsonResponse
    {
        try {
            $request->validate([
                'key' => 'required|string|max:255|unique:settings,key',
                'value' => 'present',
                'group' => 'nullable|string|max:255',
                'type' => 'nullable|string|max:50',
            ]);

            $setting = Setting::create([
                'key' => $request->input('key'),
                'value' => $request->input('value'),
                'group' => $request->input('group', 'general'),
                'type' => $request->input('type'),
            ]);

            return response()->json([
                'success' => true,
                'data' => $setting,
                'message' => 'تنظیم با موفقیت ایجاد شد',
            ], 201);
        } catch (ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => 'اطلاعات تنظیم معتبر نیست',
                'errors' => $e->errors(),
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در ایجاد تنظیم',
            ], 500);
        }
    }

    public function update(Request $request, Setting $setting): JsonResponse
    {
        try {
            $request->validate([
                'value' => 'present',
                'group' => 'nullable|string|max:255',
                'type' => 'nullable|string|max:50',
            ]);

            $setting->update([
                'value' => $request->input('value'),
                'group' => $request->input('group', $setting->group),
                'type' => $request->input('type', $setting->type),
            ]);

            return response()->json([
                'success' => true,
                'data' => $setting->fresh(),
                'message' => 'تنظیم به‌روزرسانی شد',
            ]);
        } catch (ValidationException $e) {
            return response()->json([
                'success' => false,
                'message' => 'اطلاعات تنظیم معتبر نیست',
                'errors' => $e->errors(),
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در به‌روزرسانی تنظیم',
            ], 500);
        }
    }

    public function uploadCompanyLogo(Request $request): JsonResponse
    {
        $request->validate([
            'logo' => 'required|image|mimes:jpg,jpeg,png,webp|max:2048',
        ]);

        $setting = Setting::firstOrNew(['key' => 'company_logo']);
        $previousPath = is_string($setting->value) ? $setting->value : null;
        $path = $request->file('logo')->store('organization-logos', 'public');

        $setting->fill(['value' => $path, 'group' => 'general', 'type' => 'string'])->save();
        if ($previousPath && str_starts_with($previousPath, 'organization-logos/')) {
            Storage::disk('public')->delete($previousPath);
        }

        $companyName = Setting::where('key', 'company_name')->value('value') ?: 'مدیریت پروژه';

        return response()->json([
            'success' => true,
            'data' => [
                'setting' => $setting->fresh(),
                'branding' => $this->brandingData($request, $companyName, $path),
            ],
            'message' => 'لوگوی شرکت بارگذاری شد',
        ], 201);
    }

    public function removeCompanyLogo(Request $request): JsonResponse
    {
        $setting = Setting::where('key', 'company_logo')->first();
        $path = is_string($setting?->value) ? $setting->value : null;
        if ($path && str_starts_with($path, 'organization-logos/')) {
            Storage::disk('public')->delete($path);
        }
        $setting?->update(['value' => '']);
        $companyName = Setting::where('key', 'company_name')->value('value') ?: 'مدیریت پروژه';

        return response()->json([
            'success' => true,
            'data' => [
                'setting' => $setting?->fresh(),
                'branding' => $this->brandingData($request, $companyName, null),
            ],
            'message' => 'لوگوی شرکت حذف شد',
        ]);
    }

    private function brandingData(Request $request, mixed $companyName, mixed $logoPath): array
    {
        $path = is_string($logoPath) ? $logoPath : null;
        $logoUrl = $path && Storage::disk('public')->exists($path)
            ? $request->getSchemeAndHttpHost().Storage::disk('public')->url($path)
            : null;

        return [
            'company_name' => is_string($companyName) ? $companyName : 'مدیریت پروژه',
            'logo_path' => $path,
            'logo_url' => $logoUrl,
        ];
    }
}
