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

class Analytics extends MY_Controller {
    
    public function __construct() {
        parent::__construct();
        $this->load->model('Analytics_model');
    }

    /**
     * Track click events
     * POST /api/analytics/track-click
     */
    public function track_click() {
        if ($this->input->method() !== 'post') {
            $this->response['message'] = 'Method not allowed';
            $this->output->set_status_header(405)->set_output(json_encode($this->response));
            return;
        }

        $json_input = json_decode($this->input->raw_input_stream, true);
        
        $click_data = [
            'event_type' => $json_input['event_type'] ?? 'click',
            'element_type' => $json_input['element_type'] ?? '',
            'element_id' => $json_input['element_id'] ?? '',
            'url' => $json_input['url'] ?? '',
            'section' => $json_input['section'] ?? '',
            'label' => $json_input['label'] ?? '',
            'user_id' => $json_input['user_id'] ?? null,
            'user_agent' => $json_input['user_agent'] ?? '',
            'referrer' => $json_input['referrer'] ?? '',
            'page_url' => $json_input['page_url'] ?? '',
            'ip_address' => $this->input->ip_address(),
            'created_at' => date('Y-m-d H:i:s')
        ];

        try {
            $result = $this->Analytics_model->log_click($click_data);
            
            if ($result) {
                $this->response['status'] = true;
                $this->response['message'] = 'Click tracked successfully';
                $this->response['data'] = ['click_id' => $result];
            } else {
                $this->response['message'] = 'Failed to track click';
            }
        } catch (Exception $e) {
            $this->response['message'] = 'Error tracking click: ' . $e->getMessage();
        }

        $this->output->set_output(json_encode($this->response));
    }

    /**
     * Get click analytics data
     * GET /api/analytics/clicks
     */
    public function clicks() {
        if ($this->input->method() !== 'get') {
            $this->response['message'] = 'Method not allowed';
            $this->output->set_status_header(405)->set_output(json_encode($this->response));
            return;
        }

        $filters = [
            'start_date' => $this->input->get('start_date'),
            'end_date' => $this->input->get('end_date'),
            'element_type' => $this->input->get('element_type'),
            'section' => $this->input->get('section'),
            'limit' => (int)($this->input->get('limit') ?? 100),
            'offset' => (int)($this->input->get('offset') ?? 0)
        ];

        try {
            $clicks = $this->Analytics_model->get_clicks($filters);
            $total_clicks = $this->Analytics_model->count_clicks($filters);
            
            $this->response['status'] = true;
            $this->response['message'] = 'Click data retrieved successfully';
            $this->response['data'] = [
                'clicks' => $clicks,
                'total' => $total_clicks,
                'filters' => $filters
            ];
        } catch (Exception $e) {
            $this->response['message'] = 'Error retrieving clicks: ' . $e->getMessage();
        }

        $this->output->set_output(json_encode($this->response));
    }

    /**
     * Get monthly click statistics
     * GET /api/analytics/monthly-stats
     */
    public function monthly_stats() {
        if ($this->input->method() !== 'get') {
            $this->response['message'] = 'Method not allowed';
            $this->output->set_status_header(405)->set_output(json_encode($this->response));
            return;
        }

        $year = $this->input->get('year') ?? date('Y');
        $month = $this->input->get('month'); // New parameter for specific month
        $element_type = $this->input->get('element_type');

        try {
            if ($month) {
                // Get specific month data
                $monthly_specific_stats = $this->Analytics_model->get_monthly_specific_stats($year, $month, $element_type);
                $top_clicked = $this->Analytics_model->get_top_clicked_elements($year, $element_type);
                
                $this->response['status'] = true;
                $this->response['message'] = 'Specific month statistics retrieved successfully';
                $this->response['data'] = [
                    'year' => $year,
                    'month' => $month,
                    'month_name' => date('F', mktime(0, 0, 0, $month, 1)),
                    'monthly_specific_stats' => $monthly_specific_stats,
                    'top_clicked' => $top_clicked
                ];
            } else {
                // Get all months for the year
                $monthly_stats = $this->Analytics_model->get_monthly_stats($year, $element_type);
                $top_clicked = $this->Analytics_model->get_top_clicked_elements($year, $element_type);
                
                $this->response['status'] = true;
                $this->response['message'] = 'Monthly statistics retrieved successfully';
                $this->response['data'] = [
                    'year' => $year,
                    'monthly_stats' => $monthly_stats,
                    'top_clicked' => $top_clicked
                ];
            }
        } catch (Exception $e) {
            $this->response['message'] = 'Error retrieving statistics: ' . $e->getMessage();
        }

        $this->output->set_output(json_encode($this->response));
    }

    /**
     * Get YouTube click analytics
     * GET /api/analytics/youtube-stats
     */
    public function youtube_stats() {
        if ($this->input->method() !== 'get') {
            $this->response['message'] = 'Method not allowed';
            $this->output->set_status_header(405)->set_output(json_encode($this->response));
            return;
        }

        $period = $this->input->get('period') ?? 'month'; // month, year, all, or specific month
        $year = $this->input->get('year');
        $month = $this->input->get('month');
        
        try {
            $youtube_stats = $this->Analytics_model->get_youtube_stats($period, $year, $month);
            
            $this->response['status'] = true;
            $this->response['message'] = 'YouTube statistics retrieved successfully';
            $this->response['data'] = $youtube_stats;
        } catch (Exception $e) {
            $this->response['message'] = 'Error retrieving YouTube stats: ' . $e->getMessage();
        }

        $this->output->set_output(json_encode($this->response));
    }
}