<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;
use Illuminate\View\View;

class ForcePasswordChangeController extends Controller
{
    /**
     * Show the force password change form.
     */
    public function show(): View
    {
        $user = Auth::user();
        
        // Jika user tidak wajib ganti password, redirect ke dashboard
        if (!$user->must_change_password) {
            return $this->redirectToDashboard($user);
        }

        return view('auth.force-password-change');
    }

    /**
     * Handle the force password change request.
     */
    public function store(Request $request): RedirectResponse
    {
        $user = Auth::user();

        // Validasi
        $validated = $request->validate([
            'password' => ['required', 'confirmed', Password::defaults()],
        ]);

        // Update password dan hapus flag must_change_password
        $user->update([
            'password' => Hash::make($validated['password']),
            'must_change_password' => false,
        ]);

        return $this->redirectToDashboard($user)
            ->with('status', 'password-changed');
    }

    /**
     * Redirect user to their dashboard based on role.
     */
    private function redirectToDashboard($user): RedirectResponse
    {
        switch ($user->user_type) {
            case 'admin':
                return redirect()->route('admin.dashboard');
            case 'supervisor':
                return redirect()->route('supervisor.dashboard');
            case 'teknisi':
                return redirect()->route('teknisi.dashboard');
            case 'user':
            default:
                return redirect()->route('index');
        }
    }
}

