<?php

namespace App\Models\Shopify;

use Illuminate\Database\Eloquent\Model;
use DB;
use Log;
use Str;
class Spysummaryreport extends Model
{
    protected $connection = 'shopify';
    protected $dates = [''];
    protected $table = 'spy_summary_report';
    protected $rules = array();
    protected $injectUniqueIdentifier = true;

    public static function fetchSpyReportSingleData($column , $value,$seller_id)
    {
        $SpycredentialObj = Spysummaryreport::where($column,$value)->where('seller_id',$seller_id)->first();

        return $SpycredentialObj;
    }
    public static function fetchReportLast($seller_id,$module)
    {
        $SpycredentialObj = Spysummaryreport::where('seller_id',$seller_id)->where('module',$module)->where('gateway','!=','shopify_payments')->where('gateway','!=','shopify_installments')->where('gateway','!=','shop_cash')->orderby('posted_date','DESC')->first();

        return $SpycredentialObj;
    }
    public static function savereportData($reportData,$type,$settingData,$reportType="",$reCalc=[],$reportstartdate="",$reportenddate="",$report_type=""){
        $modelName=Spysummaryreport::class;
        
        foreach ($reportData as $key => $reports) {
            if(stripos($key,',') !== false || (isset($reports['transaction_type']) &&  $reports['transaction_type']=="Individual")){
                $reports=array('0'=>$reports);
            }
            foreach ($reports as $settlement_month=>$value) {
          
                if((is_null($value['total_amount']) || ($value['total_amount']===""  ) ) && (empty($reCalc)) ){
                    Log::info("savereportData Data ---" .print_r($value,true));
                    continue;
                }
                $cost_arry=[];
                $module=(isset($value['module']) && !empty($value['module']))?$value['module']:"xosp";
                $validGateway=(!empty($value['gateway']))?$value['gateway']:null;

                if (isset($settingData->cogs_enable) && $settingData->cogs_enable=="Yes") {
                    $cosModelName = Spysummarycostreport::class;
                    $storeCostReport = $cosModelName::where('seller_id', $value['seller_id'])->where('module', $module)->where('posted_date', $value['posted_date'])->where('gateway', $validGateway)->first();

                    if (empty($storeCostReport)) {
                        $storeCostReport = new $cosModelName();
                    }
                    if (isset($value['seller_id']) && !empty($value['seller_id'])) {
                        $storeCostReport->seller_id = $value['seller_id'];
                    }
                    if (isset($module) && !empty($module)) {
                        $storeCostReport->module = $module;
                    }
                    if (isset($value['unique_id']) && !empty($value['unique_id'])) {
                        $storeCostReport->unique_id = $value['unique_id'];
                    }
                    if (isset($value['posted_date']) && !empty($value['posted_date'])) {
                        $storeCostReport->posted_date = $value['posted_date'];
                    }
                    if (isset($value['settlement_month']) && !empty($value['settlement_month'])) {
                        $storeCostReport->settlement_month = $value['settlement_month'];
                    }

                    if (isset($value['currency']) && !empty($value['currency'])) {
                        $storeCostReport->currency = $value['currency'];
                    }
                    if (isset($value['total_cost_transactions']) && !empty($value['total_cost_transactions'])) {
                        $storeCostReport->total_transactions = $value['total_cost_transactions'];
                    }
                    if (isset($value['transaction_type']) && !empty($value['transaction_type'])) {
                        $storeCostReport->transaction_type = $value['transaction_type'];
                    }
                    if (isset($value['gateway']) && !empty($value['gateway'])) {
                        $storeCostReport->gateway = $value['gateway'];
                    }
                    if(isset($value['total_cost_amount']) && !empty($value['total_cost_amount'])){
                        $storeCostReport->cost_amount = $value['total_cost_amount'];
                    }
                    if (isset($value['total_cost_amount']) && !empty($value['total_cost_amount'])) {

                        $cost_arry[$settlement_month]['description'] = "Shopify";
                        $cost_arry[$settlement_month]['Amount'] = $value['total_cost_amount'];
                        $storeCostReport->summary_details = json_encode($cost_arry);
                    }
                    if($value['transaction_type']=="Individual"){
                        $storeCostReport->reference = Spysummaryreport::getreference($value,$module);
                    }

                    $storeCostReport->document_number= Spysummaryreport::getDocumentNumber($settingData, $value);
                    $storeCostReport->sync_flg = 'N';

                    if (count($reports) > 1) {
                        $storeCostReport->partial_settlement = 'Y';
                    }
                    $storeCostReport->save();
                }   
                $validGateway=(!empty($value['gateway']))?$value['gateway']:null;
                if(!empty($reCalc)){
                    $storeReport = $modelName::where('id',$reCalc['report_id'])->where('seller_id',$value['seller_id'])->where('module',$module)->where('settlement_month',$value['settlement_month'])->first();
                    if(empty($storeReport)){
                        continue;
                    }
                }else if($type == 'payout'){
                    $storeReport = $modelName::where('seller_id',$value['seller_id'])->where('module',$module)->where('unique_id',$value['unique_id'])->where('posted_date',$value['posted_date'])->where('settlement_month',$settlement_month)->where('gateway',$validGateway)->where('transaction_type',$value['transaction_type'])->first();
                }else if($value['transaction_type']=="Individual"){
                    $storeReport = $modelName::where('seller_id',$value['seller_id'])->where('module',$module)->where('posted_date',$value['posted_date'])->where('unique_id',$value['unique_id'])->where('gateway',$validGateway)->first();
                } else{
                    $storeReport = $modelName::where('seller_id',$value['seller_id'])->where('module',$module)->where('posted_date',$value['posted_date'])->where('gateway',$validGateway)->first();
                }
                
                if(empty($storeReport) && empty($reCalc)){
                    $storeReport = new $modelName();
                }
                if(isset($value['seller_id']) && !empty($value['seller_id'])){
                    $storeReport->seller_id = $value['seller_id'];
                }
                if(isset($module) && !empty($module)){
                    $storeReport->module = $module;
                }
                if(isset($value['start_date']) && !empty($value['start_date'])){
                    $storeReport->start_date = $value['start_date'];
                }
                if(isset($value['end_date']) && !empty($value['end_date'])){
                    $storeReport->end_date = $value['end_date'];
                }
                /* if(isset($reportstartdate) && !empty($reportstartdate)){
                    $storeReport->start_date = $reportstartdate;
                }
                if(isset($reportenddate) && !empty($reportenddate)){
                    $storeReport->end_date = $reportenddate;
                } */
                if(isset($value['unique_id']) && !empty($value['unique_id'])){
                    $storeReport->unique_id = $value['unique_id'];
                }
                if(isset($value['posted_date']) && !empty($value['posted_date'])){
                    $storeReport->posted_date = $value['posted_date'];
                }
                if(isset($value['settlement_month']) && !empty($value['settlement_month'])){
                    $storeReport->settlement_month = $value['settlement_month'];
                }
                if (isset($value['taxes_included']) && !empty($value['taxes_included'])) {
                    $storeReport->tax_type = $value['taxes_included'];
                }
                if(isset($value['currency']) && !empty($value['currency'])){
                    $storeReport->currency = $value['currency'];
                }
                if(isset($value['total_transactions']) && !empty($value['total_transactions'])){
                    $storeReport->total_transactions = $value['total_transactions'];
                }
                if(isset($value['transaction_type']) && !empty($value['transaction_type'])){
                    $storeReport->transaction_type = $value['transaction_type'];
                }
                if(isset($value['gateway']) && !empty($value['gateway'])){
                    $storeReport->gateway = $value['gateway'];
                }
                $storeReport->total_amount =$value['total_amount'];
            
                if(isset($value['summary_details']) && !empty($value['summary_details'])){
                   $storeReport->summary_details = json_encode($value['summary_details']);
                }
                if($value['transaction_type']=="Individual"){
                    $storeReport->reference = Spysummaryreport::getreference($value,$module);
                }
                
                $storeReport->document_number= Spysummaryreport::getDocumentNumber($settingData, $value);

                $storeReport->sync_flg='N';

                if(count($reports) > 1){
                    $storeReport->partial_settlement = 'Y';                    
                }
                $storeReport->save();
                $gatewayArray = config('shopify.considerAsShopify');
                if(!in_array($validGateway,$gatewayArray)){
                    $Spylastsyncdata = Spylastsync::updateSyncStartDate($reportstartdate,$value['seller_id'],$module,$report_type);
                }

            }
        }

    }
    public static function fetchSpyUnsyncdata($seller_id,$limit){
        $spyOrder = Spysummaryreport::where("seller_id",$seller_id)
                    ->where("sync_status_flg","new")
                    ->whereNull("xo_id")
                    ->orderBy("posted_date","ASC");
        if($limit!=0)
        $spyOrder->limit($limit);
    
        $spyOrder = $spyOrder->get();
        return $spyOrder;
    }
     public static function fetchReportData($seller_id,$report_id)
    {
        if(!empty($report_id)){

            $SpycredentialObj = Spysummaryreport::where('id',$report_id)->where('seller_id',$seller_id)->get();
        }else{
            $SpycredentialObj = Spysummaryreport::where('sync_flg','N')->where('seller_id',$seller_id)->get();

        }

        return $SpycredentialObj;
    }
    public static function fetchReportById($report_id,$module)
    {
    
        $table = "spy_credential";
        $SpycredentialObj = Spysummaryreport::join($table, $table.'.id', '=', 'spy_summary_report.seller_id')->where('spy_summary_report.id',$report_id)->orderby('posted_date','DESC')->first();
        return $SpycredentialObj;
    }
    public static function getreference($value,$module="")
    {
        $data = Spysummaryordertrans::where('transaction_id', $value['unique_id'])->where('seller_id', $value['seller_id'])->where('module', $module)->first(['reference']);

        return (!empty($data->reference))?$value['gateway'] . "|" . $data->reference:NULL;
    }
    public static function checkReportExist($order_data,$reportenddate){
        $gateway=getGateway($order_data['gateway']);

        $spyOrder = Spysummaryreport::where("seller_id",$order_data['seller_id'])->where("module",$order_data['module'])
        ->where("gateway",$gateway)->where("currency",$order_data['currency'])->whereDate ("posted_date",$reportenddate)->exists();
      
        return $spyOrder;
    }

    public static function getDocumentNumber($settingData, $value)
    {
        $document_number = "";
        $gatewaySF = Spysummaryreport::getGatewayShortForm($value['gateway']);
        $gateway = (!empty($gatewaySF)) ? $gatewaySF . "_" : "";

        if (isset($value['document_number']) && !empty($value['document_number'])) {
            $document_number = $value['document_number'];
        } else {

            $uniqueName = ($value['transaction_type'] == "Individual") ? $value['unique_id'] : date('Ymd', strtotime($value['posted_date']));

            if ($settingData->prefix_required == 'Y') {
                $document_number = $settingData->prefix . '_' . $gateway . $uniqueName;
            } else {
                $document_number = $gateway . $uniqueName;
            }
        }
        return $document_number;
    }

    public static function getGatewayShortForm($gateway = null)
    {
        $gateways=config('shopify.gateways');
        
        if(isset($gateways[$gateway]) && !empty($gateways[$gateway])){
            $gateway=$gateways[$gateway];
        }else{
            $gateway= (!empty($gateway))?(string)Str::of($gateway)->limit(8,""):"";
        }

        return $gateway;
    }
}
