<?php

use DeviceDetector\DeviceDetector;
use DeviceDetector\Parser\Device\DeviceParserAbstract;

date_default_timezone_set('Africa/Lagos');

class LoginRecord {

    /**
     * Saves the user device information, ip, location
     *
     * @param User $user
     * @param mysqli $link Database connection
     * @access public
     * @return true or false
     */
    static function saveUserRecords($user, $link) {
        $dd = new DeviceDetector($_SERVER['HTTP_USER_AGENT']);
        $dd->parse();

        function ip_details($ip) {
            $json = @file_get_contents("http://ipinfo.io/{$ip}");
            $details = json_decode($json);
            return $details;
        }

        $details = ip_details($_SERVER['REMOTE_ADDR']);
        $country = isset($details->country) ? Helper::countryName($details->country) : NOT_SET;
        $ip = isset($details->ip) ? ((!filter_var($details->ip, FILTER_VALIDATE_IP)) ? NOT_SET : $details->ip ) : NOT_SET;
        $time = time();
        $browser = $dd->getClient()['name'] . " " . $dd->getClient()['version']; // Eg. Firefox or Chrome
        $device = empty(trim($dd->getDeviceName())) ? NOT_SET : $dd->getDeviceName(); // Eg. Tablet, smartphone or desktop
        $brand = empty(trim($dd->getBrandName())) ? NOT_SET : $dd->getBrandName(); // Eg Samsung or Apple
        $model = empty(trim($dd->getModel())) ? NOT_SET : $dd->getModel(); // Phone model eg. Galaxy s8
        $os = $dd->getOs()['name'] . " " . $dd->getOs()['version']; // OS version eg. Windows 10
        return mysqli_query($link, "insert INTO `loginrecords` (`user`,`browser`,`device`,`ip`,`location`,`timeDate`,`brand`,`model`,`os`) VALUES ('{$user->getEmail()}','$browser','$device','$ip', '$country', '$time', '$brand', '$model', '$os')");
    }

}
