<?php
namespace App\Http\Traits;
use App\Helpers\Helper;
use App\Http\Controllers\Controller;
use App\Models\Amazon\Azsummaryrequest;
use App\Models\Master\Sellers;
use App\Models\Tally\Tysummary;
use Illuminate\Http\Request;
use Log;
use DB;

/*
Manali Patel - 07-07-2023
This controller makes common flow to manual sync button functionality which includes Fetch data from respective marketplace , calculate its summary and send it to sync to respective accounting.
*/
trait Summaryfetch
{
  public function fetchSummaryRequest($seller_id){
      $sellerdetails = Sellers::where('id',$seller_id)->first();
      if(strpos($sellerdetails->marketplace_name, 'az') !== false){
        $tablename = new Azsummaryrequest();
      }
      $Summaryrequest = $tablename::where('seller_id',$seller_id)->first();
      
      if($Summaryrequest){
        if(strtotime($Summaryrequest->created_at) < strtotime('-2 hours')  ){
          //request if more than of 2 hrs, need to make entry Pending for reprocess
          $Summaryrequest->where('seller_id',$seller_id)->update(['status'=>'Pending','created_at'=>date('Y-m-d H:i:s')]);
          $message_type = 'success';
          $message = 'Request Successfull';
        }else{
          $message_type = 'success';
          $message = 'Already requested';
        }
      }else{
        $Summaryrequest = new $tablename;
        $Summaryrequest->seller_id = $seller_id;
        $Summaryrequest->module = $sellerdetails->marketplace_name;
        $Summaryrequest->created_at = date('Y-m-d H:i:s');
        $Summaryrequest->save();
        $message_type = 'success';
        $message = 'Request Successfull';
      }
      return array($message,$message_type);
  }

  public function fetchSummaryToDb($seller_id){
    $seller = Helper::encryptor('encrypt',$seller_id);
    $seller = Sellers::where('id',$seller_id)->first();
    
    if(strpos($seller->marketplace, 'az')){
      $this->fetchAmazonSummary();
    }
    return true;
  }
  
  public function fetchAmazonSummary(Request $request){
      $request = new \Illuminate\Http\Request();
      $request->replace(['sellerid' => $request->seller_id]);
    
      app('App\Http\Controllers\Ecomtoacc\Ecomtodb\Amazon\FinancialeventsController')->getFinancialEvents($request,'from manual');
      app('App\Http\Controllers\Ecomtoacc\Ecomtodb\Amazon\OrderController')->getOrdersFromAmazon($request,'from manual');

      //app('App\Http\Controllers\Ecomtoacc\Dbtoacc\AmazonController')->syncDbToAcc($request,'from manual');
  }

  public function getSummaryData($seller_id,$limit = ''){
      $settlementData = array();
      $settlementData = Tysummary::select('*')->where("seller_id",$seller_id)->orderBy('invoice_date','desc');
      if($limit != '')
      $settlementData = $settlementData->limit(3);
      $settlementData = $settlementData->get()->toArray();
      return $settlementData;
    }
}
