<?
namespace controls;
class Api
{
  static public function campaigns_data_save()
  {
    global $mdb;

    $json = file_get_contents( 'php://input' );
    $data = json_decode( $json, true );

    if ( $data['clientId'] and $data['date'] )
    {
      foreach ( $data['data'] as $campaign )
      {
        if ( !$mdb -> count( 'campaigns', [ 'AND' => [ 'client_id' => $data['clientId'], 'campaign_id' => $campaign['campaignId'] ] ] ) )
        {
          $campaign_data['client_id'] = $data['clientId'];
          $campaign_data['campaign_id'] = $campaign['campaignId'];
          $campaign_data['campaign_name'] = $campaign['camapignName'];

          $mdb -> insert( 'campaigns', [
            'client_id' => $data['clientId'],
            'campaign_id' => $campaign['campaignId'],
            'campaign_name' => $campaign['camapignName']
          ] );

          $campaign_id = $mdb -> id();
        }
        else
        {
          $campaign_id = $mdb -> get( 'campaigns', 'id', [ 'AND' => [ 'client_id' => $data['clientId'], 'campaign_id' => $campaign['campaignId'] ] ] );
        }

        if ( $campaign_id )
        {
          $campaign_history_data = [];
          $campaign_history_data['roas_30_days'] = $campaign['roas30Days'];
          $campaign_history_data['roas_all_time'] = $campaign['roasAllTime'];
          $campaign_history_data['budget'] = str_replace( ' zł', '' , $campaign['budget'] );
          $campaign_history_data['money_spent'] = floatval( preg_replace(['/[^0-9,]/', '/,/'], ['', '.'], $campaign['spend30Days'] ) );
          $campaign_history_data['conversion_value'] = preg_replace( '/[^\d,.-]/', '', $campaign['conversionValue30Days'] );

          if ( isset( $campaign['biddingStrategy'] ) and $campaign['biddingStrategy'] == 'MAXIMIZE_CONVERSIONS' )
          {
            $campaign_history_data['bidding_strategy'] = 'Maksymalizacja liczby konwersji';
          }
          else if ( isset( $campaign['biddingStrategy'] ) and $campaign['biddingStrategy'] == 'MAXIMIZE_CONVERSION_VALUE' )
          {
            $campaign_history_data['bidding_strategy'] = 'Maksymalizacja wartości konwersji';
          }
          else if ( isset( $campaign['biddingStrategy'] ) and $campaign['biddingStrategy'] == 'TARGET_ROAS' )
          {
            $campaign_history_data['bidding_strategy'] = 'Docelowy ROAS';
          }
          else if ( isset( $campaign['biddingStrategy'] ) )
          {
            $campaign_history_data['bidding_strategy'] = $campaign['biddingStrategy'];
          }
          else
          {
            $campaign_history_data['bidding_strategy'] = 'brak';
          }

          if ( isset( $campaign['targetRoas'] ) and (float)$campaign['targetRoas'] > 0 )
          {
            $campaign_history_data['bidding_strategy'] .= ' | docelowy ROAS: ' . ( (float)$campaign['targetRoas'] * 100 ) . '%';
          }

          if ( $mdb -> count( 'campaigns_history', [ 'AND' => [ 'campaign_id' => $campaign_id, 'date_add' => $data['date'] ] ] ) )
          {
            $mdb -> update( 'campaigns_history', $campaign_history_data, [ 'AND' => [ 'campaign_id' => $campaign_id, 'date_add' => $data['date'] ] ] );
          }
          else
          {
            $campaign_history_data['campaign_id'] = $campaign_id;
            $campaign_history_data['date_add'] = $data['date'];

            $mdb -> insert( 'campaigns_history', $campaign_history_data );
          }
        }
      }
    }

    echo json_encode( [ 'status' => 'ok' ] );
    exit;
  }

  static public function phrases_data_save()
  {
    global $mdb;

    $json = file_get_contents( 'php://input' );
    $data = json_decode( $json, true );

    if ( $data['client_id'] and $data['date'] )
    {
      foreach ( $data['data'] as $phrase )
      {
        $phrase_data = [];

        if ( !$mdb -> count( 'phrases', [ 'AND' => [ 'client_id' => $data['client_id'], 'phrase' => $phrase['Query'] ] ] ) )
        {
          $phrase_data['phrase'] = $phrase['Query'];

          $mdb -> insert( 'phrases', [
            'client_id' => $data['client_id'],
            'phrase' => $phrase['Query']
          ] );

          $phrase_id = $mdb -> id();
        }
        else
        {
          $phrase_id = $mdb -> get( 'phrases', 'id', [ 'AND' => [ 'client_id' => $data['client_id'], 'phrase' => $phrase['Query'] ] ] );
        }

        if ( $phrase_id )
        {
          $phrase_data['impressions'] = $phrase['Impressions'];
          $phrase_data['clicks'] = $phrase['Clicks'];
          $phrase_data['cost'] = $phrase['Cost'];
          $phrase_data['conversions'] = $phrase['Conversions'];
          $phrase_data['conversions_value'] = preg_replace( '/[^\d,.-]/', '', $phrase['ConversionValue'] );
          $phrase_data['updated'] = 1;

          if ( $mdb -> count( 'phrases_history', [ 'AND' => [ 'phrase_id' => $phrase_id, 'date_add' => $data['date'] ] ] ) )
          {
            $phrase_data_old = [];

            $phrase_data_old = $mdb -> get( 'phrases_history', '*', [ 'AND' => [ 'phrase_id' => $phrase_id, 'date_add' => $data['date'] ] ] );

            if (
              $phrase_data_old['impressions'] == $phrase_data['impressions']
              and $phrase_data_old['clicks'] == $phrase_data['clicks']
              and number_format((float)str_replace(',', '.', $phrase_data_old['cost']), 5) == number_format((float)$phrase_data['cost'], 5)
              and $phrase_data_old['conversions'] == $phrase_data['conversions']
              and number_format((float)str_replace(',', '.', $phrase_data_old['conversions_value']), 5) == number_format((float)$phrase_data['conversions_value'], 5)
            ) {
              continue;
            }

            $mdb -> update( 'phrases_history', [
              'impressions' => $phrase_data['impressions'],
              'clicks' => $phrase_data['clicks'],
              'cost' => $phrase_data['cost'],
              'conversions' => $phrase_data['conversions'],
              'conversions_value' => $phrase_data['conversions_value'],
              'updated' => 1
            ], [
              'AND' => [ 'phrase_id' => $phrase_id, 'date_add' => $data['date'] ]
            ] );
          }
          else
          {
            $mdb -> insert( 'phrases_history', [
              'phrase_id' => $phrase_id,
              'date_add' => $data['date'],
              'impressions' => $phrase_data['impressions'],
              'clicks' => $phrase_data['clicks'],
              'cost' => $phrase_data['cost'],
              'conversions' => $phrase_data['conversions'],
              'conversions_value' => $phrase_data['conversions_value'],
              'updated' => 1
            ] );
          }
        }
      }
    }

    echo json_encode( [ 'status' => 'ok' ] );
    exit;
  }

  static public function products_data_save()
  {
    global $mdb;

    $json = file_get_contents( 'php://input' );
    $data = json_decode( $json, true );
    // file_put_contents( 'tmp/products_data_save.txt', print_r( $data, true ) );
    if ( $data['client_id'] and $data['date'] )
    {
      foreach ( $data['data'] as $offer )
      {
        $offer_data = [];

        if ( !$mdb -> count( 'products', [ 'AND' => [ 'client_id' => $data['client_id'], 'offer_id' => $offer['OfferId'] ] ] ) )
        {
          $offer_data['client_id'] = $data['client_id'];
          $offer_data['offer_id'] = $offer['OfferId'];
          $offer_data['offer_name'] = $offer['ProductTitle'];

          $mdb -> insert( 'products', [
            'client_id' => $data['client_id'],
            'offer_id' => $offer['OfferId'],
            'name' => $offer['ProductTitle']
          ] );

          $offer_id = $mdb -> id();
        }
        else
        {
          $offer_id = $mdb -> get( 'products', 'id', [ 'AND' => [ 'client_id' => $data['client_id'], 'offer_id' => $offer['OfferId'] ] ] );

          $offer_current_name = $mdb -> get( 'products', 'name', [ 'AND' => [ 'client_id' => $data['client_id'], 'offer_id' => $offer['OfferId'] ] ] );

          if ( $offer_current_name != $offer['ProductTitle'] and $data['date'] == date( 'Y-m-d', strtotime( '-1 days', time() ) ) )
          {
            $mdb -> update( 'products', [ 'name' => $offer['ProductTitle'] ], [ 'AND' => [ 'client_id' => $data['client_id'], 'offer_id' => $offer['OfferId'] ] ] );
          }
        }

        if ( $offer_id )
        {
          $offer_data['impressions'] = $offer['Impressions'];
          $offer_data['clicks'] = $offer['Clicks'];
          $offer_data['ctr'] = round( $offer['Clicks'] / $offer['Impressions'], 4 ) * 100;
          $offer_data['cost'] = preg_replace( '/[^\d,.-]/', '', $offer['Cost'] );
          $offer_data['conversions'] = $offer['Conversions'];
          $offer_data['conversions_value'] = preg_replace( '/[^\d,.-]/', '', $offer['ConversionValue'] );
          $offer_data['updated'] = 1;

          if ( $mdb -> count( 'products_history', [ 'AND' => [ 'product_id' => $offer_id, 'date_add' => $data['date'] ] ] ) )
          {
            $offer_data_old = [];

            $offer_data_old = $mdb -> get( 'products_history', '*', [ 'AND' => [ 'product_id' => $offer_id, 'date_add' => $data['date'] ] ] );

            if (
              $offer_data_old['impressions'] == $offer_data['impressions']
              and $offer_data_old['clicks'] == $offer_data['clicks']
              and number_format((float)str_replace(',', '.', $offer_data_old['cost']), 5) == number_format((float)$offer_data['cost'], 5)
              and $offer_data_old['conversions'] == $offer_data['conversions']
              and number_format((float)str_replace(',', '.', $offer_data_old['conversions_value']), 5) == number_format((float)$offer_data['conversions_value'], 5)
            ) {
              continue;
            }

            $mdb -> update( 'products_history', [
              'impressions' => $offer_data['impressions'],
              'clicks' => $offer_data['clicks'],
              'ctr' => $offer_data['ctr'],
              'cost' => $offer_data['cost'],
              'conversions' => $offer_data['conversions'],
              'conversions_value' => $offer_data['conversions_value'],
              'updated' => 1
            ], [
              'AND' => [ 'product_id' => $offer_id, 'date_add' => $data['date'] ]
            ] );
          }
          else
          {
            $mdb -> insert( 'products_history', [
              'product_id' => $offer_id,
              'date_add' => $data['date'],
              'impressions' => $offer_data['impressions'],
              'clicks' => $offer_data['clicks'],
              'ctr' => $offer_data['ctr'],
              'cost' => $offer_data['cost'],
              'conversions' => $offer_data['conversions'],
              'conversions_value' => $offer_data['conversions_value'],
              'updated' => 1
            ] );
          }
        }
      }
    }

    echo json_encode( [ 'status' => 'ok' ] );
    exit;
  }
}