<?php

namespace App\Http\Controllers\Master\Connection;

use App\Http\Controllers\Controller;
use App\Models\Master\Sellers;
use App\Models\Master\SellerPlan;
use App\Models\Master\UserSellers;
use App\Models\Tally\Tyconnections;
use App\Models\Tally\Tycompanies;
use Illuminate\Http\Request;
use App\Helpers\Helper;
use View;
use Auth;
use Log;
use Redirect;
use Response;

class TallyConnectionController extends Controller
{
	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));
            }

            $tallyConnected = Tyconnections::checkTallyConnected($seller_id, $module);
            $settingUrl = route('tlsettings', array('seller_id'=> $seller_id_enc));

            if($request->get('downloadFile') == 'yes'){
                return View::make('tally/connection/connect')->with('seller_id',$seller_id_enc)->with('seller_details',$sellerData)->with('module',$module)->with('tallyConnected', $tallyConnected)->with('settingUrl', $settingUrl)->with('downloadFile', 'yes');
            } else if($tallyConnected == 'connected'){
                return Redirect::to($settingUrl);
            } else if($tallyConnected == 'updatecompany'){
                $companyList = Tycompanies::getCompanyList($seller_id, $module);
                $tyConnection = Tyconnections::where('seller_id',$seller_id)->where('module', $module)->where('status','Active')->first();
                return View::make('tally/connection/updatecompany')->with('seller_id',$seller_id_enc)->with('seller_details',$sellerData)->with('module',$module)->with('tallyConnected', $tyConnection)->with('settingUrl', $settingUrl)->with('companyList', $companyList);
            } else if($tallyConnected == 'tldatacheck'){
                return View::make('tally/connection/tldatacheck')->with('seller_id',$seller_id_enc)->with('seller_details',$sellerData)->with('module',$module)->with('tallyConnected', $tallyConnected)->with('settingUrl', $settingUrl);
            } else {
                return View::make('tally/connection/connect')->with('seller_id',$seller_id_enc)->with('seller_details',$sellerData)->with('module',$module)->with('tallyConnected', $tallyConnected)->with('settingUrl', $settingUrl);
            }
        } else {
        	return redirect()->route('sellers');
        }
    }

    public function checkTallyConnection(Request $request){

        $seller_id = Helper::encryptor('decrypt',$request->get('seller_id'));
        $sellerData = Sellers::getSellerData('id', $seller_id);
        if(!empty($sellerData)){
            $tlConnected = Tyconnections::checkTallyConnected($seller_id, $sellerData->marketplace_name);
            if(!empty($tlConnected)){
                if($tlConnected == 'connected'){
                    return Response::json(array(
                        'success' => true,
                        'data' => $tlConnected,
                        'message' => 'Connection Successful.'
                    ), 200);
                } else if($tlConnected == 'updatecompany'){
                    return Response::json(array(
                        'success' => false,
                        'data' => $tlConnected,
                        'message' => 'Setup tally company',
                    ), 200);
                }
            } else {
                return Response::json(array(
                    'success' => false,
                    'data' => '',
                    'message' => 'Not set .PTG file in webconnector.'
                ), 200);
            }
        }
        return Response::json(array(
            'success' => false,
            'data' => '',
            'message' => 'Not connected.'
        ), 200);
    }

    public function generatePtgFile(Request $request){

        $seller_id = Helper::encryptor('decrypt', $request->get('seller_id'));
        $sellerData = Sellers::getSellerData('id', $seller_id);
        if(!empty($sellerData)){

            $userData = UserSellers::where('seller_id', $seller_id)->where('role', 'Owner')->where('status', 'Active')->first();
            $username = sprintf('%06s', $userData->user_id).'-'.@sprintf('%06s', $seller_id);
            $password = Helper::pwGenerator();
            //$url = config("app.TALLY_API_DOMAIN_URL")."/connect";
            $url = config('tallyconstant.apiUrls.connect');

            if(!empty($request->get('downloadFile')) && $request->get('downloadFile') == "yes"){
                $tlConnected = Tyconnections::where('seller_id',$seller_id)->where('module', $sellerData->marketplace_name)->where('status','Active')->first();
                $password = $tlConnected->password;
                //$url = config("app.TALLY_API_DOMAIN_URL")."/regeneratefile";
                $url = config('tallyconstant.apiUrls.regenerateFile');
            }
            $postData = array(
                'username' => $username,
                'password' => $password,
                'module' => $sellerData->marketplace_name,
                'companyName' => $sellerData->seller_name,
                'userId' => $userData->user_id,
                'seller_id' => $seller_id,
            );
            
            list($jsonResponse,$error) = $this->postCurlCall($url, array(), $postData);

            /*$jsonResponse = array(
                'success' => true,
                'tally_url' => 'http://192.168.1.177/tallyconlib/public/uploads/tally/000001-000015.ptg',
            );*/

            if(!empty($jsonResponse) && $jsonResponse['success'] == true){
                $urlExp = explode("/", $jsonResponse['tally_url']);
                $fileName = end($urlExp);
                $jsonResponse['fileName'] = $fileName;
                $jsonResponse['content'] = file_get_contents($jsonResponse['tally_url']);
                return $jsonResponse;
            }

        }
        return false;
    }

    public function updateCompany(Request $request){

        $seller_id = Helper::encryptor('decrypt', $request->get('seller_id'));
        $sellerData = Sellers::getSellerData('id', $seller_id);
        if(!empty($sellerData)){
            $expCompany = explode(",", $request->get('companyName'));
            $companyId = $expCompany[0];
            $companyName = $expCompany[1];

            $postData = array(
                'seller_id' => $seller_id,
                'module' => $sellerData->marketplace_name,
                'company_id' => $companyId,
                'company_name' => $companyName,
            );
            //$url = config("app.TALLY_API_DOMAIN_URL")."/updateCompany";
            $url = config('tallyconstant.apiUrls.updateCompany');
            list($jsonResponse,$error) = $this->postCurlCall($url, array(), $postData);
            return $jsonResponse;exit;
        }
        return false;
    }

    public function checkQueueStatus(Request $request)
    {
        $data = [];
        $code = 200;
        try
        {   
            if (!empty($request->seller_id)) {
                $seller_id = Helper::encryptor('decrypt',$request->get('seller_id'));
                $sellerData = Sellers::getSellerData('id', $seller_id);
                if(!empty($sellerData)){
                    $tlConnected = Tyconnections::checkTallyConnected($seller_id, $sellerData->marketplace_name);
                    if(!empty($tlConnected)){
                        if($tlConnected == 'connected'){
                            $curlUrl = config('tallyconstant.apiUrls.createAccounts');
                            $queueCount = 0;
                            
                            if ($queueCount > 0) {
                                $data['success'] = false;
                                $data['message'] = "Queue not processed.";
                            } else {
                                $data['success'] = true;
                                $data['message'] = "Queue is empty.";
                            }
                        }
                    }
                }
            } else {
                $data['success'] = false;
                $data['message'] = "Something went wrong.";
                $code            = 404;
            }
        } catch (\Exception $e) {
            $data['success'] = false;
            $data['message'] = $e->getMessage();
            $code            = 404;
        }
        return Response::json($data, $code);
    }
}
