<?php
namespace App\Http\Controllers\Ecomtoacc\Dbtoacc;
use App\Http\Controllers\Controller;
use App\Models\Amazon\Azfinanceevent;
use App\Models\Amazon\Azsummaryfinanceevent;
use App\Models\Amazon\Azfinancialreport;
use App\Models\Amazon\Summarycostreport;
use App\Models\Amazon\Azsellers;
use Illuminate\Http\Request;
use App\Helpers\Helper;
use View;
use Log;
use DB;

class AmazonController extends Controller
{
    public function __construct(Request $request) {
        if (version_compare(phpversion(), '7.1', '>=')) {
            ini_set('precision', 10);
            ini_set('serialize_precision', 10);
        }
    }
    /*
    * Sync Events from Az to master db
    * Manali Patel - 05/05/2023
    */
    public function syncDbToAcc(Request $request, $type = '')
    {                
        $sellerid = Helper::encryptor('decrypt',$request->get('sellerid'));
        $sellerid = 15;
        $sellerDetails = Azsellers::getSellerDetails($sellerid);    

        if(count($sellerDetails) > 0){
            $module = $sellerDetails[0]['module'];            
            $connected = $this->checkForConnection($sellerid, $module);            
            if($connected == 'connected'){
                if(!empty($type))
                    $sync_status = ($type == 'update') ? 'Process' : 'New'; 
                else
                    $sync_status = ($request->get('type') == 'update') ? 'Process' : 'New';


                 $sync_flag = ($sync_status == 'Process') ? ['U','N'] : ['N'];
                
                if($sellerDetails[0]['sync_type'] == 'Summary')
                    $eventsData = Azsummaryfinanceevent::getEventsForSync($sellerid, $sync_status, $sync_flag, $type);

                if(!empty($eventsData)){
                    foreach ($eventsData as $event) {
                        $this->syncEventsAz($sellerDetails, $event,$connected);              
                    }
                }

                if($sellerDetails[0]['sync_type'] == 'Summary')
                    $eventsCostData = Summarycostreport::getEventsCostForSync($sellerid, $sync_status, $sync_flag);
                if(!empty($eventsCostData)){
                    foreach ($eventsCostData as $eventCost) {
                        $this->syncEventsCostAz($sellerDetails,$eventCost);
                    }
                }
            }                  
        }
        if(!empty($type)){
            return true;
        }else{
            echo 'success';exit;
        }
    }
    
    public function syncEventsAz($sellerDetails, $event,$connected){
        $module = $sellerDetails[0]['module'];

        $sellerid = $sellerDetails[0]['seller_id'];
        //reference create
        $reference = '';
        $GroupData = '';
        if($event['financial_reports_id'] != NULL){
            //take finanace report entry from this id and get group id from there for reference purpose
            $GroupData = Azfinancialreport::select('az_financial_event_groups.*')->join('az_financial_event_groups','az_financial_event_groups.id','=','az_financial_reports.financial_event_groups_id')->where('az_financial_reports.seller_id',$sellerid)->where('az_financial_reports.ReportId',$event['financial_reports_id'])->first();

        }
        
        if($GroupData){ 
            $original_currency = $GroupData->original_total_currency;
            $converted_currency = $GroupData->converted_total_currency;
            if($converted_currency != ''){
                if($original_currency != $converted_currency){
                    $reference = $GroupData->original_total_currency.' '.$GroupData->original_total_amount.' Converted to '.$GroupData->converted_total_currency.' '.$GroupData->converted_total_amount;
                }
            }
        }
        
        if($sellerDetails[0]['sync_type'] == 'Summary'){
            $total_amount = $event['event_total_amount'];
            $settlement_amount = $event['settlement_amount'];
        }
        else{
            $total_amount = $event['fee_amount'];
            $settlement_amount = NULL;
        }       

        $invoice_date = '';
        if(date('m',strtotime($event['posted_date'])) == date('m',strtotime($event['end_date']))){
            $invoice_date = $event['posted_date'];
        }else{
            $invoice_date = $event['end_date'];
        }
        if($GroupData){
            if($GroupData->fund_transfer_date != '0000-00-00 00:00:00' && !empty($GroupData->fund_transfer_date)){
                $invoice_date = $GroupData->fund_transfer_date;
            }   
        }
        $inclusive = false;
        if(in_array($event['financial_events_currency'], config('amazonsummaryconstant.tax_inclusive_currency'))){
            $inclusive = true;
        }
        $json_data = json_decode($event['financial_events'],1);
        $json_amount = array_sum(array_column($json_data, 'amount'));
        if($inclusive == false)
        $json_amount += array_sum(array_column($json_data, 'taxAmount'));

	    $json_amount = number_format($json_amount,2,'.','');

        $insertArr = [];
        $insertArr['seller_id'] = $sellerid;
        $insertArr['module'] = $module;
        $insertArr['marketplace_primary_id'] = $event['id']; // Primary key of Azfinanceevent table of amazon database
        $insertArr['document_number'] = $event['document_number'];
        $insertArr['invoice_date'] = $invoice_date;
        $insertArr['start_date'] = $event['start_date'];
        $insertArr['end_date'] = $event['end_date'];
        if($settlement_amount != NULL)
        $insertArr['settlement_amount'] = $settlement_amount;
        if($json_amount == 0)
            $total_amount = 0;
        $insertArr['total_amount'] = $total_amount;
        $insertArr['json_amount'] = $json_amount;
        $insertArr['currency'] = $event['financial_events_currency'];
        $insertArr['country_code'] = $event['country_code'];
        $insertArr['payout_id'] = $event['settlement_id'];
        if($reference != '')
        $insertArr['reference'] = $reference;
        $insertArr['payout_id'] = $event['settlement_id'];
        $insertArr['data'] = json_encode($json_data);
        
        if($inclusive)
        $insertArr['tax_type'] = 'Inclusive';
        else
        $insertArr['tax_type'] = 'Exclusive';

        $insertArr['sync_status'] = $event['sync_status_flg'];
        $master_order_id = $this->syncEventsCommon($insertArr, $event, $sellerDetails);

        if(!is_null($event['charge_amount'])){
            $this->syncFeesAz($sellerDetails, $event,$master_order_id);
        }
        if($master_order_id > 1001){
            if($GroupData){
                $original_currency = $GroupData->original_total_currency;
                $converted_currency = $GroupData->converted_total_currency;
                if($converted_currency != ''){
                    if($connected['xero_base_currency'] != $converted_currency){
                        //save receive money
                        if($event['partial_settlement'] == 'N')
                        $this->syncCurrencyExchange($sellerDetails,$GroupData,$master_order_id);
                    }
                }
            }
        }
    }

    public function syncFeesAz($sellerDetails, $event, $master_order_id){
        $module = $sellerDetails[0]['module'];
        $sellerid = $sellerDetails[0]['seller_id'];

        $charge_data = json_decode($event['charge_amount'],true);
        foreach ($charge_data as $chargekey => $chargevalue) {
            $invoice_date = date('Y-m-d',strtotime($chargekey));
            
            $first_key =  array_key_first($chargevalue);
            $data = json_encode($chargevalue);

            $insertArr = [];
            $insertArr['seller_id'] = $sellerid;
            $insertArr['module'] = $module;
            $insertArr['gateway'] = 'amazon';
            $insertArr['marketplace_primary_id'] = $event['id'];
            $insertArr['tally_summary_id'] = $master_order_id;
            $insertArr['document_number'] = 'AMAZON_FEES_'.date('Ymd',strtotime($invoice_date));
            $insertArr['invoice_date'] = $invoice_date;
            $insertArr['total_amount'] = $chargevalue[$first_key]['amount'];
            $insertArr['json_amount'] = $chargevalue[$first_key]['amount'];
            $insertArr['currency'] = $event['financial_events_currency'];
            $insertArr['country_code'] = $event['country_code'];
            $insertArr['data'] = $data;
            $insertArr['tax_type'] = 'Inclusive';

            $this->syncFeesCommon($insertArr, $event, $sellerDetails);
        }
    }

    public function syncEventsCostAz($sellerDetails, $event){
        $sellerid = $sellerDetails[0]['seller_id'];
        $module = $sellerDetails[0]['module'];
        $insertArr = [];
        $insertArr['seller_id'] = $sellerid;
        $insertArr['module'] = $module;
        $insertArr['marketplace_primary_id'] = $event['id']; // Primary key of Azfinanceevent table of amazon database
        $insertArr['journal_date'] = $event['posted_date'];
        $insertArr['narration'] = $event['document_number'];
        $insertArr['line_items'] = $event['summary_details'];
        $insertArr['sync_status'] = $event['sync_status_flg'];
        
        $this->syncEventsCostCommon($insertArr, $event, $sellerDetails);
    }

    public function syncEventsCommon($insertArr, $event, $sellerDetails){

        $module = $sellerDetails[0]['module'];
        $master_order_id = app('App\Http\Controllers\Ecomtoacc\Common\CommonEventSyncController')->saveEventsToMaster($module,$insertArr,$sellerDetails);      

        if(!empty($master_order_id)){
            
            if($sellerDetails[0]['sync_type'] == 'Summary')
                Azsummaryfinanceevent::where('id', $event->id)->where('seller_id', $sellerDetails[0]['seller_id'])->update(['sync_flg' => 'Y','sync_status_flg' => 'Process']);  // Update order sync status    
            else
                Azfinanceevent::where('settlement_id', $event->settlement_id)->where('seller_id', $sellerDetails[0]['seller_id'])->update(['sync_flg' => 'Y','sync_status_flg' => 'Process']);  // Update order sync status    

        }
        return $master_order_id;
    }

    public function syncEventsCostCommon($insertArr, $event, $sellerDetails){

        $module = $sellerDetails[0]['module'];
        $master_order_id = app('App\Http\Controllers\Ecomtoacc\Common\CommonEventCostSyncController')->saveEventsCostToMaster($module,$insertArr,$sellerDetails);      

        if(!empty($master_order_id)){
            
            if($sellerDetails[0]['sync_type'] == 'Summary')
                Summarycostreport::where('id', $event->id)->where('seller_id', $sellerDetails[0]['seller_id'])->update(['sync_flg' => 'Y','sync_status_flg' => 'Process']);  // Update order sync status  
        }
    }

    public function syncFeesCommon($insertArr, $event, $sellerDetails){
        $module = $sellerDetails[0]['module'];
        $master_order_id = app('App\Http\Controllers\Ecomtoacc\Common\CommonFeesSyncController')->saveFeesToMaster($module,$insertArr,$sellerDetails);      
    }

    public function syncCurrencyExchange($sellerDetails,$GroupData,$master_order_id){

        $module = $sellerDetails[0]['module'];
        $sellerid = $sellerDetails[0]['seller_id'];

        $insertArr = [];
        $insertArr['seller_id'] = $sellerid;
        $insertArr['module'] = $module;
        $insertArr['tally_summary_id'] = $master_order_id;
        $insertArr['original_amount'] = $GroupData['original_total_amount'];
        $insertArr['original_currency'] = $GroupData['original_total_currency'];
        $insertArr['converted_amount'] = $GroupData['converted_total_amount'];
        $insertArr['converted_currency'] = $GroupData['converted_total_currency'];
        $this->syncCurrencyExchangeCommon($insertArr,$sellerDetails);
    }
    public function syncCurrencyExchangeCommon($insertArr,  $sellerDetails){
        $module = $sellerDetails[0]['module'];
        app('App\Http\Controllers\Master\Common\CommonConvertedCurrencySyncController')->saveConvertedCurrencyToMaster($module,$insertArr,$sellerDetails);      
    }
}
