<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth; // ← Tambahkan ini!

class AuthController extends Controller
{
    public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');

        if (Auth::attempt($credentials)) {
            $user = Auth::user();
            
            // Cek apakah user aktif
            if (!$user->is_active) {
                Auth::logout();
                return back()->withErrors([
                    'email' => 'Akun Anda telah dinonaktifkan. Silakan hubungi administrator.',
                ]);
            }
            
            // Update last login
            $user->updateLastLogin();
            
            // Cek apakah user wajib mengganti password
            if ($user->must_change_password) {
                return redirect()->route('password.force-change')
                    ->with('warning', 'Anda wajib mengganti password sebelum melanjutkan. Password Anda telah direset oleh administrator.');
            }
            
            // Cek apakah ada produk yang disimpan sebelum login
            if (session()->has('buy_now_product_id')) {
                $productId = session('buy_now_product_id');
                session()->forget('buy_now_product_id');
                return redirect()->route('checkout.form', $productId);
            }

            // Redirect berdasarkan role
            switch ($user->user_type) {
                case 'admin':
                    return redirect()->intended(route('admin.dashboard'));
                case 'supervisor':
                    return redirect()->intended(route('supervisor.dashboard'));
                case 'teknisi':
                    return redirect()->intended(route('teknisi.dashboard'));
                case 'user':
                default:
                    return redirect()->intended(route('index'));
            }
        }

        return back()->withErrors([
            'email' => 'Email atau password salah.',
        ]);
    }
}
