<?php

namespace App\Http\Controllers;

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 settings page.
     */
    public function index(Request $request): Response
    {
        return Inertia::render('Settings');
    }

    /**
     * Update user 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(
            "User {$user->name} updated profile information",
            [
                'old_data' => $oldData,
                'new_data' => $validated,
            ],
            $request
        );

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

    /**
     * Update user 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(
            "User {$user->name} updated password",
            [
                'user_id' => $user->id,
                'email' => $user->email,
            ],
            $request
        );

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