<?php
// +-------------------------------------------------+
// | 2002-2011 PMB Services / www.sigb.net pmb@sigb.net et contributeurs (voir www.sigb.net)
// +-------------------------------------------------+
// $Id: list_graphs_campaigns_ui.class.php,v 1.1.2.8 2026/07/24 10:19:01 dgoron Exp $
if (stristr($_SERVER['REQUEST_URI'], ".class.php")) die("no access");

class list_graphs_campaigns_ui extends list_graphs_ui {
    
    protected static $num_campaigns;
    
    protected $campaigns;

    /**
     * Instances de stats
     * @var campaign_stats
     */
    protected static $campaign_stats;
    
    protected $campaigns_view;
    
    protected function _init_graphs() {
        switch ($this->filters['model']) {
            case 'standard':
            default:
                //Affichage de l'histogramme d'ouverture et de clics par campagnes
                $this->add_graph('opening_and_clicks', '', 'bar');
                //Affichage de l'histogramme d'ouvertures par localisation par campagnes
                $this->add_graph('opening', 'recipients', 'bar', ['group_by' => 'location']); //location
                //Affichage de l'histogramme d'ouvertures par catégorie par campagnes
                $this->add_graph('opening', 'recipients', 'bar', ['group_by' => 'categ']); //categ
                
                //Affichage de l'histogramme de clics par localisation par campagnes
                $this->add_graph('clicks', 'recipients', 'bar', ['group_by' => 'location']); //location
                //Affichage de l'histogramme de clics par catégorie par campagnes
                $this->add_graph('clicks', 'recipients', 'bar', ['group_by' => 'categ']); //categ
                break;
        }
    }
    
    public function get_graph_title($name, $settings = []) {
        global $msg;
        
        if (!empty($settings['group_by']) && isset($msg['campaigns_view_' . $name."_".$settings['group_by']])) {
            return $msg['campaigns_view_' . $name."_".$settings['group_by']];
        }
        return $msg['campaigns_view_' . $name] ?? '';
    }
    
    public function get_graph_labels($name, $settings = []) {
        $labels = [];
        foreach (static::$num_campaigns as $num_campaign) {
            $campaign = new campaign($num_campaign);
            $labels[] = strip_tags($campaign->get_dated_label());
        }
        return $labels;
    }
    
    public function get_graph_datasets($name, $settings = []) {
        global $msg;
        
        $this->get_campaigns();
        switch ($name) {
            case 'opening_and_clicks':
                $opening_rates = [];
                $clicks_rates  = [];
                foreach ($this->campaigns as $campaign) {
                    $stats      = $this->get_campaign_stats($campaign->get_id());
                    $recipients = (int) $stats->get_recipients_number();
                    $opening    = $stats->get_opening(true);
                    $clicks     = $stats->get_clicks(true);
                    $opening_rates[] = $recipients > 0 ? round($opening / $recipients * 100, 2) : 0;
                    $clicks_rates[]  = $recipients > 0 ? round($clicks  / $recipients * 100, 2) : 0;
                }
                return [
                    ['label' => $msg['campaign_view_opening_rate'], 'kind' => 'opening', 'data' => $opening_rates],
                    ['label' => $msg['campaign_view_clicks_rate'],  'kind' => 'clicks',  'data' => $clicks_rates],
                ];
            case 'opening_by_recipients':
            case 'clicks_by_recipients':
                $element      = $settings['group_by'];
                $method       = 'get_' . $name;
                $total_method = (strpos($name, 'opening') !== false) ? 'get_opening' : 'get_clicks';
                $possible_vals = campaign_recipients::get_possible_values_of_field(static::$num_campaigns, $element);
                $series        = array_fill_keys($possible_vals, array_fill(0, count($this->campaigns), 0));
                $i             = 0;
                foreach ($this->campaigns as $campaign) {
                    $stats  = $this->get_campaign_stats($campaign->get_id());
                    $total  = $stats->{$total_method}(true);
                    $values = $stats->{$method}($element, true);
                    foreach ($values as $value_key => $count) {
                        if (array_key_exists($value_key, $series)) {
                            $series[$value_key][$i] = $total > 0 ? round($count / $total * 100, 2) : 0;
                        }
                    }
                    $i++;
                }
                $datasets = [];
                foreach ($series as $label => $data) {
                    $datasets[] = ['label' => (string) $label, 'data' => $data];
                }
                return $datasets;
        }
    }
    
    public function get_graph_options($name, $settings = []) {
        global $msg;
        
        switch ($name) {
            case 'opening_and_clicks':
            case 'opening_by_recipients':
            case 'clicks_by_recipients':
                return [
                    'scales' => [
                        'y' => [
                            'min' => 0,
                            'max' => 100,
                            'ticks' => ['stepSize' => 25],
                            'title' => ['display' => true, 'text' => $msg['campaigns_view_rate']],
                        ]
                    ]
                ];
            default:
                return [];
        }
    }
    
    /**
     * Affichage du formulaire de recherche
     */
    public function get_search_form() {
        return $this->get_search_buttons_extension();
    }
    
    /**
	 * Affichage de la liste des objets
	 * @return string
	 */
// 	public function get_display_objects_list() {
// 	    $campaigns_view = $this->get_campaigns_view();
// 		$view = "
// 			<div class='row'>
// 				".$campaigns_view->get_display_summary()."
// 			</div>";
// 		$view .= "
// 		<div class='row'>";
// 		$view .= parent::get_display_objects_list();
// 		$view .= "</div>";
// 		return $view;
// 	}
    
    /**
     * Objet de la liste
     */
//     protected function get_display_content_object_list($object, $indice) {
//         $display = "<div class='".$this->objects_type."_view_graph campaign_view_graph'>";
//         $list_campaigns_logs_ui = new list_campaigns_logs_ui(array('stat' => $object->name));
//         $display .= $list_campaigns_logs_ui->get_display_graph($object->settings);
//         $display .= "</div>";
//         return $display;
//     }
    
    /**
     * Retourne la vue statistiques de la campagne via vue-chartjs.
     *
     * @return string HTML + script Vue.js
     */
    public function get_display_content_list() {
        global $msg;
        
        $data = [
            'mode'      => 'multi',
            'campaigns' => $this->get_campaigns_view()->get_summary_data(),
            'charts'    => $this->get_campaigns_view()->get_charts_data(),
            'msg'       => [
                'campaign_label'    => $msg['campaign_label'],
                'campaign_date'     => $msg['campaign_date'],
                'recipients_number' => $msg['campaign_view_recipients_number'],
                'opening_rate'      => $msg['campaign_view_opening_rate'],
                'clicks_rate'       => $msg['campaign_view_clicks_rate'],
                'see_detail'        => $msg['campaign_view_see_detail'],
            ],
        ];
        
        $vue_view = new \Pmb\Common\Views\VueJsView('campaigns/campaigns', $data);
        return $vue_view->render();
    }
    
    public static function set_num_campaigns($num_campaigns) {
        static::$num_campaigns = $num_campaigns;
    }
    
    public function get_campaigns() {
        if(!isset($this->campaigns)) {
            $this->campaigns = [];
            foreach (static::$num_campaigns as $num_campaign) {
                $this->campaigns[] = new campaign($num_campaign);
            }
        }
        return $this->campaigns;
    }
    
    /**
     * @param int $campaign_id
     * @return campaign_stats
     */
    public function get_campaign_stats($campaign_id) {
        if(!isset(static::$campaign_stats[$campaign_id])) {
            static::$campaign_stats[$campaign_id] = new campaign_stats($campaign_id);
        }
        return static::$campaign_stats[$campaign_id];
    }
    
    public function get_campaigns_view() {
        if(!isset($this->campaigns_view)) {
            $this->campaigns_view = new campaigns_view();
            foreach (static::$num_campaigns as $num_campaign) {
                $this->campaigns_view->add(new campaign($num_campaign));
            }
        }
        return $this->campaigns_view;
    }
}