<?php
namespace App\Http\Controllers\Login;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\PaintingCategory;
use App\Models\Artist;
use App\Models\ArtTag;
use App\Models\IllustrationCategory;
use App\Models\Illustration;
use App\Models\CreativeArt;
use App\Traits\LogUtils;
use Auth;
use Illuminate\Http\Request;
use Validator;

class AuthController extends Controller
{
    use LogUtils;

    public function index()
    {
        return view('login');
    }

    public function submitLogIn(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email'    => 'required|email',
            'password' => 'required',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        $credentials = $request->only('email', 'password');

        if (Auth::attempt($credentials)) {
            return redirect()->route('dashboard')
                ->with('success', 'Welcome to your dashboard');
        }

        return redirect()->back()
            ->withInput()
            ->with('error', 'Invalid email or password');
    }

    public function logout()
    {
        try {
            Auth::logout();
            return \Redirect::Route('login');
        } catch (Exception $e) {
            return redirect()->route('login');
        }
    }

    public function dashboard(Request $request)
    {
        // Products
        $productCount = Product::where('is_delete', 0)->where('status', 1)->count();

        // Painting Categories
        $paintingCategoryCount = PaintingCategory::where('is_delete', 0)->where('status', 1)->count();

        // Artists
        $artistCount = Artist::where('is_delete', 0)->where('status', 1)->count();

        // Art Tags
        $artTagCount = ArtTag::where('is_delete', 0)->where('status', 1)->count();

        // Illustration Categories
        $illustrationCategoryCount = IllustrationCategory::where('is_delete', 0)->where('status', 1)->count();

        // Illustrations
        $illustrationCount = Illustration::where('is_delete', 0)->where('status', 1)->count();

        // Art (CreativeArt)
        $artCount = CreativeArt::where('is_delete', 0)->where('status', 1)->count();

        return view('dashboard', [
            'productCount'               => $productCount,
            'paintingCategoryCount'      => $paintingCategoryCount,
            'artistCount'                => $artistCount,
            'artTagCount'                => $artTagCount,
            'illustrationCategoryCount'  => $illustrationCategoryCount,
            'illustrationCount'          => $illustrationCount,
            'artCount'                   => $artCount,
        ]);
    }
}
