<?php
namespace App\Http\Controllers\Shopify;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Shopify\Spysummary;
use App\Models\Shopify\Summaryaccountmapping;
use App\Models\Shopify\Spyreportsetting;
use App\Models\Shopify\Payoutfieldmapping;
use App\Models\Shopify\Spysummaryreport;
use App\Models\Shopify\Spycredential;
use App\Helpers\Helper;
use Auth;
use Input;
use Redirect;
use View;
use DB;
use Response;
use File;
use Log;
/**
 * This controller handles all actions related to Manufacturers for
 * the Snipe-IT Asset Management application.
 *
 * @version    v1.0
 */
class SettlementsController extends Controller
{   
    public function getSettlementList(Request $request)
    { 
        $shop = $request->get('shop');
        $SpycredentialObj = Spycredential::fetchSpySingleData("store_domain", $shop);

        if(!empty($SpycredentialObj) && $SpycredentialObj->status = 'Active'){
            $seller_id = $SpycredentialObj->id;

            $settlementData = Spysummary::where("seller_id", $seller_id)->where('module', config('app.module'))->orderBy('invoice_date', 'desc')->get()->toArray();

            return View::make('shopify/settlementlist')->with('shop',$shop)->with('seller_id',$request->get('seller_id'))->with('settlementData', $settlementData);
        }
    }

    public function settlementDetails(Request $request){

      $shop = $request->get('shop');
      $settlement_id = Helper::encryptor('decrypt',$request->get('settlement_id'));

      $SpycredentialObj = Spycredential::fetchSpySingleData("store_domain", $shop);
      $seller_id = $SpycredentialObj->id;
      $spyConnected = Spycredential::checkConnection($seller_id);

      $settlementDetail = Spysummary::where('id',$settlement_id)->get();
      if(!empty($settlementDetail)){
        $eventsList = array();
        foreach ($settlementDetail as $key => $value) {
           $financial_events = json_decode($value['data'],1);
           if(!empty($eventsList)){
              $financial_events = json_decode($value['data'],true);
              foreach ($eventsList as $k => $v) {
                foreach ($financial_events as $fk => $fv) {
                  if($v['FeeType'] == $fv['FeeType']){
                    $eventsList[$k]['CurrencyAmount'] = floatval(preg_replace('/[^\d.]/', '', $v['CurrencyAmount'])) + floatval(preg_replace('/[^\d.]/', '', $fv['CurrencyAmount']));
                    unset($financial_events[$fk]);
                  }
                }
              }
              if(!empty($financial_events)){
                $eventsList = array_merge($eventsList,$financial_events);
                $financial_events = array();
              }
           }else{
              $eventsList =  $financial_events;
           }
        }

        $summaryData = $oldsummaryData = array();
        $settingData = Spyreportsetting::fetchReportSettingData('seller_id', $seller_id);
        $mappingForDescription = Payoutfieldmapping::whereNull('deleted_at')->where('module', config('app.module'))->get()->toArray();
        $fields = array_column($mappingForDescription, 'field');
        $descriptions = array_column($mappingForDescription, 'description');
        $descriptionArray = array_combine($fields, $descriptions);
        
        $item_account_filed_mapping = array();
        foreach ($mappingForDescription as $key => $value) {
          $item_account_filed_mapping[$value['key']][] = $value['field'];
        }
        
        list($summaryData,$oldsummaryData) = $this->setDataInEvents($spyConnected,$settingData,$eventsList,$descriptionArray,$item_account_filed_mapping);
      }
          
      if(isset($summaryData['no_category'])){
	      $v = $summaryData['no_category'];
	      unset($summaryData['no_category']);
	      $summaryData['no_category'] = $v;
      }
      
      return View::make('shopify/settlementdetails',compact('summaryData','settlementDetail'))->with('seller_id',$request->get('seller_id'))->with('settlement',$request->get('settlement_id'))->with('shop',$shop)->with('tax_method', 'line');
    }
   
    public function setDataInEvents($spyConnected,$settingData,$eventsList,$descriptionArray,$item_account_filed_mapping){
     
        $seller_id = $spyConnected['id'];
        $tax_fields = config('summarysetting.tax_fields')['tax'];
        $shipping_tax_fields = config('summarysetting.shipping_tax_fields')['tax'];
        
        foreach ($eventsList as $k => $v) {
            foreach ($v['data'] as $key => $value) {
                if ($value['amount'] != 0) {
                    /*if ($settingData['tax_method'] != 'line' && (in_array($key, $tax_fields) || in_array($key, $shipping_tax_fields))) {
                        unset($summaryData[$key]);
                    } else {*/
                        if (isset($value['data'])) {                            
                            foreach ($value['data'] as $datakey => $datavalue) {

                                if ($datavalue['amount'] != 0) {
                                    $accountDataMapping = $this->getAccountRef($key, $settingData, $k);
                                    $main_category      = $accountDataMapping['main_category'];
                                    if ($main_category == '') {
                                        $main_category = 'no_category';
                                    }

                                    if (!isset($descriptionArray[$key])) {
                                        Log::info('We have got new field in Shopify report. need to handle it in payout mapping field table : ' . $key);
                                    }
                                    $accountDataMapping['FeeType']              = $key;
                                    $accountDataMapping['FeeType_description']  = isset($descriptionArray[$key]) ? $descriptionArray[$key] : $key;
                                    $accountDataMapping['CurrencyAmount']       = $datavalue['amount'];
                                    $accountDataMapping['dataTax']              = $datakey;
                                    $summaryData[$k][$main_category][$datakey] = $accountDataMapping;
                                    $oldsummaryData[$k][$datakey]              = $accountDataMapping;
                                }
                            }
                        } else {
                            $accountDataMapping = $this->getAccountRef($key, $settingData, $k);
                            
                            $main_category = $accountDataMapping['main_category'];
                            if ($main_category == '') {
                                $main_category = 'no_category';
                            }

                            if (!isset($descriptionArray[$key])) {
                                Log::info('We have got new field in Shopify report. need to handle it in payout mapping field table : ' . $key);
                            }
                            $accountDataMapping['FeeType']              = $key;
                            $accountDataMapping['FeeType_description']  = isset($descriptionArray[$key]) ? $descriptionArray[$key] : $key;
                            $accountDataMapping['CurrencyAmount']       = $value['amount'];
                            $summaryData[$k][$main_category][] = $accountDataMapping;
                            $oldsummaryData[$k][]              = $accountDataMapping;
                        }
                    //}
                }
            }
        }
        
        return array($summaryData,$oldsummaryData);
    }

    public function getAccountRef($feeType, $summarySettings, $parent_field)
    {
        $feeType    = strtolower($feeType);
        $fieldType = Payoutfieldmapping::where('parent_field', "")->where('field', $feeType)->whereNull('deleted_at')->where('module', config('app.module'))->first();
        
        if (!empty($fieldType)) {
            $feeType = $fieldType->key;
        }
        $accountRef = array('account_name' => $feeType . '_acc', 'main_category' => $feeType);

        return $accountRef;
    }
}

