<?php
namespace App\Http\Controllers\Master\Common;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Helpers\Helper;
use App\Models\Tally\TySummaryCostJournal;
use Log;

class CommonEventCostSyncController extends Controller
{        
    /*
    * Common function for sync marketplace events to master db 
    * Manali Patel - 05/05/2023
    */
    public function saveEventsCostToMaster($module, $insertArr,$sellerDetails){
        $updateFlg = false;  
          
        if(strpos($module,'tl') !== false){
            $eventExist = TySummaryCostJournal::fetchTallyJournalById($module, $insertArr['marketplace_primary_id'],$insertArr['seller_id']);  
            if(empty($eventExist)){
                $eventExist = new TySummaryCostJournal();
                $eventExist->module = $module;
                $eventExist->seller_id = array_key_exists('seller_id', $insertArr) ? $insertArr['seller_id'] : '';
                $eventExist->marketplace_id = array_key_exists('marketplace_primary_id', $insertArr) ? $insertArr['marketplace_primary_id'] : '';  // Primary key of marketplace order table   
                $eventExist->sync_flag = array_key_exists('sync_flag',$insertArr) ? $insertArr['sync_flag'] : 'N';
                $eventExist->sync_status = array_key_exists('sync_status',$insertArr) ? $insertArr['sync_status'] : 'New';  
            }
            $sync_id = $eventExist->tally_id;
        }
    
        $eventExist->journal_date = array_key_exists('journal_date',$insertArr) ? $insertArr['journal_date'] : '';
        $eventExist->narration = array_key_exists('narration',$insertArr) ? $insertArr['narration'] : '';
        $eventExist->line_items = array_key_exists('line_items',$insertArr) ? $insertArr['line_items'] : '';
        if(strpos($module,'tl') !== false){
            if(empty($eventExisttally_id)){
                $eventExist->tally_id = array_key_exists('tally_id',$insertArr) ? $insertArr['tally_id'] : NULL;
            }else{
                if($insertArr['sync_status'] == 'Pending'){
                    $eventExist->sync_status == 'New';
                }else{
                    $eventExist->sync_flag = 'U';
                }
            }
        }
        if(empty($sync_id) && array_key_exists('snr_status', $insertArr)){
            if($insertArr['snr_status'] == true)
                $eventExist->sync_status = 'SNR';
            else if($eventExist->sync_status == 'SNR')
                $eventExist->sync_status = 'New';
        }
        $eventExist->save();
        return $eventExist->id;
    }
}