<?php
namespace controls;
class Campaigns
{
  static public function main_view()
  {
    return \Tpl::view( 'campaigns/main_view', [
      'clients' => \factory\Campaigns::get_clients(),
    ] );
  }

  static public function get_campaigns_list()
  {
    echo json_encode( [ 'campaigns' => \factory\Campaigns::get_campaigns_list( \S::get( 'client_id' ) ) ] );
    exit;
  }

  static public function get_campaign_history_data_table()
  {
    $campaign_id = \S::get( 'campaign_id' );
    $start = \S::get( 'start' );
    $length = \S::get( 'length' );

    $db_results = \factory\Campaigns::get_campaign_history_data( $campaign_id, $start, $length );
    $recordsTotal = \factory\Campaigns::get_records_total_campaign_history_data( $campaign_id );

    $result = [
      'draw' => \S::get( 'draw' ),
      'recordsTotal' => $recordsTotal,
      'recordsFiltered' => $recordsTotal
    ];

    foreach ( $db_results as $row )
    {
      $result['data'][] = [
        $row['date_add'],
        number_format( $row['roas_30_days'], 0, '', ' ' ),
        number_format( $row['roas_all_time'], 0, '', ' ' ),
        \S::number_display( $row['conversion_value'] ),
        \S::number_display( $row['money_spent'] ),
        '',
        $row['bidding_strategy'],
        \S::number_display( $row['budget'] ),
      ];
    }

    echo json_encode( $result );
    exit;
  }

  static public function get_campaign_history_data_table_chart()
  {
    $campaign_id = \S::get( 'campaign_id' );

    $db_result = \factory\Campaigns::get_campaign_history_data( $campaign_id, 0, 1000, true );

    $roas30 = [];
    $roasAllTime = [];
    $budget = [];
    $moneySpent = [];
    $conversionValue = [];
    $dates = [];

    foreach ( $db_result as $row )
    {
      $roas30[] = (float)$row['roas_30_days'];
      $roasAllTime[] = (float)$row['roas_all_time'];
      $budget[] = (float)$row['budget'];
      $moneySpent[] = (float)$row['money_spent'];
      $dates[] = $row['date_add'];
      $conversionValue[] = (float)$row['conversion_value'];
    }

    $chart_data = [
      [
        'name' => 'Roas 30 dni',
        'data' => $roas30,
        'visible' => true
      ], [
        'name' => 'Roas cały okres',
        'data' => $roasAllTime,
        'visible' => true
      ], [
        'name' => 'Budżet',
        'data' => $budget,
        'visible' => false
      ], [
        'name' => 'Wydatki',
        'data' => $moneySpent,
        'visible' => false
      ], [
        'name' => 'Wartość konwersji',
        'data' => $conversionValue,
        'visible' => false
      ]
    ];

    echo json_encode( [
      'chart_data' => $chart_data,
      'dates' => $dates,
      'comments' => []
    ] );
    exit;
  }
}
