<?php
/**
 * Class represents records from table aff_clicks
 * {autogenerated}
 * @property int $log_id 
 * @property int $aff_id 
 * @property int $banner_id
 * @property datetime $time 
 * @property string $url 
 * @property string $remote_addr 
 * @property string $referer 
 * @see Am_Table
 */

class AffClick extends Am_Record { }

class AffClickTable extends Am_Table {
    protected $_key = 'log_id';
    protected $_table = '?_aff_click';
    protected $_recordClass = 'AffClick';
  
    public function insert(array $values, $returnInserted = false)
    {
        if (empty($values['time']))
            $values['time'] = $this->getDi()->sqlDateTime;
        return parent::insert($values, $returnInserted);
    }
    
    function log(User $aff, AffBanner $banner = null)
    {
        $this->_db->query("INSERT INTO ?_aff_click
            SET
                aff_id=?d,
                time=?,
                banner_id=?d,
                remote_addr=?,
                referer=?
            ", 
            $aff->pk(), 
            $this->getDi()->sqlDateTime,
            $banner ? $banner->pk() : null, 
            $_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_REFERER']
        );
        return $this->_db->selectCell("SELECT LAST_INSERT_ID()");
    }

    function fetchByDate($date, $aff_id=null)
    {
        return $this->selectObjects(
                "SELECT * FROM ?_aff_click WHERE time BETWEEN ? AND ? { AND aff_id=?d}",
                date('Y-m-d 00:00:00', amstrtotime($date)), date('Y-m-d 23:59:59', amstrtotime($date)), 
                $aff_id === null ? DBSIMPLE_SKIP : $aff_id); 
    }
    /**
     * Find affililate by IP address if cookie is empty
     * @param type $ip 
     * @return last aff_id in record with matching IP 
     */
    function findAffIdByIp($ip)
    {
        $startTm = sqlTime($this->getDi()->time - $this->getDi()->config->get('aff.cookie_lifetime', 365) * 24 * 3600);
        return $this->_db->selectCell("SELECT CONCAT(aff_id, '-', IFNULL(banner_id, ''))
            FROM $this->_table
            WHERE time >= ? AND remote_addr=? AND aff_id>0
            ORDER BY time DESC
            LIMIT 1", $startTm, $ip);
    }
}
