<?php

namespace App\Http\Controllers\Tally\Settings;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Helpers\Helper;
use App\Models\Master\Sellers;
use App\Models\Master\SellerPlan;
use App\Models\Tally\Tyconnections;
use App\Models\Tally\Tysummarysettings;
use App\Models\Tally\Tysummarysettingsdraft;
use App\Models\Tally\Tysummarysettingslog;
use App\Models\Tally\Tyaccounts;
use Validator;
use Input;
use View;
use Response;

class TallySettingsController extends Controller
{
    public function __construct(Request $request) {  
        if($request->seller_id){
            $seller_id = Helper::encryptor('decrypt',$request->seller_id);
            $sellers = Sellers::where('id',$seller_id)->first();
            $this->seller_marketplace_name = $sellers->marketplace_name;
            $this->seller_country = $sellers->country;

            if(strpos($sellers->marketplace_name,'az') !== false){
                $this->setting_fields = config('amazonsummaryconstant.summary_setting_fields');
                $this->defaultPrefix = 'AMZ';
            }
        }
    }

    public function index(Request $request) {

        $seller_id_enc = $request->get('seller_id');
        $seller_id = Helper::encryptor('decrypt', $seller_id_enc);

        $sellerData = Sellers::getSellerData('id', $seller_id);
        if(!empty($sellerData)) {
            $module = $sellerData->marketplace_name;
            $sellerPlanData = SellerPlan::getSellerPlan($seller_id);
            if(empty($sellerPlanData)){
                return redirect()->route('plans', array('seller_id'=>$seller_id_enc));
            }

            $tlConnected = Tyconnections::checkTallyConnected($seller_id, $sellerData->marketplace_name);
            if($tlConnected == 'connected'){
                $settingDataSetFlg = true;
                $settingData = Tysummarysettings::fetchSettingForSeller($seller_id, $module);
                if(empty($settingData)){
                    $settingData = new Tysummarysettings;
                    $settingDataSetFlg = false;
                }
                
                $syncMinDate = date('Y-m-d', strtotime('-60 day', strtotime('now')));
                $editable = "true";

                $setting_fields = $this->setting_fields;
                $allAccounts = Tyaccounts::getAccountList($seller_id, $module);
                
                foreach ($setting_fields as $key1 => $field1) {
                    foreach ($field1 as $key => $field) {
                        $accountsData = array();
                        $accountsData[""] = "--- Select Account ---";

                        $tallyAccounts = Tyaccounts::where('seller_id', $seller_id)->where('module', $module)->whereIn('parent', $field['tally_acc_type'])->get()->pluck('name', 'name')->toArray();
                        $accountsData = array_replace($accountsData, $tallyAccounts);

                        if ($settingDataSetFlg == false) {
                            if(isset($allAccounts[$field['label']])){
                                $accountsData[$allAccounts[$field['label']]] = $field['label'];
                            } else {
                                $accountsData['0,' . $field['label']] = $field['label'];
                            }
                        }

                        $setting_fields[$key1][$key]['accounts'] =  $accountsData;
                    }
                }

                if (!empty($settingData) && $settingData['account_settings'] != '') {
                    $settingData = $settingData->toArray();
                    $account_settings = json_decode($settingData['account_settings'], true);
                    if (!empty($account_settings)) {
                        foreach ($account_settings as $key => $value) {
                            foreach ($value as $k => $v) {
                                $settingData[$k] = $v;
                            }
                        }
                    }
                }

                $taxCodeList = array("" => "--- Select Tax Code ---") + Tyaccounts::where('seller_id', $seller_id)->where('module', $module)->whereIn('parent', ['Duties & Taxes'])->get()->pluck('name', 'name')->toArray();

                $bankAccountList = array("" => "--- Select Bank Account ---") + Tyaccounts::where('seller_id', $seller_id)->where('module', $module)->whereIn('parent', ['Bank Accounts '])->get()->pluck('name', 'name')->toArray();

                $syncTypeList = array("SALES" => "Sales Voucher" , "JOURNAL" => "Journal");
                return View::make('tally/settings/summarysettings')->with('seller_id',$seller_id_enc)->with('seller_details',$sellerData)->with('tallyConnected', $tlConnected)->with('settingData', $settingData)->with('syncMinDate', $syncMinDate)->with('editable', $editable)->with('setting_fields', $setting_fields)->with('settingDataSetFlg', $settingDataSetFlg)->with('taxCodeList', $taxCodeList)->with('syncTypeList', $syncTypeList)->with('bankAccountList', $bankAccountList)->with('defaultPrefix', $this->defaultPrefix);
            } else {
                return redirect()->route('tyauth', array('seller_id'=>$seller_id_enc));
            }

        }
    }

    public function setSettingsValidation(Request $request)
    {
        $validationArray                    = array();
        $validationArray['sync_type'] = 'required';
        $validationArray['seller_id']= 'required';
        $validationArray['sync_start_date']= 'required';        
        $validationArray['bank_account']= 'required';        
        $validationArray['account_settings']= 'required';
        return $validationArray;
    }

    public function storeSettings(Request $request){

        $seller_id_enc = $request->get('seller_id');
        $seller_id = Helper::encryptor('decrypt', $seller_id_enc);

        $sellerData = Sellers::getSellerData('id', $seller_id);
        if(!empty($sellerData)) {
            $validationArray = $this->setSettingsValidation($request);
        
            $validator = Validator::make(Input::all(), $validationArray);
            if ($validator->fails()) {
                return Response::json(array(
                    'success' => false,
                    'errors'  => $validator->getMessageBag()->toArray(),

                ), 422);
            }

            $setting_field = $this->setting_fields;
            foreach ($setting_field as $key => $value) {
                foreach ($value as $k => $v) {
                    $setting_fields[$k] = $v;
                }
            }
            
            $account_settings = json_decode($request->get('account_settings'),1);
            $gatewaySettings = [array('paypal' => 'NO', 'stripe' => 'NO')];

            $settingData = Tysummarysettings::fetchSettingForSeller($seller_id, $sellerData->marketplace_name);
            if(empty($settingData)){
                $settingData = new Tysummarysettings();
                $settingData->seller_id = $seller_id;
                $settingData->module = $sellerData->marketplace_name;
            }
            if (!empty($request->get('prefix_required')) && $request->get('prefix_required') == "on") {
                $settingData->prefix_required = 'N';
            } else {
                $settingData->prefix_required = 'Y';            
            }
            $settingData->prefix = $request->get('tlPrefix');
            $settingData->bank_account = $request->get('bank_account');
            $settingData->sync_start_date = $request->get('sync_start_date');
            $settingData->sync_type = $request->get('sync_type');

            if($this->seller_country == 'US' || $this->seller_country == 'CA'){
                $settingData->tax_method = 'line';
            } else {
                $settingData->tax_method = 'default';
            }

            $settingData->account_settings = json_encode($account_settings);
            $settingData->gateway_settings = json_encode($gatewaySettings);
            
            $settingData->save();

            $this->saveSummarySettingLog($settingData);

            Tysummarysettingsdraft::where('seller_id', $seller_id)->whereNull('deleted_at')->update(['deleted_at' => date('Y-m-d H:i:s')]);
            return Response::json(array(
                'success' => true,
                'message' => "Settings stored successfully.",

            ), 200);
        }
    }

    public function saveSummarySettingLog($settingData)
    {
        $settingLog = new Tysummarysettingslog();
        $settingData = $settingData->toArray();
        foreach ($settingData as $key => $value) {
            if($key != 'id' && $key != 'created_at') {
                    $settingLog->$key = $value;
                }
            }
        $settingLog->updated_at = date('Y-m-d H:i:s');
        $settingLog->save();
    }

    public function createSummaryAccounts(Request $request){

        $seller_id_enc = $request->get('seller_id');
        $seller_id = Helper::encryptor('decrypt', $seller_id_enc);

        $sellerData = Sellers::getSellerData('id', $seller_id);
        $this->saveDraftSettingData($request->get('formdata'), $sellerData);

        $accountsData = json_decode($request->get('accountsdata'), true);

        $setting_field = $this->setting_fields;
        foreach ($setting_field as $key => $value) {
            foreach ($value as $k => $v) {
                $setting_fields[$v['label']] = $v;
            }
        }
        
        $postAccountsData = array();
        if(!empty($accountsData)){
            foreach ($accountsData as $akey => $aval) {
                $postAccountsData[] = array(
                    'name' => $aval,
                    'parent' => $setting_fields[$aval]['tally_account_create_type']
                );
            }
        }
        
        $postData = array(
            'seller_id' => $seller_id,
            'module' => $sellerData->marketplace_name,
            'accounts' => $postAccountsData,
        );
        
        //$curlUrl = config('app.TALLY_API_DOMAIN_URL').'/createAccounts';  
        $curlUrl = config('tallyconstant.apiUrls.createAccounts');
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/json")); 
        curl_setopt($ch, CURLOPT_URL, $curlUrl);            
        curl_setopt($ch, CURLOPT_POST, 3);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
       
        $result = curl_exec($ch);
        curl_close($ch);
        
        return Response::json(array(
            'success' => true,
            'message' => "",
            'data' => ''
        ), 200);
    }

    public function saveDraftSettingData($request, $sellerData){

        $formdata = array_column($request, 'value', 'name');
        if(!empty($formdata)){            
            $settingData = Tysummarysettingsdraft::checkSettingDraftData("seller_id", $sellerData->id);

            if(empty($settingData)){
                $settingData = new Tysummarysettingsdraft();
                $settingData->seller_id = $sellerData->id;
            }
            if (!empty($formdata['prefix_required']) && $formdata['prefix_required'] == "on") {
                $settingData->prefix_required = 'N';
            } else {
                $settingData->prefix_required = 'Y';            
            }
            $settingData->prefix = $formdata['tlPrefix'];
            $settingData->bank_account = $formdata['bank_account'];
            $settingData->sync_start_date = $formdata['sync_start_date'];
            $settingData->sync_type = $formdata['sync_type'];
            
            $settingData->save();
        }
    }

}
