<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use App\Models\Admin;
use Illuminate\Support\Facades\Hash;
use App\Models\Notification;

class AuthController extends Controller
{
    public function Login(){
        
        return view('admin.login');
    }

    public function StoreLogin(Request $request){

        $credentials = $request->validate([
            'email' => 'required|email',
            'password' => 'required|string|min:6',
        ]);

        // Check if the email exists in the admins table
         $admin = Admin::where('email', $request->email)->first();
        
        if (!$admin) {
          
            return back()->withErrors(['email' => 'The provided email is incorrect.']);
        }
        
        if (!Hash::check($request->password, $admin->password)) {
        
            return back()->withErrors(['password' => 'The provided password is incorrect.']);
        }
         Auth::guard('admin')->login($admin);
         return redirect()->intended(route('admin.dashboard'));

    }

    public function Logout(Request $request){
      
        Auth::guard('admin')->logout(); 
       return redirect()->route('login');
   }

    public function Changepassword(){

        return view('admin.changepassword');
    }

    public function StoreChangepassword(Request $request){
        
        $request->validate([
            'current_password' => 'required',
            'newpassword' => 'required|min:6|confirmed',
            'newpassword_confirmation'=>'required',
        ]);   

        $admin = Auth::guard('admin')->user();

        if (!Hash::check($request->current_password, $admin->password)) {
            return back()->withErrors(['current_password' => 'The current password is incorrect.']);
        }

        $admin->password = Hash::make($request->newpassword);
        $admin->save();   

        return redirect()->back()->with('success', 'Password Changed Successfully.');
    }
    
    public function Notification(){
        
        $notifications = Notification::orderBy('created_at','desc')->get();
        return view('admin.notification',compact('notifications'));
    }
    
    public function AddNotification(Request $request){
          $request->validate([
            'title' => 'required',
            'message' => 'required',
        ]);   
        
        $notification = new Notification();
        $notification->title = $request->title;
        $notification->message = $request->message;
        $notification->save();
        return redirect()->back()->with('success', 'Notification Added Successfully.');

    }
}
