<?php
namespace controls;

class CampaignAlerts
{
  static private function redirect_to_main_view( $client_id = 0, $page = 1 )
  {
    $client_id = (int) $client_id;
    $page = max( 1, (int) $page );

    $query = [];

    if ( $client_id > 0 )
    {
      $query[] = 'client_id=' . $client_id;
    }

    if ( $page > 1 )
    {
      $query[] = 'page=' . $page;
    }

    $url = '/campaign_alerts';
    if ( !empty( $query ) )
    {
      $url .= '?' . implode( '&', $query );
    }

    header( 'Location: ' . $url );
    exit;
  }

  static public function main_view()
  {
    $client_id = (int) \S::get( 'client_id' );
    $page = max( 1, (int) \S::get( 'page' ) );
    $per_page = 15;
    $offset = ( $page - 1 ) * $per_page;

    \factory\CampaignAlerts::mark_all_seen();
    \factory\CampaignAlerts::delete_old_alerts( 30 );

    $total = \factory\CampaignAlerts::get_alerts_count( $client_id );
    $total_pages = max( 1, (int) ceil( $total / $per_page ) );

    if ( $page > $total_pages )
    {
      $page = $total_pages;
      $offset = ( $page - 1 ) * $per_page;
    }

    return \Tpl::view( 'campaign_alerts/main_view', [
      'clients' => \factory\CampaignAlerts::get_clients(),
      'alerts' => \factory\CampaignAlerts::get_alerts( $client_id, $per_page, $offset ),
      'selected_client_id' => $client_id,
      'page' => $page,
      'total_pages' => $total_pages,
      'total' => $total
    ] );
  }

  static public function delete_selected()
  {
    $client_id = (int) \S::get( 'client_id' );
    $page = max( 1, (int) \S::get( 'page' ) );
    $alert_ids = \S::get( 'alert_ids' );

    if ( !is_array( $alert_ids ) || empty( $alert_ids ) )
    {
      \S::alert( 'Nie zaznaczono alertow do usuniecia.' );
      self::redirect_to_main_view( $client_id, $page );
    }

    $deleted = \factory\CampaignAlerts::delete_alerts( $alert_ids );

    if ( $deleted > 0 )
    {
      \S::alert( $deleted === 1 ? 'Usunieto 1 alert.' : 'Usunieto ' . $deleted . ' alertow.' );
    }
    else
    {
      \S::alert( 'Nie udalo sie usunac zaznaczonych alertow.' );
    }

    self::redirect_to_main_view( $client_id, $page );
  }
}
