<?php
namespace controls;

class Allegro {

  static public function main_view()
  {
    $offers_added = null;
    $history_added = null;
    $history_updated = null;

    if ( \S::get_session( 'offers_added' ) )
    {
      $offers_added = \S::get_session( 'offers_added' );
      \S::del_session( 'offers_added' );
    }

    if ( \S::get_session( 'history_added' ) )
    {
      $history_added = \S::get_session( 'history_added' );
      \S::del_session( 'history_added' );
    }

    if ( \S::get_session( 'history_updated' ) )
    {
      $history_updated = \S::get_session( 'history_updated' );
      \S::del_session( 'history_updated' );
    }

    return \Tpl::view( 'allegro/main_view', [
      'clients' => \factory\Campaigns::get_clients(),
      'offers_added' => $offers_added,
      'history_added' => $history_added,
      'history_updated' => $history_updated
    ] );
  }

  static public function import_data()
  {
    global $mdb;

    $offers_added = 0;
    $history_added = 0;
    $history_updated = 0;
    $data = [];

    if ( !isset( $_FILES['file'] ) || $_FILES['file']['error'] !== UPLOAD_ERR_OK )
    {
      \S::alert( 'error', 'Nieprawidłowy plik. Wybierz plik CSV.' );
      header( 'Location: /allegro/main_view/' );
      exit;
    }

    $file = $_FILES['file']['tmp_name'];
    $ext = strtolower( pathinfo( $_FILES['file']['name'], PATHINFO_EXTENSION ) );

    if ( $ext !== 'csv' )
    {
      \S::alert( 'error', 'Dozwolony format pliku: CSV.' );
      header( 'Location: /allegro/main_view/' );
      exit;
    }

    if ( ( $handle = fopen( $file, 'r' ) ) !== false )
    {
      // Pomiń pierwszy wiersz (nagłówki)
      fgetcsv($handle, null, ";");

      while (($row_data = fgetcsv($handle, null, ";")) !== false)
      {
        // Upewnij się, że wiersz jest poprawnie wczytany
        if ( is_array( $row_data ) && count( $row_data ) > 1 )
        {
          $client_name_part_1 = $row_data[0];
          $client_name_part_2 = $row_data[1];

          $offer_id = $row_data[3];
          $date_add = date( 'Y-m-d', strtotime( $row_data[13] ) );

          // Klucz składający się z offer_id i date_add, aby śledzić powtórzenia
          $key = \S::seo( $client_name_part_1 ) . '_' . \S::seo( $client_name_part_2 ) . '_' . $offer_id . '_' . $date_add;

          // Przygotowanie danych z wiersza CSV
          $impressions = (int)$row_data[4];
          $clicks = (int)$row_data[5];
          $cost = \S::to_decimal( str_replace( [' PLN', ','], ['', '.'], $row_data[9] ) );
          $conversions = (int)$row_data[11];
          $conversions_value = \S::to_decimal(str_replace([' PLN', ','], ['', '.'], $row_data[12]));

          // Jeśli ten klucz (offer_id + date_add) już istnieje, sumujemy dane
          if (isset($data[$key]))
          {
            $data[$key]['campaign_name'] = $client_name_part_1;
            $data[$key]['group_name'] = $client_name_part_2;
            $data[$key]['impressions'] += $impressions;
            $data[$key]['clicks'] += $clicks;
            $data[$key]['cost'] += $cost;
            $data[$key]['conversions'] += $conversions;
            $data[$key]['conversions_value'] += $conversions_value;
          }
          else
          {
            // Jeśli klucz nie istnieje, dodajemy nowy wpis
            $data[$key] = [
              'campaign_name' => $client_name_part_1,
              'group_name' => $client_name_part_2,
              'offer_id' => $offer_id,
              'offer_name' => $row_data[2],
              'impressions' => $impressions,
              'clicks' => $clicks,
              'cost' => $cost,
              'conversions' => $conversions,
              'conversions_value' => $conversions_value,
              'date_add' => $date_add
            ];
          }
        }
      }

      // Zamknij plik po przetworzeniu
      fclose( $handle );
    }

    foreach ( $data as $offer )
    {
      $offer_data = [];

      $campaign_name = 'allegro.pl - ' . $offer['campaign_name'] . ' - ' . $offer['group_name'];

      $client_id = $mdb -> get( 'clients', 'id', [ 'name' => $campaign_name ] );
      if ( !$client_id )
      {
        $mdb -> insert( 'clients', [ 'name' => $campaign_name ] );
        $client_id = $mdb -> id();
      }

      if ( !$mdb -> count( 'products', [ 'AND' => [ 'client_id' => $client_id, 'offer_id' => $offer['offer_id'] ] ] ) )
      {
        $product_data = [
          'client_id' => $client_id,
          'offer_id' => $offer['offer_id'],
          'name' => $offer['offer_name'],
        ];

        if ( $mdb -> insert( 'products', $product_data ) )
        {
          $product_id = $mdb -> id();
          $offers_added++;
        }

      }
      else
      {
        $product = $mdb -> get( 'products', [ 'id', 'name' ], [ 'AND' => [ 'client_id' => $client_id, 'offer_id' => $offer['offer_id'] ] ] );
        $product_id = $product['id'];
        $offer_current_name = $product['name'];

        if ( $offer_current_name != $offer['offer_name'] and $offer['date_add'] == date( 'Y-m-d', strtotime( '-1 days', time() ) ) )
        {
          $mdb -> update( 'products', [ 'name' => $offer['offer_name'] ], [ 'AND' => [ 'client_id' => $client_id, 'offer_id' => $offer['offer_id'] ] ] );
          $mdb -> insert( 'products_comments', [ 'product_id' => $product_id, 'comment' => 'Zmiana nazwy oferty na: ' . $offer['offer_name'], 'type' => 2, 'date_add' => $offer['date_add'] ] );
        }
      }

      if ( $offer['offer_id'] )
      {
        $offer_data['impressions'] = $offer['impressions'];
        $offer_data['clicks'] = $offer['clicks'];
        $offer_data['cost'] = $offer['cost'];
        $offer_data['conversions'] = $offer['conversions'];
        $offer_data['conversions_value'] = $offer['conversions_value'];
        $offer_data['ctr'] = $offer['impressions'] ? round( $offer['clicks'] / $offer['impressions'], 4 ) : 0;
        $offer_data['updated'] = 1;

        if ( $mdb -> count( 'products_history', [ 'AND' => [ 'product_id' => $product_id, 'date_add' => $offer['date_add'] ] ] ) )
        {
          $mdb -> update( 'products_history', $offer_data, [ 'AND' => [ 'product_id' => $product_id, 'date_add' => $offer['date_add'] ] ] );
          $history_updated++;
        }
        else
        {
          $offer_data['product_id'] = $product_id;
          $offer_data['date_add'] = $offer['date_add'];
          $mdb -> insert( 'products_history', $offer_data );
          $history_added++;
        }
      }
    }

    \S::set_session( 'offers_added', $offers_added );
    \S::set_session( 'history_added', $history_added );
    \S::set_session( 'history_updated', $history_updated );

    header( 'Location: /allegro/main_view/' );
    exit;
  }
}