<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Event;
use App\Models\User;
use App\Models\Visitor;
use App\Models\Product;
use Session;
use Carbon\Carbon;
use Alert;


class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
        $this->_event = new Event();
        $this->_user = new User();
        $this->_visitor = new Visitor();
        $this->_product = new Product();
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {


        // HomeController::checkuserDetail();
        // return Session::get('customerDetailApiCallDateTime')->format("Y-m-d H:i:s");
        HomeController::checkSubscriptionExpiredWithOnlyAlret();
      
        if (auth()->user()->getUser() && auth()->user()->getUser()->is_admin == "false") {
            return redirect()->route('event.list');
        }
        $data['events'] = $this->_event->countEvents();
        $data['users'] = $this->_user->countUsers2();
        $data['visitors'] = $this->_visitor->countVisitors();
        $data['products'] = $this->_product->countProducts();

        return view('dashboard', $data);
    }

    public static function checkuserDetail()
    {
        // return Session::put('customerDetailApiCallDateTime',now('Asia/Kolkata')->subHours(24));

        $lastCallTime = !empty(Session::get('customerDetailApiCallDateTime')) ? Carbon::parse(Session::get('customerDetailApiCallDateTime')) : null;
        $hour = 12;
        if (empty($lastCallTime) || now('Asia/Kolkata')->diffInHours($lastCallTime) >= $hour) {
            $url = 'https://frenzinsoftwares.com/visitor/webservice_v3/v1/customerdetail';
            $data = [
                "CustomerID" => 0,
                "device_type" => "web",
                "email" => auth()->user()->email,
                "type" => "login"
            ];

            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Content-Type: application/json'
            ]);
            $loginResponse = curl_exec($ch);
            curl_close($ch);
            $loginResponse = json_decode($loginResponse);

            Session::put('customerDetailApiCallDateTime', Carbon::now('Asia/Kolkata'));
            Session::put('expiryDate', $loginResponse->expiry_date);
            Session::put('expiryTitle', $loginResponse->expiry_Title);
            Session::put('expiryMessage', $loginResponse->expiry_message);
            return $loginResponse;
        }
    }
    public static function checkSubscriptionExpired()
    {
        // $expiryDate = !empty(Session::get('expiryDate')) ? Carbon::parse(Session::get('expiryDate')) : null;
        if (empty($expiryDate)) {
            HomeController::checkuserDetail();
        }
        $expiryDate = !empty(Session::get('expiryDate')) ? Carbon::parse(Session::get('expiryDate')) : null;
        if (!empty($expiryDate) && Carbon::parse($expiryDate, 'Asia/Kolkata')->isPast()) {
            return true;
        } else {
            return false;
        }
    }
    public static function checkSubscriptionExpiredWithRedirectBack()
    {
        //not work this method . you need to add method code in controller.
        $isSubscriptionExpired = HomeController::checkSubscriptionExpired();
        if ($isSubscriptionExpired) {
            $expiryTitle = !empty(Session::get('expiryTitle')) ? Session::get('expiryTitle') : "Your Subscription is Expired";
            $expiryMessage = !empty(Session::get('expiryMessage')) ? Session::get('expiryMessage') : "Your Subscription is Expired , Please Contact support for Activation.";

            Alert::error($expiryTitle, $expiryMessage);
            return redirect()->back();
        }
    }
     public static function checkSubscriptionExpiredWithOnlyAlret()
    {
        $isSubscriptionExpired = HomeController::checkSubscriptionExpired();
        if ($isSubscriptionExpired) {
            $expiryTitle = !empty(Session::get('expiryTitle')) ? Session::get('expiryTitle') : "Your Subscription is Expired";
            $expiryMessage = !empty(Session::get('expiryMessage')) ? Session::get('expiryMessage') : "Your Subscription is Expired , Please Contact support for Activation.";

            Alert::error($expiryTitle, $expiryMessage);
        }
    }
    // public function chartjs()  
    // {  
    // $viewer = View::select(DB::raw("SUM(numberofview) as count"))  
    //     ->orderBy("created_at")  
    //     ->groupBy(DB::raw("year(created_at)"))  
    //     ->get()->toArray();  
    // $viewer = array_column($viewer, 'count');  

    // $click = Click::select(DB::raw("SUM(numberofclick) as count"))  
    //     ->orderBy("created_at")  
    //     ->groupBy(DB::raw("year(created_at)"))  
    //     ->get()->toArray();  
    // $click = array_column($click, 'count');  

    // return view('chartjs')  
    //         ->with('viewer',json_encode($viewer,JSON_NUMERIC_CHECK))  
    //         ->with('click',json_encode($click,JSON_NUMERIC_CHECK));  
    // }  
}
