<?php
namespace front\Controllers;

use Domain\Order\OrderRepository;
use Domain\Order\OrderAdminService;

class ShopOrderController
{
  private $repository;
  private $adminService;

  public function __construct( OrderRepository $repository, OrderAdminService $adminService )
  {
    $this->repository = $repository;
    $this->adminService = $adminService;
  }

  public function paymentConfirmation()
  {
    global $settings;

    $order = $this->repository->orderDetailsFrontend( null, \Shared\Helpers\Helpers::get( 'order_hash' ) );

    return \Shared\Tpl\Tpl::view( 'shop-order/payment-confirmation', [
              'order' => $order,
              'settings' => $settings
            ] );
  }

  public function paymentStatusTpay()
  {
    file_put_contents( 'tpay.txt', print_r( $_POST, true ) . print_r( $_GET, true ), FILE_APPEND );

    if ( \Shared\Helpers\Helpers::get( 'tr_status' ) == 'TRUE' && \Shared\Helpers\Helpers::get( 'tr_crc' ) )
    {
      $order = $this->repository->findRawByHash( \Shared\Helpers\Helpers::get( 'tr_crc' ) );

      if ( $order && $order['id'] )
      {
        $this->adminService->setOrderAsPaid( (int)$order['id'], true );
        echo 'TRUE';
        exit;
      }
    }

    echo 'FALSE';
    exit;
  }

  public function paymentStatusPrzelewy24pl()
  {
    global $settings;

    $post = [
      'p24_merchant_id' => \Shared\Helpers\Helpers::get( 'p24_merchant_id' ),
      'p24_pos_id' => \Shared\Helpers\Helpers::get( 'p24_pos_id' ),
      'p24_session_id' => \Shared\Helpers\Helpers::get( 'p24_session_id' ),
      'p24_amount' => \Shared\Helpers\Helpers::get( 'p24_amount' ),
      'p24_currency' => \Shared\Helpers\Helpers::get( 'p24_currency' ),
      'p24_order_id' => \Shared\Helpers\Helpers::get( 'p24_order_id' ),
      'p24_sign' => md5( \Shared\Helpers\Helpers::get( 'p24_session_id' ) . '|' . \Shared\Helpers\Helpers::get( 'p24_order_id' ) . '|' . \Shared\Helpers\Helpers::get( 'p24_amount' ) . '|' . \Shared\Helpers\Helpers::get( 'p24_currency' ) . '|' . $settings['przelewy24_crc_key'] )
    ];

    $ch = curl_init();
    if ( $settings['przelewy24_sandbox'] )
      curl_setopt( $ch, CURLOPT_URL, 'https://sandbox.przelewy24.pl/trnVerify' );
    if ( !$settings['przelewy24_sandbox'] )
      curl_setopt( $ch, CURLOPT_URL, 'https://secure.przelewy24.pl/trnVerify' );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query( $post ) );
    $response = curl_exec( $ch );

    $order = $this->repository->findRawByPrzelewy24Hash( \Shared\Helpers\Helpers::get( 'p24_session_id' ) );

    if ( $order && $order['status'] == 0 && $order['summary'] * 100 == \Shared\Helpers\Helpers::get( 'p24_amount' ) )
    {
      if ( $order['id'] )
      {
        $this->adminService->setOrderAsPaid( (int)$order['id'], true );
      }
    }

    exit;
  }

  public function paymentStatusHotpay()
  {
    global $lang;

    if ( !empty( $_POST["KWOTA"] ) && !empty( $_POST["ID_PLATNOSCI"] ) && !empty( $_POST["ID_ZAMOWIENIA"] ) && !empty( $_POST["STATUS"] ) && !empty( $_POST["SEKRET"] ) && !empty( $_POST["HASH"] ) )
    {
      $order = $this->repository->orderDetailsFrontend( (int)$_POST['ID_ZAMOWIENIA'] );

      if ( $order && $order['id'] )
      {
        if ( is_array( $order['products'] ) && count( $order['products'] ) ):
          $summary_tmp = 0;
          foreach ( $order['products'] as $product ):
            $product_tmp = ( new \Domain\Product\ProductRepository( $GLOBALS['mdb'] ) )->productDetailsFrontCached( (int)$product['product_id'], $lang['id'] );
            $summary_tmp += \Shared\Helpers\Helpers::normalize_decimal( $product['price_netto'] + $product['price_netto'] * $product['vat'] / 100 ) * $product['quantity'];
          endforeach;
          $summary_tmp += $order['transport_cost'];
        endif;

        if ( hash( "sha256", "ProjectPro1916;" . round( $summary_tmp, 2 ) . ";" . $_POST["ID_PLATNOSCI"] . ";" . $_POST["ID_ZAMOWIENIA"] . ";" . $_POST["STATUS"] . ";" . $_POST["SEKRET"] ) == $_POST["HASH"] )
        {
          if ( $_POST["STATUS"] == "SUCCESS" )
          {
            $this->adminService->setOrderAsPaid( (int)$order['id'], true );

            echo \Shared\Helpers\Helpers::lang( 'zamowienie-zostalo-oplacone' );
          }
          else if ( $_POST["STATUS"] == "FAILURE" )
          {
            $this->adminService->changeStatus( (int)$order['id'], 2, true );

            echo \Shared\Helpers\Helpers::lang( 'platnosc-zostala-odrzucona' );
          }
        }
        else
        {
          $this->adminService->changeStatus( (int)$order['id'], 3, true );

          echo \Shared\Helpers\Helpers::lang( 'zamowienie-zostalo-oplacone-reczne' );
        }
      }
    }
    exit;
  }

  public function orderDetails()
  {
    global $page, $settings;

    $page['language']['meta_title'] = \Shared\Helpers\Helpers::lang( 'meta-title-szczegoly-zamowienia' ) . ' | ' . $settings['firm_name'];
    $order = $this->repository->orderDetailsFrontend(
      $this->repository->findIdByHash( \Shared\Helpers\Helpers::get( 'order_hash' ) )
    );
    $coupon = (int)$order['coupon_id'] ? ( new \Domain\Coupon\CouponRepository( $GLOBALS['mdb'] ) )->find( (int)$order['coupon_id'] ) : null;

    return \Shared\Tpl\Tpl::view( 'shop-order/order-details', [
      'order' => $order,
      'coupon' => $coupon,
      'client' => \Shared\Helpers\Helpers::get_session( 'client' ),
      'settings' => $settings
    ] );
  }
}
