<?php

namespace App\Http\Controllers\Partner;

use App\Http\Controllers\Controller;
use App\Models\PartnerSetting;
use App\Services\ActivityLogService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;
use Inertia\Inertia;
use Inertia\Response;

class SettingsController extends Controller
{
    public function __construct(
        protected ActivityLogService $activityLogService
    ) {}

    /**
     * Display the partner settings page.
     */
    public function index(Request $request): Response
    {
        $partner = Auth::user();
        $settings = $partner->partnerSettings;

        return Inertia::render('Partner/Settings', [
            'partnerSettings' => $settings ? $settings->settings : [],
        ]);
    }

    /**
     * Update partner profile information.
     */
    public function updateProfile(Request $request)
    {
        $user = Auth::user();

        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email,'.$user->id],
        ]);

        $oldData = [
            'name' => $user->name,
            'email' => $user->email,
        ];

        $user->update($validated);

        // Log settings update activity
        $this->activityLogService->logSettingsUpdate(
            "Partner {$user->name} updated profile information",
            [
                'old_data' => $oldData,
                'new_data' => $validated,
            ],
            $request
        );

        return redirect()->route('partner.settings')->with('success', 'Profil berhasil diperbarui.');
    }

    /**
     * Update partner password.
     */
    public function updatePassword(Request $request)
    {
        $request->validate([
            'current_password' => ['required', 'string'],
            'password' => ['required', 'string', 'confirmed', Password::defaults()],
        ]);

        $user = Auth::user();

        if (! Hash::check($request->current_password, $user->password)) {
            return back()->withErrors([
                'current_password' => 'Password saat ini tidak sesuai.',
            ]);
        }

        $user->update([
            'password' => Hash::make($request->password),
        ]);

        // Log password update activity
        $this->activityLogService->logSettingsUpdate(
            "Partner {$user->name} updated password",
            [
                'user_id' => $user->id,
                'email' => $user->email,
            ],
            $request
        );

        return redirect()->route('partner.settings')->with('success', 'Password berhasil diperbarui.');
    }

    /**
     * Update partner custom settings.
     */
    public function updateSettings(Request $request)
    {
        $partner = Auth::user();

        $validated = $request->validate([
            'settings' => ['required', 'array'],
        ]);

        $partnerSetting = $partner->partnerSettings;

        if ($partnerSetting) {
            $oldSettings = $partnerSetting->settings;
            $partnerSetting->update([
                'settings' => $validated['settings'],
            ]);

            // Log settings update activity
            $this->activityLogService->logSettingsUpdate(
                "Partner {$partner->name} updated custom settings",
                [
                    'old_settings' => $oldSettings,
                    'new_settings' => $validated['settings'],
                ],
                $request
            );
        } else {
            $partnerSetting = PartnerSetting::create([
                'partner_id' => $partner->id,
                'settings' => $validated['settings'],
            ]);

            // Log create activity
            $this->activityLogService->logCreate($partnerSetting);
        }

        return redirect()->route('partner.settings')->with('success', 'Pengaturan berhasil diperbarui.');
    }
}
