<?php
require_once dirname( __FILE__ ) . '/config.php';

$grid = $_SESSION[ 'g-upload-' . $_POST[ 'gtable' ] ];
if ( is_a( $grid, 'gridUpload' ) )
{
  if ( $grid -> dir_upload === null )
  {
    $response = [ 'status' => 'error', 'msg' => 'Proszę zdefiniować ściężkę do wysłania pliku.' ];
    echo json_encode( $response );
    exit;
  }
  
  if ( !empty( $_FILES["file"] ) )
  {
    if ( $_FILES["file"]["error"] > 0 )
    {
      $response = [ 'status' => 'error' ];
    }
    else
    {
      $file_dir   = $grid -> dir_upload;
      $dir_abs    = $grid -> dir_upload_abs . $grid -> dir_upload;
      
      if ( !is_dir( $dir_abs ) )
        mkdir( $dir_abs, 0777, true );

      $file_name  = pathinfo( $_FILES['file']['name'], PATHINFO_FILENAME );
      $file_ext   = pathinfo( $_FILES['file']['name'], PATHINFO_EXTENSION );
      
      if ( !in_array( $file_ext, $grid -> allowed_extensions ) )
      {
        $response = [ 'status' => 'error', 'msg' => 'Nieprawidłowe rozszerzenie pliku. Dozwolone rozszerzenia: <b>' . implode( ', ', $grid -> allowed_extensions ) . '</b>.' ];
        echo json_encode( $response );
        exit;
      }
      
      $response = [ 'status' => 'error', 'msg' => $file_name ];
      
      while ( file_exists( $dir_abs . DIRECTORY_SEPARATOR . $file_name . $count . '.' . $file_ext ) )
        $count++;
      
      $file_name  = $file_name . $count . '.' . $file_ext;
      
      move_uploaded_file( $_FILES["file"]["tmp_name"], $dir_abs . DIRECTORY_SEPARATOR . $file_name );
      
      if ( $grid -> db !== null )
      {
        if ( is_array( $_POST ) ) foreach ( $_POST as $key => $val )
        {
          if ( $key != 'gtable' )
            $columns[ $key ] = $val;
        }
        $columns[ $grid -> db['file_column'] ] = $file_dir . DIRECTORY_SEPARATOR . $file_name;
        
        if ( $file_id = $grid -> connectToDb() -> insert( $grid -> db['table'] , $columns ) )
        {
          $columns[ 'id' ] = $file_id;
          
          $response = [ 'status' => 'ok', 'file' => $columns ];
        }
      }
      else
        $response = [ 'status' => 'ok', 'file' => [ 'src' => $file_dir . DIRECTORY_SEPARATOR . $file_name ] ];
    }
  }
  else
    $response = [ 'status' => 'error', 'msg' => 'Niewybrano pliku lub plik jest zbyt duży.' ];
  echo json_encode( $response );
  exit;
}