<?php

namespace App\Http\Controllers;

use App\Models\Setting;
use App\Models\User;
use App\Models\Role;
use App\Models\Permission;
use App\Models\Partner;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class SettingsController extends Controller
{
    public function index()
    {
        return view('settings.index', [
            'users' => User::with(['roles', 'partner'])->get(),
            'roles' => Role::with('permissions')->get(),
            'permissions' => Permission::all(),
            'partners' => Partner::all(),
            'settings' => Setting::all()->groupBy('group'),
            'categories' => [
                'income' => $this->getIncomeCategories(),
                'expense' => $this->getExpenseCategories()
            ]
        ]);
    }

    public function updateGeneralSettings(Request $request)
    {
        $request->validate([
            'app_name' => 'required|string|max:255',
            'logo' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
            'favicon' => 'nullable|image|mimes:ico,png|max:1024',
            'footer_text' => 'nullable|string|max:500',
            'currency' => 'required|string|max:10',
            'timezone' => 'required|string|max:100',
        ]);

        // حفظ الإعدادات العامة
        Setting::set('app_name', $request->app_name);
        Setting::set('footer_text', $request->footer_text);
        Setting::set('currency', $request->currency);
        Setting::set('timezone', $request->timezone);

        // معالجة الشعار
        if ($request->hasFile('logo')) {
            $path = $request->file('logo')->store('logos', 'public');
            Setting::set('logo', $path);
        }

        // معالجة الأيقونة المفضلة
        if ($request->hasFile('favicon')) {
            // حذف الأيقونة القديمة إذا وجدت
            $oldFavicon = Setting::get('favicon');
            if ($oldFavicon && Storage::disk('public')->exists($oldFavicon)) {
                Storage::disk('public')->delete($oldFavicon);
            }

            $favicon = $request->file('favicon');
            $faviconPath = $favicon->store('settings', 'public');
            Setting::set('favicon', $faviconPath);
        }

        // تحديث اسم التطبيق في ملف .env
        $this->updateEnvFile('APP_NAME', $request->app_name);

        return back()->with('success', 'تم تحديث الإعدادات العامة بنجاح');
    }

    private function updateEnvFile($key, $value)
    {
        $path = base_path('.env');
        $value = str_replace('"', '\"', $value); // escape double quotes

        if (file_exists($path)) {
            file_put_contents($path, preg_replace(
                "/^{$key}=.*/m",
                "{$key}=\"{$value}\"",
                file_get_contents($path)
            ));
        }
    }

    public function updateCategories(Request $request)
    {
        $request->validate([
            'income_categories' => 'required|array',
            'expense_categories' => 'required|array',
        ]);

        Setting::set('income_categories', json_encode($request->income_categories), 'categories');
        Setting::set('expense_categories', json_encode($request->expense_categories), 'categories');

        return response()->json(['message' => 'تم تحديث التصنيفات بنجاح']);
    }

    private function getIncomeCategories()
    {
        $categories = Setting::get('income_categories');
        return $categories ? json_decode($categories, true) : config('categories.income');
    }

    private function getExpenseCategories()
    {
        $categories = Setting::get('expense_categories');
        return $categories ? json_decode($categories, true) : config('categories.expense');
    }

    public function deleteLogo()
    {
        $logo = Setting::get('logo');
        if ($logo && Storage::disk('public')->exists($logo)) {
            Storage::disk('public')->delete($logo);
        }
        Setting::set('logo', null);
        return response()->json(['message' => 'تم حذف الشعار بنجاح']);
    }

    public function deleteFavicon()
    {
        $favicon = Setting::get('favicon');
        if ($favicon && Storage::disk('public')->exists($favicon)) {
            Storage::disk('public')->delete($favicon);
        }
        Setting::set('favicon', null);
        return response()->json(['message' => 'تم حذف الأيقونة المفضلة بنجاح']);
    }

    public function update(Request $request)
    {
        try {
            foreach ($request->except('_token') as $key => $value) {
                if ($request->hasFile($key)) {
                    // معالجة الملفات المرفوعة
                    $path = $request->file($key)->store('settings', 'public');
                    Setting::set($key, $path);
                } else {
                    Setting::set($key, $value);
                }
            }

            return response()->json(['message' => 'تم حفظ الإعدادات بنجاح']);
        } catch (\Exception $e) {
            return response()->json(['message' => 'حدث خطأ أثناء حفظ الإعدادات'], 500);
        }
    }
} 