<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\RedirectResponse;
use Illuminate\Validation\ValidationException;

class AuthenticatedSessionController extends Controller
{
    public function create()
    {
        return view('auth.login');
    }

    /**
     * Menangani permintaan login.
     */
    public function store(Request $request): RedirectResponse // <-- TYPO "publicaS" DIPERBAIKI DI SINI
    {
        $request->validate([
            'username' => ['required', 'string'],
            'password' => ['required', 'string'],
            'login_portal' => ['required', 'string', 'in:kontraktor,tim,owner'], // Validasi input baru kita
        ]);

        if (! Auth::attempt($request->only('username', 'password'), $request->boolean('remember'))) {
            throw ValidationException::withMessages([
                'username' => __('auth.failed'),
            ]);
        }

        $request->session()->regenerate();

        $user = Auth::user();
        $portal = $request->input('login_portal'); // Ambil portal yang dipilih

        // === [LOGIC REDIRECT BARU YANG LEBIH CERDAS] ===

        // 1. User memilih portal "Kontraktor"
        if ($portal === 'kontraktor') {
            if ($user->role !== 'admin') {
                Auth::logout(); // Logout paksa
                throw ValidationException::withMessages(['username' => 'Anda tidak memiliki hak akses Kontraktor.']);
            }
            return redirect()->intended(route('dashboard.kontraktor'));
        }

        // 2. User memilih portal "Manajemen Proyek (Tim)"
        if ($portal === 'tim') {
            
            // [PERUBAHAN LOGIC] HANYA admin yang bisa masuk ke portal ini.
            if ($user->role === 'admin') {
                // Arahkan LANGSUNG ke HALAMAN TUGAS (tasks.index)
                return redirect()->intended(route('tasks.index')); 
            }
            
            // Jika BUKAN admin (meskipun itu 'user' tim), tolak.
            Auth::logout();
            throw ValidationException::withMessages(['username' => 'Hanya Admin yang dapat mengakses portal ini.']);
        }

        // 3. User memilih portal "Owner (Klien)"
        if ($portal === 'owner') {
            if ($user->role !== 'user') {
                Auth::logout();
                throw ValidationException::withMessages(['username' => 'Anda tidak memiliki hak akses Owner.']);
            }
            
            $user->loadCount('proyeks');
            if ($user->proyeks_count > 0) {
                return redirect()->intended(route('dashboard.owner')); // Owner ke dashboard owner
            }

            // Jika dia 'tim' (user 0 proyek), tolak
            Auth::logout();
            throw ValidationException::withMessages(['username' => 'Anda tidak memiliki hak akses Owner.']);
        }

        // Fallback (seharusnya tidak pernah tercapai)
        Auth::logout();
        return redirect()->route('login');
    }

    /**
     * Menangani permintaan logout.
     */
    public function destroy(Request $request): RedirectResponse
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return redirect()->route('login');
    }
}