<?php

namespace App\Http\Controllers\User\Auth;

use Exception;
use App\Models\Order;
use App\Models\Deposit;
use App\Models\UserCookie;
use App\Models\WebsitePage;
use Illuminate\Support\Str;
use App\Models\UserLoginLog;
use Illuminate\Support\Carbon;
use App\Models\UserActivateAccount;
use App\Models\WebsiteInformation;
use App\Http\Controllers\Controller;
use DateTime;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Session;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Support\Facades\Log;

class AuthController extends Controller {
    public function home() {
        if (Auth::check()== true) {
			$components = [
				'information' => WebsiteInformation::orderBy('id', 'desc')->limit('5')->get(),
				'orders' => [
					'total' => Order::where('user_id', Auth::user()->id)->sum('price'),
					'count' => Order::where('user_id', Auth::user()->id)->count('*')
				],
				'deposits' => [
					'total' => Deposit::where('user_id', Auth::user()->id)->sum('amount'),
					'count' => Deposit::where('user_id', Auth::user()->id)->count('*')
				],
				'chart'		  => chart(Carbon::parse(now())->subDays(6), Carbon::parse(now()), Auth::id()),
				'live_orders' => Order::whereDate('created_at', date('Y-m-d'))->limit(20)->latest('id')->get()
			];
            return view('user.auth.home', $components);
		} else {
            if (website_config('main')->is_landing_page_enabled == '') {
                return redirect('auth/login');
            }
            $components['page'] = [
                'contact_us' => WebsitePage::where('title', 'Kontak Kami')->first(),
                'faq'        => WebsitePage::where('title', 'Pertanyaan Umum')->first(),
                'tos'        => WebsitePage::where('title', 'Ketentuan Layanan')->first(),
            ];
			return view('landing', $components);
		}
	}
	public function logout() {
		if (Auth::check() == false) return redirect('auth/login');
		if (Session::has('information_popup') == true) Session::forget('information_popup');
		if (Cookie::has('user') == true) {
			UserCookie::where('value', Cookie::get('user'))->delete();
			Cookie::queue(Cookie::forget('user'));
		}
		Auth::logout();
        return redirect('auth/login')->with('result', [
			'alert'   => 'success', 
			'title'   => 'Berhasil', 
			'message' => 'Sampai jumpa lagi...',
            'timeout' => 5000,
            'size'    => 'col-lg-6 offset-lg-3'
		]);
    }
}