<?php

class Af2AjaxDashboard {

    private $Admin = null;
    
    function __construct($Admin) {
        $this->Admin = $Admin;
    }

    public function get_leads_chart() {
        $year = isset($_POST['year']) ? $_POST['year'] : date('Y');
        $month = isset($_POST['month']) ? $_POST['month'] : date('m');


        $impression_data = unserialize(get_option('af2_impressions_data'));
        $impression_count = isset($impression_data[$year][intval($month)]) ? $impression_data[$year][ intval($month) ] : 0;

        // Difference
        if($year == date('Y') && $month == date('m')) {
            $impression_count = get_option('af2_impressions');
        }

        // Reset
        
        $args = array('year' => $year, 'monthnum' => $month);
        $result = $this->Admin->af2_get_posts('af2_request',$args);

        $newArray = array();

        foreach($result as $res) {
            require_once AF2_MISC_FUNCTIONS_PATH;
            $content = af2_get_post_content($res);
            if($content['dashboard_relevant'] != 'not') array_push($newArray, $res);
        }

        $result = $newArray;

        $response = array();
        $labels = array();

        $total_month_days = cal_days_in_month(0, $month, $year);

        foreach ($result as $post) {
            $pDate = $post->post_date;
            $onlydate = date('d', strtotime($pDate));
            if( isset($response[$onlydate]) ){
                $response[$onlydate] += 1;
            }
            else{
                $response[$onlydate] = 1;
            }
        }

        for ($i=1; $i <= $total_month_days; $i++) { 
            $index = $i < 10 ? "0".$i : $i;
            if( !isset( $response[$index] )){
                $response[$i] = 0;
            }else if($i < 10 ){
                $response[$i] = $response[$index];
                unset($response[$index]);
            }
            $temp_date = $i.'-'.$month.'-'.$year;
            $temp_time = strtotime($temp_date);
            $temp_month=date_i18n('d-F',$temp_time);
            $labels[] = __($temp_month);
        }
        ksort($response);

        $date_obj   = DateTime::createFromFormat('!m', $month);
        $month_name = $date_obj->format('F');
        echo json_encode( array('monthname' => __($month_name), 'data' => $response, 'label'=>$labels, 'impression_count' => $impression_count, 'lead_count' => array_sum($response)) );
        die();
    }
}
