<?php
namespace controls;

class Feeds
{
  static public function main_view()
  {
    global $mdb;

    // Sprawdz czy kolumna deleted istnieje
    $has_deleted = false;
    try
    {
      $stmt = $mdb -> pdo -> prepare( "SHOW COLUMNS FROM clients LIKE 'deleted'" );
      $stmt -> execute();
      $has_deleted = (bool) $stmt -> fetch( \PDO::FETCH_ASSOC );
    }
    catch ( \Throwable $e ) {}

    $not_deleted_sql = $has_deleted ? 'COALESCE( deleted, 0 ) = 0' : '1=1';

    $clients = $mdb -> query(
      "SELECT id, name, google_merchant_account_id
       FROM clients
       WHERE " . $not_deleted_sql . "
         AND google_merchant_account_id IS NOT NULL
         AND google_merchant_account_id <> ''
       ORDER BY name ASC"
    ) -> fetchAll( \PDO::FETCH_ASSOC );

    $base_url = ( !empty( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http' )
      . '://' . $_SERVER['HTTP_HOST'];

    $feeds_dir = __DIR__ . '/../../feeds';
    $items = [];

    foreach ( $clients as $client )
    {
      $filename = 'supplemental_' . $client['id'] . '.tsv';
      $file_path = $feeds_dir . '/' . $filename;
      $exists = file_exists( $file_path );

      $items[] = [
        'client_id'   => (int) $client['id'],
        'client_name' => (string) $client['name'],
        'merchant_id' => (string) $client['google_merchant_account_id'],
        'filename'    => $filename,
        'url'         => $base_url . '/feeds/' . $filename,
        'exists'      => $exists,
        'modified_at' => $exists ? date( 'Y-m-d H:i:s', filemtime( $file_path ) ) : null,
        'size'        => $exists ? filesize( $file_path ) : 0,
      ];
    }

    return \view\Feeds::main_view( $items );
  }
}
