<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Administrator;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redirect;

class AuthController extends Controller
{
    public function loginPage() {
        return view('login-page');
    }
    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|email|exists:users,email',
            'password' => 'required|min:8',
        ], [
            'email.required' => 'Alamat email wajib diisi.',
            'email.email'    => 'Format email tidak valid.',
            'email.exists'   => 'Email belum terdaftar.',
            'password.required' => 'Kata sandi wajib diisi.',
            'password.min'      => 'Kata sandi minimal harus 8 karakter.',
        ]);


        $user = User::where('email', $request->email)->first();

        if ($user->status == 0) {
            return redirect()->route('login.view')->with('error', 'Akun ini telah dinonaktifkan');
        }

        if ($user->status == 2) {
            return redirect()->route('login.view')->with('error', 'Akun ini telah dibanned');
        }

        if (Auth::attempt($request->only('email', 'password'))) {
            $user->update(['refreshed' => 0]);
            return redirect()->intended(route('dashboard.view'));
        }

        return redirect()->route('login.view')->with('error', 'Email atau kata sandi salah');
    }

    public function changePassword() {
        return view('change_password');
    }

    public function changePasswordP(Request $request)
    {
        $request->validate([
            'old_password'     => 'required',
            'new_password'     => 'required|min:8',
            'confirm_password' => 'required|same:new_password',
        ], [
            'old_password.required'     => 'Kata sandi lama wajib diisi.',
            'new_password.required'     => 'Kata sandi baru wajib diisi.',
            'new_password.min'          => 'Kata sandi baru minimal harus 8 karakter.',
            'confirm_password.required' => 'Konfirmasi kata sandi wajib diisi.',
            'confirm_password.same'     => 'Konfirmasi kata sandi tidak cocok dengan kata sandi baru.',
        ]);

        $user = Auth::user();

        if (!Hash::check($request->old_password, $user->password)) {
            return back()->withErrors(['old_password' => 'Kata sandi lama yang Anda masukkan salah.'])->withInput();
        }

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

        return redirect()->route('dashboard.view')->with('success', 'Kata sandi berhasil diperbarui.');
    }
    public function logout(Request $request) {
        auth()->logout();

        return Redirect::route('login.view');
    }
}
