<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Option;
use App\Models\Visitor;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests;

class HomeBaseController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    function __construct()
    {
    	$timezone = Option::where('name', 'timezone')->first();
    	// Setting the default timezone
    	date_default_timezone_set($timezone->value);


        $this->visitors = new Visitor;

        $this->visitorInfo();
    }



    /**
     *
     * Get Visitor  Info and insert to the database
     *
     */
    public function visitorInfo()
    {
        // Get User Agent
        $agent  = $_SERVER['HTTP_USER_AGENT'];
        $ip     = $this->getClientIP();

        // Check if the user is logged in
        if( Auth::check() ) :
            // Check if the user has a client role
            if( Auth::user()->hasRole(['client']) ) :

                $entry = $this->visitors->whereDay('created_at', '=', date('d'))->where('ip', $ip)->where('type', 'client')->get();

                if( count($entry) < 1 ) :
                   // Add the visitor info
                    $this->visitors->create([
                        'agent' => $agent,
                        'ip' => $ip,
                        'type' => 'client',
                    ]);
                endif;

 

            endif;

        else:
            // If visitor is a guest

            $entry = $this->visitors->whereDay('created_at', '=', date('d'))->where('ip', $ip)->where('type', 'guest')->get();

            if( count($entry) < 1 ) :
               // Add the visitor info
                $this->visitors->create([
                    'agent' => $agent,
                    'ip' => $ip,
                    'type' => 'guest',
                ]);
            endif;

        endif;

    }



    /**
     *
     * Get Client IP Address
     * @return  integer
     * 
     */
    public function getClientIP() 
    {
        $ip = '';
        if (getenv('HTTP_CLIENT_IP'))
            $ip = getenv('HTTP_CLIENT_IP');
        else if(getenv('HTTP_X_FORWARDED_FOR'))
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        else if(getenv('HTTP_X_FORWARDED'))
            $ip = getenv('HTTP_X_FORWARDED');
        else if(getenv('HTTP_FORWARDED_FOR'))
            $ip = getenv('HTTP_FORWARDED_FOR');
        else if(getenv('HTTP_FORWARDED'))
            $ip = getenv('HTTP_FORWARDED');
        else if(getenv('REMOTE_ADDR'))
            $ip = getenv('REMOTE_ADDR');
        else
            $ip = 'UNKNOWN';
     
        return $ip;   
    }
}
