<?php
namespace front\factory;

class ShopOrder
{
  public static function order_id( $order_hash )
  {
    global $mdb;
    return $mdb -> get( 'pp_shop_orders', 'id', [ 'hash' => $order_hash ] );
  }

  public static function order_hash( $order_id )
  {
    global $mdb;
    return $mdb -> get( 'pp_shop_orders', 'hash', [ 'id' => $order_id ] );
  }

  public static function order_details( $order_id = '', $hash = '', $przelewy24_hash = '' )
  {
    global $mdb;

    if ( $order_id )
    {
      $order = $mdb -> get( 'pp_shop_orders', '*', [ 'id' => $order_id ] );
      $order[ 'products' ] = $mdb -> select( 'pp_shop_order_products', '*', [ 'order_id' => $order_id ] );
    }

    if ( $hash )
    {
      $order = $mdb -> get( 'pp_shop_orders', '*', [ 'hash' => $hash ] );
      $order[ 'products' ] = $mdb -> select( 'pp_shop_order_products', '*', [ 'order_id' => $order[ 'id' ] ] );
    }

    if ( $przelewy24_hash )
    {
      $order = $mdb -> get( 'pp_shop_orders', '*', [ 'przelewy24_hash' => $przelewy24_hash ] );
      $order[ 'products' ] = $mdb -> select( 'pp_shop_order_products', '*', [ 'order_id' => $order[ 'id' ] ] );
    }


    return $order;
  }

  public static function generate_order_number()
  {
    global $mdb;

    $date = date( 'Y-m' );

    $results = $mdb -> query( 'SELECT MAX( CONVERT( substring_index( substring_index( number, \'/\', -1 ), \' \', -1 ), UNSIGNED INTEGER) ) FROM pp_shop_orders WHERE date_order LIKE \'' . $date . '%\'' ) -> fetchAll();
    if ( is_array( $results ) and count( $results ) )
      foreach ( $results as $row )
        $nr = ++$row[ 0 ];

    if ( !$nr )
      $nr = 1;

    if ( $nr < 10 )
      $nr = '00' . $nr;

    if ( $nr < 100 and $nr >= 10 )
      $nr = '0' . $nr;

    return date( 'Y/m', strtotime( $date ) ) . '/' . $nr;
  }

  public static function basket_save(
    $client_id,
    $basket,
    $transport_id,
    $payment_id,
    $email,
    $phone,
    $name,
    $surname,
    $street,
    $postal_code,
    $city,
    $firm_name,
    $firm_street,
    $firm_postal_code,
    $firm_city,
    $firm_nip,
    $inpost_info,
    $orlen_point_id,
    $orlen_point_info,
    $coupon,
    $basket_message )
  {
    global $mdb, $lang_id, $settings;

    if ( $client_id )
      $email = \front\factory\ShopClient::client_email( $client_id );

    if ( !is_array( $basket ) or !$transport_id or !$payment_id or !$email or !$phone or !$name or !$surname )
      return false;

    $transport = \front\factory\ShopTransport::transport( $transport_id );
    $payment_method = \front\factory\ShopPaymentMethod::payment_method( $payment_id );
    $basket_summary = \front\factory\ShopBasket::summary_price( $basket, $coupon );
    $order_number = self::generate_order_number();
    $order_date = date( 'Y-m-d H:i:s' );
    $hash = md5( $order_number . time() );

    if ( $transport['delivery_free'] == 1 and $basket_summary >= $settings['free_delivery'] )
      $transport_cost = '0.00';
    else
      $transport_cost = $transport['cost'];

    $mdb -> insert( 'pp_shop_orders', [
        'number' => $order_number,
        'client_id' => $client_id ? $client_id : null,
        'date_order' => $order_date,
        'comment' => null,
        'client_name' => $name,
        'client_surname' => $surname,
        'client_email' => $email,
        'client_street' => $street,
        'client_postal_code' => $postal_code,
        'client_city' => $city,
        'client_phone' => $phone,
        'firm_name' => $firm_name ? $firm_name : null,
        'firm_street' => $firm_street ? $firm_street : null,
        'firm_postal_code' => $firm_postal_code ? $firm_postal_code : null,
        'firm_city' => $firm_city ? $firm_city : null,
        'firm_nip' => $firm_nip ? $firm_nip : null,
        'transport_id' => $transport_id,
        'transport' => $transport[ 'name_visible' ],
        'transport_cost' => $transport_cost,
        'transport_description' => $transport[ 'description' ],
        'orlen_point' => ( $orlen_point_id ) ? $orlen_point_id . ' | ' . $orlen_point_info : null,
        'inpost_paczkomat' => ( $transport_id == 1 or $transport_id == 2 ) ? $inpost_info : null,
        'payment_method' => $payment_method[ 'name' ],
        'payment_method_id' => $payment_id,
        'hash' => $hash,
        'summary' => \Shared\Helpers\Helpers::normalize_decimal( $basket_summary + $transport_cost ),
        'coupon_id' => $coupon ? $coupon -> id : null,
        'message' => $basket_message ? $basket_message : null,
        'apilo_order_status_date' => date( 'Y-m-d H:i:s' ),
    ] );

    $order_id = $mdb -> id();

    if ( !$order_id )
      return false;

    if ( $coupon )
      $mdb -> update( 'pp_shop_coupon', [ 'used_count[+]' => 1 ], [ 'id' => $coupon -> id ] );

    // ustawienie statusu zamówienia
    $mdb -> insert( 'pp_shop_order_statuses', [ 'order_id' => $order_id, 'status_id' => 0, 'mail' => 1 ] );

    if ( is_array( $basket ) )
    {
      foreach ( $basket as $basket_position )
      {
        $attributes = '';
        $product = \shop\Product::getFromCache( $basket_position[ 'product-id' ], $lang_id );

        if ( is_array( $basket_position[ 'attributes' ] ) )
        {
          foreach ( $basket_position[ 'attributes' ] as $row )
          {
            $row = explode( '-', $row );
            $attribute = \front\factory\ShopAttribute::attribute_details( $row[ 0 ], $lang_id );
            $value = \front\factory\ShopAttribute::value_details( $row[ 1 ], $lang_id );

            if ( $attributes )
              $attributes .= '<br>';
            $attributes .= '<b>' . $attribute[ 'language' ][ 'name' ] . '</b>: ';
            $attributes .= $value[ 'language' ][ 'name' ];
          }
        }

        // custom fields
        $product_custom_fields = '';
        if ( is_array( $basket_position[ 'custom_fields' ] ) )
        {
          foreach ( $basket_position[ 'custom_fields' ] as $key => $val )
          {
            $custom_field = \shop\ProductCustomField::getFromCache( $key );
            if ( $product_custom_fields )
              $product_custom_fields .= '<br>';
            $product_custom_fields .= '<b>' . $custom_field[ 'name' ] . '</b>: ' . $val;
          }
        }

        $product_price_tmp = \shop\Product::calculate_basket_product_price( (float)$product['price_brutto_promo'], (float)$product['price_brutto'], $coupon, $basket_position );

        $mdb -> insert( 'pp_shop_order_products', [
            'order_id' => $order_id,
            'product_id' => $basket_position['product-id'],
            'parent_product_id' => $basket_position['parent_id'] ? $basket_position['parent_id'] : $basket_position['product-id'],
            'name' => $product -> language['name'],
            'attributes' => $attributes,
            'vat' => $product -> vat,
            'price_brutto'  => $product_price_tmp['price'],
            'price_brutto_promo' => $product_price_tmp['price_new'],
            'quantity' => $basket_position['quantity'],
            'message' => $basket_position['message'],
            'custom_fields' => $product_custom_fields,
        ] );

        $product_quantity = \shop\Product::get_product_quantity( $basket_position['product-id'] );
        if ( $product_quantity != null )
          $mdb -> update( 'pp_shop_products', [ 'quantity[-]' => $basket_position[ 'quantity' ] ], [ 'id'  => $basket_position['product-id'] ] );
        else
          $mdb -> update( 'pp_shop_products', [ 'quantity[-]' => $basket_position[ 'quantity' ] ], [ 'id'  => $basket_position['parent_id'] ] );

        $mdb -> update( 'pp_shop_products', [ 'quantity' => 0 ], [ 'quantity[<]' => 0 ] );
      }
    }

    if ( $coupon and $coupon -> is_one_time() )
      $coupon -> set_as_used();

    $order = \front\factory\ShopOrder::order_details( $order_id );

    $mail_order = \Shared\Tpl\Tpl::view( 'shop-order/mail-summary', [
      'settings' => $settings,
      'order' => $order,
      'coupon' => $coupon,
    ] );

    $settings[ 'ssl' ] ? $base = 'https' : $base = 'http';

    $regex = "-(<img[^>]+src\s*=\s*['\"])(((?!'|\"|https?://).)*)(['\"][^>]*>)-i";
    $mail_order = preg_replace( $regex, "$1" . $base . "://" . $_SERVER[ 'SERVER_NAME' ] . "$2$4", $mail_order );

    $regex = "-(<a[^>]+href\s*=\s*['\"])(((?!'|\"|https?://).)*)(['\"][^>]*>)-i";
    $mail_order = preg_replace( $regex, "$1" . $base . "://" . $_SERVER[ 'SERVER_NAME' ] . "$2$4", $mail_order );

    \Shared\Helpers\Helpers::send_email( $email, \Shared\Helpers\Helpers::lang( 'potwierdzenie-zamowienia-ze-sklepu' ) . ' ' . $settings[ 'firm_name' ], $mail_order );
    \Shared\Helpers\Helpers::send_email( $settings[ 'contact_email' ], 'Nowe zamówienie / ' . $settings[ 'firm_name' ] . ' / ' . $order['number'] . ' - ' . $order['client_surname'] . ' ' . $order['client_name'], $mail_order );

    // zmiana statusu w realizacji jeżeli płatność przy odbiorze
    if ( $payment_id == 3 )
    {
      $order_tmp = new \shop\Order( $order_id );
      $order_tmp -> update_status( 4, true );
    }

    return $order_id;
  }

}