<?php

namespace Drupal\product_importer\Form;

use Drupal\commerce_order\Entity\OrderItem;
use Drupal\commerce_price\Price;
use Drupal\commerce_product\Entity\Product;
use Drupal\commerce_product\Entity\ProductAttribute;
use Drupal\commerce_product\Entity\ProductAttributeValue;
use Drupal\commerce_product\Entity\ProductVariation;
use Drupal\commerce_store\Entity\Store;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\file\Entity\File;
use Drupal\taxonomy\Entity\Term;

class ProductImportForm extends FormBase {

    public function getFormId()
    {
        return "product_import";
    }

    public function buildForm(array $form, FormStateInterface $form_state)
    {
        $form['description'] = [
          '#markup' => '<p>Use this form to upload a CSV file of Data</p>'
        ];

        $validators = [
          'file_validate_extensions' => ['csv']
        ];

        $form['import_csv'] = [
          '#type' => 'managed_file',
          '#title' => t('Upload file here:'),
          '#upload_location' => 'public://importcsv/',
          '#upload_validators' => $validators,
        ];

        $form['submit'] = [
          '#type' => 'submit',
          '#value' => $this->t('Save'),
          '#button_type' => 'primary',
        ];

    return $form;
    }

    public function submitForm(array &$form, FormStateInterface $form_state)
    {
        $csv_file = $form_state->getValue('import_csv');

        $file = File::load($csv_file[0]);

        $file->setPermanent();          //Da bih ga sačuvao u bazi mora biti setovan na permanent.

        $file->save();

        $data = $this->csvtoarray($file->getFileUri(), ';');

        $store = Store::load('1');

//            -----------------         KREIRANJE PROIZVODA         ------------------------
        $i = 1;

        foreach($data as $item) {
            $nesto = file_get_contents($item['Image']);
            $slika = file_save_data(
              $nesto,
              'public://'.pathinfo($item['Image'])['basename'],
              FileSystemInterface::EXISTS_RENAME
            );

//            ---------------      Pozivanje odgovarajućeg terma i kreiranje ako ne postoji       ----------------

            $term = \Drupal::entityTypeManager()
              ->getStorage('taxonomy_term')
              ->loadByProperties(['name' => $item['Category']]);
            if(count($term) > 0){
              $term = reset($term);
            } else {
              $term = Term::create([
                'name' => $item['Category'],
                'vid' => 'products'
              ]);
              $term->save();
//              $term = \Drupal::entityTypeManager()
//                ->getStorage('taxonomy_term')
//                ->loadByProperties(['name' => $item['Category']]);
//              $term = reset($term);
            }


//            --------        Pozivanje odgovarajuce vrednosti atributa i kreiranje ako ne postoji        -----------

              $color = \Drupal::entityTypeManager()
                ->getStorage('commerce_product_attribute_value')
                ->loadByProperties(['name' => $item['Color']]);
              if(count($color) > 0) {
                $color = reset($color);
              } else {
                $color = ProductAttributeValue::create([
                  'attribute' => 'color',
                  'name' => $item['Color']
                ]);
                $color->save();
//                $color = \Drupal::entityTypeManager()
//                  ->getStorage('commerce_product_attribute_value')
//                  ->loadByProperties(['name' => $item['Color']]);
//                $color = reset($color);
              }

//              dsm($color);

              $gender =  \Drupal::entityTypeManager()
                ->getStorage('commerce_product_attribute_value')
                ->loadByProperties(['name' => $item['Gender']]);
              if(count($gender) > 0) {
                $gender = reset($gender);
              } else {
                $gender = ProductAttributeValue::create([
                  'attribute' => 'gender',
                  'name' => $item['Gender']
                ]);
                $gender->save();
//                $gender = \Drupal::entityTypeManager()
//                  ->getStorage('commerce_product_attribute_value')
//                  ->loadByProperties(['name' => $item['Gender']]);
//                $gender = reset($gender);
              }


              $size =  \Drupal::entityTypeManager()
                ->getStorage('commerce_product_attribute_value')
                ->loadByProperties(['name' => $item['Size']]);
              if(count($size) > 0) {
                $size = reset($size);
              } else {
                $size = ProductAttributeValue::create([
                  'attribute' => 'size',
                  'name' => $item['Size']
                ]);
                $size->save();
//                $size = \Drupal::entityTypeManager()
//                  ->getStorage('commerce_product_attribute_value')
//                  ->loadByProperties(['name' => $item['Size']]);
//                $size = reset($size);
              }

//            -------------------       Kreiranje proizvoda i varijacija        -------------------------

            $product = Product::create([
              'type' => 'default',
              'stores' => [1],
              'title' => $item['Title'],
              'body' => $item['Body'],
              'field_category' => $term
              ]
            );
            $variation = ProductVariation::create([
              'title' => $item['Title'],
              'type' => 'default',
              'sku' => $item['SKU'],
              'price' => new Price($item['Price'], 'EUR'),
              'field_stock' => $item['Lager'],
              'field_image' => [
                'target_id' => $slika->id(),
                'alt' => 'Sample',
                'title' => 'Sample file'
                ],
              'attribute_color' => $color,
              'attribute_gender' => $gender,
              'field_size' => $size
            ]);

//            $product[$i]->save();
            $variation->save();
            $product->addVariation($variation);
            $product->save();
        }
        // dsm($variation[1]);
    }

    public static function csvtoarray($filename='', $delimiter) {
        if(!file_exists($filename) || !is_readable($filename)) return false;
        $header = NULL;
        $data = [];

        if(($handle = fopen($filename, 'r')) == true) {
            while (($row = fgetcsv($handle, 10000, $delimiter)) == true)
            {
                if(!$header) {
                    $header = $row;
                } else {
                    $data[] = array_combine($header, $row);
                }
            }
            fclose($handle);
        }
        return $data;
    }

}