<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Banner_click_model extends CI_Model {

    public function __construct()
    {
        parent::__construct();
    }

    public function track_click($banner_id, $user_id = null)
    {
        $data = array(
            'banner_id' => $banner_id,
            'user_id' => $user_id,
            'ip_address' => $this->input->ip_address(),
            'user_agent' => $this->input->user_agent(),
            'clicked_at' => date('Y-m-d H:i:s')
        );
        
        $this->db->insert('banner_clicks', $data);
        return $this->db->insert_id();
    }

    public function get_click_count($banner_id)
    {
        $this->db->where('banner_id', $banner_id);
        return $this->db->count_all_results('banner_clicks');
    }

    public function get_banner_stats($limit = null, $offset = 0, $sort_by = 'clicks', $sort_order = 'desc')
    {
        $this->db->select('b.*, COUNT(bc.id) as click_count');
        $this->db->from('banners b');
        $this->db->join('banner_clicks bc', 'b.id = bc.banner_id', 'left');
        $this->db->group_by('b.id');
        
        // Sorting
        $allowed_sorts = array('click_count', 'title', 'created_at', 'status');
        if (in_array($sort_by, $allowed_sorts)) {
            $this->db->order_by($sort_by, $sort_order);
        } else {
            $this->db->order_by('click_count', 'desc');
        }
        
        if ($limit !== null) {
            $this->db->limit($limit, $offset);
        }
        
        return $this->db->get()->result();
    }

    public function count_total_clicks($banner_id)
    {
        return $this->get_click_count($banner_id);
    }

    public function count_unique_clicks($banner_id)
    {
        $this->db->select('COUNT(DISTINCT ip_address) as unique_clicks');
        $this->db->where('banner_id', $banner_id);
        $result = $this->db->get('banner_clicks')->row();
        return $result ? $result->unique_clicks : 0;
    }

    public function get_clicks_by_date($banner_id, $days = 30)
    {
        $this->db->select('DATE(clicked_at) as date, COUNT(*) as clicks');
        $this->db->where('banner_id', $banner_id);
        $this->db->where('clicked_at >=', date('Y-m-d', strtotime("-$days days")));
        $this->db->group_by('DATE(clicked_at)');
        $this->db->order_by('date', 'asc');
        
        return $this->db->get('banner_clicks')->result();
    }
}
