<?php

namespace System;

class Revenue{

    public $group, $country, $dbo, $uid;

    public $group_a = ['united states', 'united kingdom'];
    public $group_b = ['netherlands', 'germany', 'france', 'canada', 'australia'];
    public $group_c = ['spain', 'iran'];

    public function make($uid){

    $this->uid = $uid;
    
    // check cookies
    if(!$this->checkCookies())
        return;

    $this->dbo = DB::getInstance();

    $user_ip = get_client_ip();

    if($user_ip == 'UNKNOWN')
        return;

      $country_query = $this->dbo->query("SELECT 
              c.country  as country
          FROM 
              ip2nationCountries c,
              ip2nation i 
          WHERE 
              i.ip < INET_ATON('$user_ip') 
              AND 
              c.code = i.country 
          ORDER BY 
              i.ip DESC 
          LIMIT 0,1");

    if(!$country_query->count())
        return;
        
    $this->country = strtolower($country_query->first()->country);

    $this->matchGroup();

  }

  public function matchGroup(){
    $country =  $this->country;

    if(in_array($country, $this->group_a)){
        $this->group = 'a';
    }elseif(in_array($country, $this->group_b)){
        $this->group = 'b';
    }elseif(in_array($country, $this->group_c)){
        $this->group = 'c';
    }else{
        $this->group = 'd';
    }

    $this->processGroup();

  }

  public function processGroup(){

    $group = $this->group;

    $get_rate = $this->dbo->query("SELECT payment_rates.rate FROM payment_rates WHERE payment_rates.group = ?", [$group])->first()->rate;

    // add one up
    $this->dbo->query("UPDATE links SET views = views + 1 WHERE uid = ?", [$this->uid]);

    $revenue = roundMoney($get_rate / 1000);

    $this->dbo->query("UPDATE links SET revenue = revenue + ? WHERE uid = ?", [$revenue, $this->uid]);

    return;

  }

  public function checkCookies(){

     if(!Cookie::exists('links')){
        $cookie = [];
     }else{
        $cookie = unserialize(Cookie::get('links'));
     }

     foreach ($cookie as $key => $value)
            if($value < time()) unset($cookie[$key]);

     if(isset($cookie[md5($this->uid)]))
        return false;

     $cookie[md5($this->uid)] = time() + 86400;

     Cookie::put('links', serialize($cookie));

     return  true;
  }

}