<?php

namespace App\Models\Shopify;

use Illuminate\Database\Eloquent\Model;

class Spylastsync extends Model
{
    protected $connection = 'shopify';
 	protected $dates = [''];    
    protected $table = 'spy_last_sync';
    protected $rules = array();
    protected $injectUniqueIdentifier = true;

    public static function fetchSpylastsyncorderData($column , $value)
    {
    	$SpycredentialObj = Spylastsync::where($column,$value)->first();

    	return $SpycredentialObj;
    }

    public static function fetchSpylastsyncorderDataById($column , $value , $sourceDestId,$module)
    {
    	$SpycredentialObj = Spylastsync::where($column,$value)->where("seller_id",$sourceDestId)->where("module",$module)->first();

    	return $SpycredentialObj;
    }
     public static function fetchLastSyncOrder($seller_id)
    {
        $spyOrder = Spylastsync::where("seller_id",$seller_id)
                    ->where('sync_type','order')
                    ->first();
        return $spyOrder;
    }
    public static function fetchReportStart($seller_id,$module)
    {
        $SpycredentialObj = Spylastsync::where('seller_id',$seller_id)->where('module',$module)->where('sync_type','Order')->orderby('report_date','DESC')->first(['report_date']);

        return $SpycredentialObj;
    }
    public static function updateSyncStartDate($reportstartdate,$seller_id,$module,$report_type)
    {
        $fieldName="seller_id";
        if($report_type=="daily"){
            $lastUpdatedReport = date('Y-m-d', strtotime($reportstartdate . ' +1 day'));
            $start=date('Y-m-d',strtotime($lastUpdatedReport));
            $end=date('Y-m-d');
        }else{
            $lastUpdatedReport =    \Carbon\Carbon::parse($reportstartdate)->addMonths(1)->toDateString()." 23:59:59";
            $start=date('Y-m',strtotime($lastUpdatedReport));
            $end=date('Y-m');
        }
       
        $checkNextDaysRecord = Spysummaryorder::where('seller_id',$seller_id)->where('module',$module)->whereDate('transaction_date', '>=', $lastUpdatedReport)->where('sync_flg', '!=', "D")->orderby('transaction_date','DESC')->first(['transaction_date']);
        
        if(!empty($checkNextDaysRecord)){
            if($start<=$end)
            Spylastsync::where($fieldName, $seller_id)->where('sync_type','Order')->where('module',$module)->update([
                "report_date" => $lastUpdatedReport,
            ]);
        }
        return $lastUpdatedReport;
    }
}
