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

class Banner extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->model('Banner_model');
        $this->load->library('session');
    }

    /**
     * Track banner click and redirect to target URL
     */
    public function track_click($banner_id)
    {
        // Get banner details
        $banner = $this->Banner_model->get_banner($banner_id);
        
        if (!$banner) {
            show_404();
        }

        // Get user IP address
        $user_ip = $this->input->ip_address();
        
        // Track the click
        $this->Banner_model->increment_banner_click($banner_id, $user_ip);
        
        // Redirect to banner URL
        if ($banner->link_url) {
            redirect($banner->link_url);
        } else {
            redirect('/');
        }
    }

    /**
     * AJAX endpoint for tracking banner clicks
     */
    public function track_click_ajax()
    {
        // Check if this is an AJAX request
        if (!$this->input->is_ajax_request()) {
            show_404();
        }

        $banner_id = $this->input->post('banner_id');
        
        if (!$banner_id) {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode(['success' => false, 'message' => 'Invalid banner ID']));
            return;
        }

        // Get banner details
        $banner = $this->Banner_model->get_banner($banner_id);
        
        if (!$banner) {
            $this->output
                ->set_content_type('application/json')
                ->set_output(json_encode(['success' => false, 'message' => 'Banner not found']));
            return;
        }

        // Get user IP address
        $user_ip = $this->input->ip_address();
        
        // Track the click
        $this->Banner_model->increment_banner_click($banner_id, $user_ip);
        
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode(['success' => true, 'message' => 'Click tracked successfully']));
    }

    /**
     * Get banner statistics
     */
    public function stats($banner_id)
    {
        // Check if user is admin
        if (!$this->session->userdata('is_admin')) {
            show_404();
        }

        $banner = $this->Banner_model->get_banner_with_clicks($banner_id);
        
        if (!$banner) {
            show_404();
        }

        $data['banner'] = $banner;
        $data['clicks_by_date'] = $this->Banner_model->get_banner_clicks_by_date($banner_id);
        
        $this->load->view('admin/banner_stats', $data);
    }
}
